Use new gst_element_class_set_static_metadata()
[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-unit", 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   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   klass->clear = GST_DEBUG_FUNCPTR (gst_multi_handle_sink_clear);
482   klass->get_stats = GST_DEBUG_FUNCPTR (gst_multi_handle_sink_get_stats);
483
484   GST_DEBUG_CATEGORY_INIT (multihandlesink_debug, "multihandlesink", 0,
485       "Multi socket sink");
486 }
487
488 static void
489 gst_multi_handle_sink_init (GstMultiHandleSink * this)
490 {
491   GST_OBJECT_FLAG_UNSET (this, GST_MULTI_HANDLE_SINK_OPEN);
492
493   CLIENTS_LOCK_INIT (this);
494   this->clients = NULL;
495
496   this->bufqueue = g_array_new (FALSE, TRUE, sizeof (GstBuffer *));
497   this->unit_format = DEFAULT_UNIT_FORMAT;
498   this->units_max = DEFAULT_UNITS_MAX;
499   this->units_soft_max = DEFAULT_UNITS_SOFT_MAX;
500   this->time_min = DEFAULT_TIME_MIN;
501   this->bytes_min = DEFAULT_BYTES_MIN;
502   this->buffers_min = DEFAULT_BUFFERS_MIN;
503   this->recover_policy = DEFAULT_RECOVER_POLICY;
504
505   this->timeout = DEFAULT_TIMEOUT;
506   this->def_sync_method = DEFAULT_SYNC_METHOD;
507
508   this->def_burst_format = DEFAULT_BURST_FORMAT;
509   this->def_burst_value = DEFAULT_BURST_VALUE;
510
511   this->qos_dscp = DEFAULT_QOS_DSCP;
512
513   this->resend_streamheader = DEFAULT_RESEND_STREAMHEADER;
514 }
515
516 static void
517 gst_multi_handle_sink_finalize (GObject * object)
518 {
519   GstMultiHandleSink *this;
520
521   this = GST_MULTI_HANDLE_SINK (object);
522
523   CLIENTS_LOCK_CLEAR (this);
524   g_array_free (this->bufqueue, TRUE);
525   g_hash_table_destroy (this->handle_hash);
526
527   G_OBJECT_CLASS (parent_class)->finalize (object);
528 }
529
530 gint
531 gst_multi_handle_sink_setup_dscp_client (GstMultiHandleSink * sink,
532     GstMultiHandleClient * client)
533 {
534 #ifndef IP_TOS
535   return 0;
536 #else
537   gint tos;
538   gint ret;
539   int fd;
540   union gst_sockaddr
541   {
542     struct sockaddr sa;
543     struct sockaddr_in6 sa_in6;
544     struct sockaddr_storage sa_stor;
545   } sa;
546   socklen_t slen = sizeof (sa);
547   gint af;
548   GstMultiHandleSinkClass *mhsinkclass = GST_MULTI_HANDLE_SINK_GET_CLASS (sink);
549
550   /* don't touch */
551   if (sink->qos_dscp < 0)
552     return 0;
553
554   fd = mhsinkclass->client_get_fd (client);
555
556   if ((ret = getsockname (fd, &sa.sa, &slen)) < 0) {
557     GST_DEBUG_OBJECT (sink, "could not get sockname: %s", g_strerror (errno));
558     return ret;
559   }
560
561   af = sa.sa.sa_family;
562
563   /* if this is an IPv4-mapped address then do IPv4 QoS */
564   if (af == AF_INET6) {
565
566     GST_DEBUG_OBJECT (sink, "check IP6 socket");
567     if (IN6_IS_ADDR_V4MAPPED (&(sa.sa_in6.sin6_addr))) {
568       GST_DEBUG_OBJECT (sink, "mapped to IPV4");
569       af = AF_INET;
570     }
571   }
572
573   /* extract and shift 6 bits of the DSCP */
574   tos = (sink->qos_dscp & 0x3f) << 2;
575
576   switch (af) {
577     case AF_INET:
578       ret = setsockopt (fd, IPPROTO_IP, IP_TOS, &tos, sizeof (tos));
579       break;
580     case AF_INET6:
581 #ifdef IPV6_TCLASS
582       ret = setsockopt (fd, IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof (tos));
583       break;
584 #endif
585     default:
586       ret = 0;
587       GST_ERROR_OBJECT (sink, "unsupported AF");
588       break;
589   }
590   if (ret)
591     GST_DEBUG_OBJECT (sink, "could not set DSCP: %s", g_strerror (errno));
592
593   return ret;
594 #endif
595 }
596
597 void
598 gst_multi_handle_sink_client_init (GstMultiHandleClient * client,
599     GstSyncMethod sync_method)
600 {
601   GTimeVal now;
602
603   client->status = GST_CLIENT_STATUS_OK;
604   client->bufpos = -1;
605   client->flushcount = -1;
606   client->bufoffset = 0;
607   client->sending = NULL;
608   client->bytes_sent = 0;
609   client->dropped_buffers = 0;
610   client->avg_queue_size = 0;
611   client->first_buffer_ts = GST_CLOCK_TIME_NONE;
612   client->last_buffer_ts = GST_CLOCK_TIME_NONE;
613   client->new_connection = TRUE;
614   client->sync_method = sync_method;
615   client->currently_removing = FALSE;
616
617   /* update start time */
618   g_get_current_time (&now);
619   client->connect_time = GST_TIMEVAL_TO_TIME (now);
620   client->disconnect_time = 0;
621   /* set last activity time to connect time */
622   client->last_activity_time = client->connect_time;
623 }
624
625 static void
626 gst_multi_handle_sink_setup_dscp (GstMultiHandleSink * mhsink)
627 {
628   GList *clients;
629
630   CLIENTS_LOCK (mhsink);
631   for (clients = mhsink->clients; clients; clients = clients->next) {
632     GstMultiHandleClient *client;
633
634     client = clients->data;
635
636     gst_multi_handle_sink_setup_dscp_client (mhsink, client);
637   }
638   CLIENTS_UNLOCK (mhsink);
639 }
640
641 void
642 gst_multi_handle_sink_add_full (GstMultiHandleSink * sink,
643     GstMultiSinkHandle handle, GstSyncMethod sync_method, GstFormat min_format,
644     guint64 min_value, GstFormat max_format, guint64 max_value)
645 {
646   GstMultiHandleClient *mhclient;
647   GList *clink;
648   GstMultiHandleSink *mhsink = GST_MULTI_HANDLE_SINK (sink);
649   gchar debug[30];
650   GstMultiHandleSinkClass *mhsinkclass =
651       GST_MULTI_HANDLE_SINK_GET_CLASS (mhsink);
652
653   mhsinkclass->handle_debug (handle, debug);
654   GST_DEBUG_OBJECT (sink, "%s adding client, sync_method %d, "
655       "min_format %d, min_value %" G_GUINT64_FORMAT
656       ", max_format %d, max_value %" G_GUINT64_FORMAT, debug,
657       sync_method, min_format, min_value, max_format, max_value);
658
659   /* do limits check if we can */
660   if (min_format == max_format) {
661     if (max_value != -1 && min_value != -1 && max_value < min_value)
662       goto wrong_limits;
663   }
664
665   CLIENTS_LOCK (sink);
666
667   /* check the hash to find a duplicate handle */
668   clink = g_hash_table_lookup (mhsink->handle_hash,
669       mhsinkclass->handle_hash_key (handle));
670   if (clink != NULL)
671     goto duplicate;
672
673   mhclient = mhsinkclass->new_client (mhsink, handle, sync_method);
674
675   /* we can add the handle now */
676   clink = mhsink->clients = g_list_prepend (mhsink->clients, mhclient);
677   g_hash_table_insert (mhsink->handle_hash,
678       mhsinkclass->handle_hash_key (mhclient->handle), clink);
679   mhsink->clients_cookie++;
680
681
682   mhclient->burst_min_format = min_format;
683   mhclient->burst_min_value = min_value;
684   mhclient->burst_max_format = max_format;
685   mhclient->burst_max_value = max_value;
686
687   if (mhsinkclass->hash_changed)
688     mhsinkclass->hash_changed (mhsink);
689
690   CLIENTS_UNLOCK (sink);
691
692   g_signal_emit (G_OBJECT (sink),
693       mhsinkclass->signals[GST_MULTI_HANDLE_SIGNAL_CLIENT_ADDED], 0, handle);
694
695   return;
696
697   /* errors */
698 wrong_limits:
699   {
700     GST_WARNING_OBJECT (sink,
701         "%s wrong values min =%" G_GUINT64_FORMAT ", max=%"
702         G_GUINT64_FORMAT ", unit %d specified when adding client",
703         debug, min_value, max_value, min_format);
704     return;
705   }
706 duplicate:
707   {
708     CLIENTS_UNLOCK (sink);
709     GST_WARNING_OBJECT (sink, "%s duplicate client found, refusing", debug);
710     g_signal_emit (G_OBJECT (sink),
711         mhsinkclass->signals[GST_MULTI_HANDLE_SIGNAL_CLIENT_REMOVED], 0,
712         handle, 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   g_signal_emit (G_OBJECT (sink),
981       mhsinkclass->signals[GST_MULTI_HANDLE_SIGNAL_CLIENT_REMOVED], 0,
982       mhclient->handle, mhclient->status);
983
984   /* lock again before we remove the client completely */
985   CLIENTS_LOCK (sink);
986
987   /* handle cannot be reused in the above signal callback so we can safely
988    * remove it from the hashtable here */
989   if (!g_hash_table_remove (sink->handle_hash,
990           mhsinkclass->handle_hash_key (mhclient->handle))) {
991     GST_WARNING_OBJECT (sink,
992         "%s error removing client %p from hash", mhclient->debug, mhclient);
993   }
994   /* after releasing the lock above, the link could be invalid, more
995    * precisely, the next and prev pointers could point to invalid list
996    * links. One optimisation could be to add a cookie to the linked list
997    * and take a shortcut when it did not change between unlocking and locking
998    * our mutex. For now we just walk the list again. */
999   sink->clients = g_list_remove (sink->clients, mhclient);
1000   sink->clients_cookie++;
1001
1002   if (mhsinkclass->removed)
1003     mhsinkclass->removed (sink, mhclient->handle);
1004
1005   CLIENTS_UNLOCK (sink);
1006
1007   /* and the handle is really gone now */
1008   g_signal_emit (G_OBJECT (sink),
1009       mhsinkclass->signals[GST_MULTI_HANDLE_SIGNAL_CLIENT_HANDLE_REMOVED],
1010       0, mhclient->handle);
1011
1012   if (mhsinkclass->client_free)
1013     mhsinkclass->client_free (mhclient);
1014   g_free (mhclient);
1015
1016   CLIENTS_LOCK (sink);
1017 }
1018
1019 static gboolean
1020 gst_multi_handle_sink_client_queue_buffer (GstMultiHandleSink * mhsink,
1021     GstMultiHandleClient * mhclient, GstBuffer * buffer)
1022 {
1023   GstMultiHandleSink *sink = GST_MULTI_HANDLE_SINK (mhsink);
1024   GstCaps *caps;
1025
1026   /* TRUE: send them if the new caps have them */
1027   gboolean send_streamheader = FALSE;
1028   GstStructure *s;
1029
1030   /* before we queue the buffer, we check if we need to queue streamheader
1031    * buffers (because it's a new client, or because they changed) */
1032   caps = gst_pad_get_current_caps (GST_BASE_SINK_PAD (sink));
1033
1034   if (!mhclient->caps) {
1035     GST_DEBUG_OBJECT (sink,
1036         "%s no previous caps for this client, send streamheader",
1037         mhclient->debug);
1038     send_streamheader = TRUE;
1039     mhclient->caps = gst_caps_ref (caps);
1040   } else {
1041     /* there were previous caps recorded, so compare */
1042     if (!gst_caps_is_equal (caps, mhclient->caps)) {
1043       const GValue *sh1, *sh2;
1044
1045       /* caps are not equal, but could still have the same streamheader */
1046       s = gst_caps_get_structure (caps, 0);
1047       if (!gst_structure_has_field (s, "streamheader")) {
1048         /* no new streamheader, so nothing new to send */
1049         GST_DEBUG_OBJECT (sink,
1050             "%s new caps do not have streamheader, not sending",
1051             mhclient->debug);
1052       } else {
1053         /* there is a new streamheader */
1054         s = gst_caps_get_structure (mhclient->caps, 0);
1055         if (!gst_structure_has_field (s, "streamheader")) {
1056           /* no previous streamheader, so send the new one */
1057           GST_DEBUG_OBJECT (sink,
1058               "%s previous caps did not have streamheader, sending",
1059               mhclient->debug);
1060           send_streamheader = TRUE;
1061         } else {
1062           /* both old and new caps have streamheader set */
1063           if (!mhsink->resend_streamheader) {
1064             GST_DEBUG_OBJECT (sink,
1065                 "%s asked to not resend the streamheader, not sending",
1066                 mhclient->debug);
1067             send_streamheader = FALSE;
1068           } else {
1069             sh1 = gst_structure_get_value (s, "streamheader");
1070             s = gst_caps_get_structure (caps, 0);
1071             sh2 = gst_structure_get_value (s, "streamheader");
1072             if (gst_value_compare (sh1, sh2) != GST_VALUE_EQUAL) {
1073               GST_DEBUG_OBJECT (sink,
1074                   "%s new streamheader different from old, sending",
1075                   mhclient->debug);
1076               send_streamheader = TRUE;
1077             }
1078           }
1079         }
1080       }
1081     }
1082     /* Replace the old caps */
1083     gst_caps_unref (mhclient->caps);
1084     mhclient->caps = gst_caps_ref (caps);
1085   }
1086
1087   if (G_UNLIKELY (send_streamheader)) {
1088     const GValue *sh;
1089     GArray *buffers;
1090     int i;
1091
1092     GST_LOG_OBJECT (sink,
1093         "%s sending streamheader from caps %" GST_PTR_FORMAT,
1094         mhclient->debug, caps);
1095     s = gst_caps_get_structure (caps, 0);
1096     if (!gst_structure_has_field (s, "streamheader")) {
1097       GST_DEBUG_OBJECT (sink,
1098           "%s no new streamheader, so nothing to send", mhclient->debug);
1099     } else {
1100       GST_LOG_OBJECT (sink,
1101           "%s sending streamheader from caps %" GST_PTR_FORMAT,
1102           mhclient->debug, caps);
1103       sh = gst_structure_get_value (s, "streamheader");
1104       g_assert (G_VALUE_TYPE (sh) == GST_TYPE_ARRAY);
1105       buffers = g_value_peek_pointer (sh);
1106       GST_DEBUG_OBJECT (sink, "%d streamheader buffers", buffers->len);
1107       for (i = 0; i < buffers->len; ++i) {
1108         GValue *bufval;
1109         GstBuffer *buffer;
1110
1111         bufval = &g_array_index (buffers, GValue, i);
1112         g_assert (G_VALUE_TYPE (bufval) == GST_TYPE_BUFFER);
1113         buffer = g_value_peek_pointer (bufval);
1114         GST_DEBUG_OBJECT (sink,
1115             "%s queueing streamheader buffer of length %" G_GSIZE_FORMAT,
1116             mhclient->debug, gst_buffer_get_size (buffer));
1117         gst_buffer_ref (buffer);
1118
1119         mhclient->sending = g_slist_append (mhclient->sending, buffer);
1120       }
1121     }
1122   }
1123
1124   gst_caps_unref (caps);
1125   caps = NULL;
1126
1127   GST_LOG_OBJECT (sink, "%s queueing buffer of length %" G_GSIZE_FORMAT,
1128       mhclient->debug, gst_buffer_get_size (buffer));
1129
1130   gst_buffer_ref (buffer);
1131   mhclient->sending = g_slist_append (mhclient->sending, buffer);
1132
1133   return TRUE;
1134 }
1135
1136 static gboolean
1137 is_sync_frame (GstMultiHandleSink * sink, GstBuffer * buffer)
1138 {
1139   if (GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT)) {
1140     return FALSE;
1141   } else if (!GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_HEADER)) {
1142     return TRUE;
1143   }
1144
1145   return FALSE;
1146 }
1147
1148 /* find the keyframe in the list of buffers starting the
1149  * search from @idx. @direction as -1 will search backwards, 
1150  * 1 will search forwards.
1151  * Returns: the index or -1 if there is no keyframe after idx.
1152  */
1153 gint
1154 find_syncframe (GstMultiHandleSink * sink, gint idx, gint direction)
1155 {
1156   gint i, len, result;
1157
1158   /* take length of queued buffers */
1159   len = sink->bufqueue->len;
1160
1161   /* assume we don't find a keyframe */
1162   result = -1;
1163
1164   /* then loop over all buffers to find the first keyframe */
1165   for (i = idx; i >= 0 && i < len; i += direction) {
1166     GstBuffer *buf;
1167
1168     buf = g_array_index (sink->bufqueue, GstBuffer *, i);
1169     if (is_sync_frame (sink, buf)) {
1170       GST_LOG_OBJECT (sink, "found keyframe at %d from %d, direction %d",
1171           i, idx, direction);
1172       result = i;
1173       break;
1174     }
1175   }
1176   return result;
1177 }
1178
1179 /* Get the number of buffers from the buffer queue needed to satisfy
1180  * the maximum max in the configured units.
1181  * If units are not BUFFERS, and there are insufficient buffers in the
1182  * queue to satify the limit, return len(queue) + 1 */
1183 gint
1184 get_buffers_max (GstMultiHandleSink * sink, gint64 max)
1185 {
1186   switch (sink->unit_format) {
1187     case GST_FORMAT_BUFFERS:
1188       return max;
1189     case GST_FORMAT_TIME:
1190     {
1191       GstBuffer *buf;
1192       int i;
1193       int len;
1194       gint64 diff;
1195       GstClockTime first = GST_CLOCK_TIME_NONE;
1196
1197       len = sink->bufqueue->len;
1198
1199       for (i = 0; i < len; i++) {
1200         buf = g_array_index (sink->bufqueue, GstBuffer *, i);
1201         if (GST_BUFFER_TIMESTAMP_IS_VALID (buf)) {
1202           if (first == -1)
1203             first = GST_BUFFER_TIMESTAMP (buf);
1204
1205           diff = first - GST_BUFFER_TIMESTAMP (buf);
1206
1207           if (diff > max)
1208             return i + 1;
1209         }
1210       }
1211       return len + 1;
1212     }
1213     case GST_FORMAT_BYTES:
1214     {
1215       GstBuffer *buf;
1216       int i;
1217       int len;
1218       gint acc = 0;
1219
1220       len = sink->bufqueue->len;
1221
1222       for (i = 0; i < len; i++) {
1223         buf = g_array_index (sink->bufqueue, GstBuffer *, i);
1224         acc += gst_buffer_get_size (buf);
1225
1226         if (acc > max)
1227           return i + 1;
1228       }
1229       return len + 1;
1230     }
1231     default:
1232       return max;
1233   }
1234 }
1235
1236 /* find the positions in the buffer queue where *_min and *_max
1237  * is satisfied
1238  */
1239 /* count the amount of data in the buffers and return the index
1240  * that satifies the given limits.
1241  *
1242  * Returns: index @idx in the buffer queue so that the given limits are
1243  * satisfied. TRUE if all the limits could be satisfied, FALSE if not
1244  * enough data was in the queue.
1245  *
1246  * FIXME, this code might now work if any of the units is in buffers...
1247  */
1248 gboolean
1249 find_limits (GstMultiHandleSink * sink,
1250     gint * min_idx, gint bytes_min, gint buffers_min, gint64 time_min,
1251     gint * max_idx, gint bytes_max, gint buffers_max, gint64 time_max)
1252 {
1253   GstClockTime first, time;
1254   gint i, len, bytes;
1255   gboolean result, max_hit;
1256
1257   /* take length of queue */
1258   len = sink->bufqueue->len;
1259
1260   /* this must hold */
1261   g_assert (len > 0);
1262
1263   GST_LOG_OBJECT (sink,
1264       "bytes_min %d, buffers_min %d, time_min %" GST_TIME_FORMAT
1265       ", bytes_max %d, buffers_max %d, time_max %" GST_TIME_FORMAT, bytes_min,
1266       buffers_min, GST_TIME_ARGS (time_min), bytes_max, buffers_max,
1267       GST_TIME_ARGS (time_max));
1268
1269   /* do the trivial buffer limit test */
1270   if (buffers_min != -1 && len < buffers_min) {
1271     *min_idx = len - 1;
1272     *max_idx = len - 1;
1273     return FALSE;
1274   }
1275
1276   result = FALSE;
1277   /* else count bytes and time */
1278   first = -1;
1279   bytes = 0;
1280   /* unset limits */
1281   *min_idx = -1;
1282   *max_idx = -1;
1283   max_hit = FALSE;
1284
1285   i = 0;
1286   /* loop through the buffers, when a limit is ok, mark it 
1287    * as -1, we have at least one buffer in the queue. */
1288   do {
1289     GstBuffer *buf;
1290
1291     /* if we checked all min limits, update result */
1292     if (bytes_min == -1 && time_min == -1 && *min_idx == -1) {
1293       /* don't go below 0 */
1294       *min_idx = MAX (i - 1, 0);
1295     }
1296     /* if we reached one max limit break out */
1297     if (max_hit) {
1298       /* i > 0 when we get here, we subtract one to get the position
1299        * of the previous buffer. */
1300       *max_idx = i - 1;
1301       /* we have valid complete result if we found a min_idx too */
1302       result = *min_idx != -1;
1303       break;
1304     }
1305     buf = g_array_index (sink->bufqueue, GstBuffer *, i);
1306
1307     bytes += gst_buffer_get_size (buf);
1308
1309     /* take timestamp and save for the base first timestamp */
1310     if ((time = GST_BUFFER_TIMESTAMP (buf)) != -1) {
1311       GST_LOG_OBJECT (sink, "Ts %" GST_TIME_FORMAT " on buffer",
1312           GST_TIME_ARGS (time));
1313       if (first == -1)
1314         first = time;
1315
1316       /* increase max usage if we did not fill enough. Note that
1317        * buffers are sorted from new to old, so the first timestamp is
1318        * bigger than the next one. */
1319       if (time_min != -1 && first - time >= time_min)
1320         time_min = -1;
1321       if (time_max != -1 && first - time >= time_max)
1322         max_hit = TRUE;
1323     } else {
1324       GST_LOG_OBJECT (sink, "No timestamp on buffer");
1325     }
1326     /* time is OK or unknown, check and increase if not enough bytes */
1327     if (bytes_min != -1) {
1328       if (bytes >= bytes_min)
1329         bytes_min = -1;
1330     }
1331     if (bytes_max != -1) {
1332       if (bytes >= bytes_max) {
1333         max_hit = TRUE;
1334       }
1335     }
1336     i++;
1337   }
1338   while (i < len);
1339
1340   /* if we did not hit the max or min limit, set to buffer size */
1341   if (*max_idx == -1)
1342     *max_idx = len - 1;
1343   /* make sure min does not exceed max */
1344   if (*min_idx == -1)
1345     *min_idx = *max_idx;
1346
1347   return result;
1348 }
1349
1350 /* parse the unit/value pair and assign it to the result value of the
1351  * right type, leave the other values untouched 
1352  *
1353  * Returns: FALSE if the unit is unknown or undefined. TRUE otherwise.
1354  */
1355 static gboolean
1356 assign_value (GstFormat format, guint64 value, gint * bytes, gint * buffers,
1357     GstClockTime * time)
1358 {
1359   gboolean res = TRUE;
1360
1361   /* set only the limit of the given format to the given value */
1362   switch (format) {
1363     case GST_FORMAT_BUFFERS:
1364       *buffers = (gint) value;
1365       break;
1366     case GST_FORMAT_TIME:
1367       *time = value;
1368       break;
1369     case GST_FORMAT_BYTES:
1370       *bytes = (gint) value;
1371       break;
1372     case GST_FORMAT_UNDEFINED:
1373     default:
1374       res = FALSE;
1375       break;
1376   }
1377   return res;
1378 }
1379
1380 /* count the index in the buffer queue to satisfy the given unit
1381  * and value pair starting from buffer at index 0.
1382  *
1383  * Returns: TRUE if there was enough data in the queue to satisfy the
1384  * burst values. @idx contains the index in the buffer that contains enough
1385  * data to satisfy the limits or the last buffer in the queue when the
1386  * function returns FALSE.
1387  */
1388 static gboolean
1389 count_burst_unit (GstMultiHandleSink * sink, gint * min_idx,
1390     GstFormat min_format, guint64 min_value, gint * max_idx,
1391     GstFormat max_format, guint64 max_value)
1392 {
1393   gint bytes_min = -1, buffers_min = -1;
1394   gint bytes_max = -1, buffers_max = -1;
1395   GstClockTime time_min = GST_CLOCK_TIME_NONE, time_max = GST_CLOCK_TIME_NONE;
1396
1397   assign_value (min_format, min_value, &bytes_min, &buffers_min, &time_min);
1398   assign_value (max_format, max_value, &bytes_max, &buffers_max, &time_max);
1399
1400   return find_limits (sink, min_idx, bytes_min, buffers_min, time_min,
1401       max_idx, bytes_max, buffers_max, time_max);
1402 }
1403
1404 /* decide where in the current buffer queue this new client should start
1405  * receiving buffers from.
1406  * This function is called whenever a client is connected and has not yet
1407  * received a buffer.
1408  * If this returns -1, it means that we haven't found a good point to
1409  * start streaming from yet, and this function should be called again later
1410  * when more buffers have arrived.
1411  */
1412 gint
1413 gst_multi_handle_sink_new_client_position (GstMultiHandleSink * sink,
1414     GstMultiHandleClient * client)
1415 {
1416   gint result;
1417
1418   GST_DEBUG_OBJECT (sink,
1419       "%s new client, deciding where to start in queue", client->debug);
1420   GST_DEBUG_OBJECT (sink, "queue is currently %d buffers long",
1421       sink->bufqueue->len);
1422   switch (client->sync_method) {
1423     case GST_SYNC_METHOD_LATEST:
1424       /* no syncing, we are happy with whatever the client is going to get */
1425       result = client->bufpos;
1426       GST_DEBUG_OBJECT (sink,
1427           "%s SYNC_METHOD_LATEST, position %d", client->debug, result);
1428       break;
1429     case GST_SYNC_METHOD_NEXT_KEYFRAME:
1430     {
1431       /* if one of the new buffers (between client->bufpos and 0) in the queue
1432        * is a sync point, we can proceed, otherwise we need to keep waiting */
1433       GST_LOG_OBJECT (sink,
1434           "%s new client, bufpos %d, waiting for keyframe",
1435           client->debug, client->bufpos);
1436
1437       result = find_prev_syncframe (sink, client->bufpos);
1438       if (result != -1) {
1439         GST_DEBUG_OBJECT (sink,
1440             "%s SYNC_METHOD_NEXT_KEYFRAME: result %d", client->debug, result);
1441         break;
1442       }
1443
1444       /* client is not on a syncbuffer, need to skip these buffers and
1445        * wait some more */
1446       GST_LOG_OBJECT (sink,
1447           "%s new client, skipping buffer(s), no syncpoint found",
1448           client->debug);
1449       client->bufpos = -1;
1450       break;
1451     }
1452     case GST_SYNC_METHOD_LATEST_KEYFRAME:
1453     {
1454       GST_DEBUG_OBJECT (sink, "%s SYNC_METHOD_LATEST_KEYFRAME", client->debug);
1455
1456       /* for new clients we initially scan the complete buffer queue for
1457        * a sync point when a buffer is added. If we don't find a keyframe,
1458        * we need to wait for the next keyframe and so we change the client's
1459        * sync method to GST_SYNC_METHOD_NEXT_KEYFRAME.
1460        */
1461       result = find_next_syncframe (sink, 0);
1462       if (result != -1) {
1463         GST_DEBUG_OBJECT (sink,
1464             "%s SYNC_METHOD_LATEST_KEYFRAME: result %d", client->debug, result);
1465         break;
1466       }
1467
1468       GST_DEBUG_OBJECT (sink,
1469           "%s SYNC_METHOD_LATEST_KEYFRAME: no keyframe found, "
1470           "switching to SYNC_METHOD_NEXT_KEYFRAME", client->debug);
1471       /* throw client to the waiting state */
1472       client->bufpos = -1;
1473       /* and make client sync to next keyframe */
1474       client->sync_method = GST_SYNC_METHOD_NEXT_KEYFRAME;
1475       break;
1476     }
1477     case GST_SYNC_METHOD_BURST:
1478     {
1479       gboolean ok;
1480       gint max;
1481
1482       /* move to the position where we satisfy the client's burst
1483        * parameters. If we could not satisfy the parameters because there
1484        * is not enough data, we just send what we have (which is in result).
1485        * We use the max value to limit the search
1486        */
1487       ok = count_burst_unit (sink, &result, client->burst_min_format,
1488           client->burst_min_value, &max, client->burst_max_format,
1489           client->burst_max_value);
1490       GST_DEBUG_OBJECT (sink,
1491           "%s SYNC_METHOD_BURST: burst_unit returned %d, result %d",
1492           client->debug, ok, result);
1493
1494       GST_LOG_OBJECT (sink, "min %d, max %d", result, max);
1495
1496       /* we hit the max and it is below the min, use that then */
1497       if (max != -1 && max <= result) {
1498         result = MAX (max - 1, 0);
1499         GST_DEBUG_OBJECT (sink,
1500             "%s SYNC_METHOD_BURST: result above max, taken down to %d",
1501             client->debug, result);
1502       }
1503       break;
1504     }
1505     case GST_SYNC_METHOD_BURST_KEYFRAME:
1506     {
1507       gint min_idx, max_idx;
1508       gint next_syncframe, prev_syncframe;
1509
1510       /* BURST_KEYFRAME:
1511        *
1512        * _always_ start sending a keyframe to the client. We first search
1513        * a keyframe between min/max limits. If there is none, we send it the
1514        * last keyframe before min. If there is none, the behaviour is like
1515        * NEXT_KEYFRAME.
1516        */
1517       /* gather burst limits */
1518       count_burst_unit (sink, &min_idx, client->burst_min_format,
1519           client->burst_min_value, &max_idx, client->burst_max_format,
1520           client->burst_max_value);
1521
1522       GST_LOG_OBJECT (sink, "min %d, max %d", min_idx, max_idx);
1523
1524       /* first find a keyframe after min_idx */
1525       next_syncframe = find_next_syncframe (sink, min_idx);
1526       if (next_syncframe != -1 && next_syncframe < max_idx) {
1527         /* we have a valid keyframe and it's below the max */
1528         GST_LOG_OBJECT (sink, "found keyframe in min/max limits");
1529         result = next_syncframe;
1530         break;
1531       }
1532
1533       /* no valid keyframe, try to find one below min */
1534       prev_syncframe = find_prev_syncframe (sink, min_idx);
1535       if (prev_syncframe != -1) {
1536         GST_WARNING_OBJECT (sink,
1537             "using keyframe below min in BURST_KEYFRAME sync mode");
1538         result = prev_syncframe;
1539         break;
1540       }
1541
1542       /* no prev keyframe or not enough data  */
1543       GST_WARNING_OBJECT (sink,
1544           "no prev keyframe found in BURST_KEYFRAME sync mode, waiting for next");
1545
1546       /* throw client to the waiting state */
1547       client->bufpos = -1;
1548       /* and make client sync to next keyframe */
1549       client->sync_method = GST_SYNC_METHOD_NEXT_KEYFRAME;
1550       result = -1;
1551       break;
1552     }
1553     case GST_SYNC_METHOD_BURST_WITH_KEYFRAME:
1554     {
1555       gint min_idx, max_idx;
1556       gint next_syncframe;
1557
1558       /* BURST_WITH_KEYFRAME:
1559        *
1560        * try to start sending a keyframe to the client. We first search
1561        * a keyframe between min/max limits. If there is none, we send it the
1562        * amount of data up 'till min.
1563        */
1564       /* gather enough data to burst */
1565       count_burst_unit (sink, &min_idx, client->burst_min_format,
1566           client->burst_min_value, &max_idx, client->burst_max_format,
1567           client->burst_max_value);
1568
1569       GST_LOG_OBJECT (sink, "min %d, max %d", min_idx, max_idx);
1570
1571       /* first find a keyframe after min_idx */
1572       next_syncframe = find_next_syncframe (sink, min_idx);
1573       if (next_syncframe != -1 && next_syncframe < max_idx) {
1574         /* we have a valid keyframe and it's below the max */
1575         GST_LOG_OBJECT (sink, "found keyframe in min/max limits");
1576         result = next_syncframe;
1577         break;
1578       }
1579
1580       /* no keyframe, send data from min_idx */
1581       GST_WARNING_OBJECT (sink, "using min in BURST_WITH_KEYFRAME sync mode");
1582
1583       /* make sure we don't go over the max limit */
1584       if (max_idx != -1 && max_idx <= min_idx) {
1585         result = MAX (max_idx - 1, 0);
1586       } else {
1587         result = min_idx;
1588       }
1589
1590       break;
1591     }
1592     default:
1593       g_warning ("unknown sync method %d", client->sync_method);
1594       result = client->bufpos;
1595       break;
1596   }
1597   return result;
1598 }
1599
1600 /* calculate the new position for a client after recovery. This function
1601  * does not update the client position but merely returns the required
1602  * position.
1603  */
1604 gint
1605 gst_multi_handle_sink_recover_client (GstMultiHandleSink * sink,
1606     GstMultiHandleClient * client)
1607 {
1608   gint newbufpos;
1609
1610   GST_WARNING_OBJECT (sink,
1611       "%s client %p is lagging at %d, recover using policy %d",
1612       client->debug, client, client->bufpos, sink->recover_policy);
1613
1614   switch (sink->recover_policy) {
1615     case GST_RECOVER_POLICY_NONE:
1616       /* do nothing, client will catch up or get kicked out when it reaches
1617        * the hard max */
1618       newbufpos = client->bufpos;
1619       break;
1620     case GST_RECOVER_POLICY_RESYNC_LATEST:
1621       /* move to beginning of queue */
1622       newbufpos = -1;
1623       break;
1624     case GST_RECOVER_POLICY_RESYNC_SOFT_LIMIT:
1625       /* move to beginning of soft max */
1626       newbufpos = get_buffers_max (sink, sink->units_soft_max);
1627       break;
1628     case GST_RECOVER_POLICY_RESYNC_KEYFRAME:
1629       /* find keyframe in buffers, we search backwards to find the
1630        * closest keyframe relative to what this client already received. */
1631       newbufpos = MIN (sink->bufqueue->len - 1,
1632           get_buffers_max (sink, sink->units_soft_max) - 1);
1633
1634       while (newbufpos >= 0) {
1635         GstBuffer *buf;
1636
1637         buf = g_array_index (sink->bufqueue, GstBuffer *, newbufpos);
1638         if (is_sync_frame (sink, buf)) {
1639           /* found a buffer that is not a delta unit */
1640           break;
1641         }
1642         newbufpos--;
1643       }
1644       break;
1645     default:
1646       /* unknown recovery procedure */
1647       newbufpos = get_buffers_max (sink, sink->units_soft_max);
1648       break;
1649   }
1650   return newbufpos;
1651 }
1652
1653 /* Queue a buffer on the global queue.
1654  *
1655  * This function adds the buffer to the front of a GArray. It removes the
1656  * tail buffer if the max queue size is exceeded, unreffing the queued buffer.
1657  * Note that unreffing the buffer is not a problem as clients who
1658  * started writing out this buffer will still have a reference to it in the
1659  * mhclient->sending queue.
1660  *
1661  * After adding the buffer, we update all client positions in the queue. If
1662  * a client moves over the soft max, we start the recovery procedure for this
1663  * slow client. If it goes over the hard max, it is put into the slow list
1664  * and removed.
1665  *
1666  * Special care is taken of clients that were waiting for a new buffer (they
1667  * had a position of -1) because they can proceed after adding this new buffer.
1668  * This is done by adding the client back into the write fd_set and signaling
1669  * the select thread that the fd_set changed.
1670  */
1671 static void
1672 gst_multi_handle_sink_queue_buffer (GstMultiHandleSink * mhsink,
1673     GstBuffer * buffer)
1674 {
1675   GList *clients, *next;
1676   gint queuelen;
1677   gboolean hash_changed = FALSE;
1678   gint max_buffer_usage;
1679   gint i;
1680   GTimeVal nowtv;
1681   GstClockTime now;
1682   gint max_buffers, soft_max_buffers;
1683   guint cookie;
1684   GstMultiHandleSink *sink = GST_MULTI_HANDLE_SINK (mhsink);
1685   GstMultiHandleSinkClass *mhsinkclass =
1686       GST_MULTI_HANDLE_SINK_GET_CLASS (mhsink);
1687
1688   g_get_current_time (&nowtv);
1689   now = GST_TIMEVAL_TO_TIME (nowtv);
1690
1691   CLIENTS_LOCK (mhsink);
1692   /* add buffer to queue */
1693   g_array_prepend_val (mhsink->bufqueue, buffer);
1694   queuelen = mhsink->bufqueue->len;
1695
1696   if (mhsink->units_max > 0)
1697     max_buffers = get_buffers_max (mhsink, mhsink->units_max);
1698   else
1699     max_buffers = -1;
1700
1701   if (mhsink->units_soft_max > 0)
1702     soft_max_buffers = get_buffers_max (mhsink, mhsink->units_soft_max);
1703   else
1704     soft_max_buffers = -1;
1705   GST_LOG_OBJECT (sink, "Using max %d, softmax %d", max_buffers,
1706       soft_max_buffers);
1707
1708   /* then loop over the clients and update the positions */
1709   max_buffer_usage = 0;
1710
1711 restart:
1712   cookie = mhsink->clients_cookie;
1713   for (clients = mhsink->clients; clients; clients = next) {
1714     GstMultiHandleClient *mhclient = clients->data;
1715
1716     if (cookie != mhsink->clients_cookie) {
1717       GST_DEBUG_OBJECT (sink, "Clients cookie outdated, restarting");
1718       goto restart;
1719     }
1720
1721     next = g_list_next (clients);
1722
1723     mhclient->bufpos++;
1724     GST_LOG_OBJECT (sink, "%s client %p at position %d",
1725         mhclient->debug, mhclient, mhclient->bufpos);
1726     /* check soft max if needed, recover client */
1727     if (soft_max_buffers > 0 && mhclient->bufpos >= soft_max_buffers) {
1728       gint newpos;
1729
1730       newpos = gst_multi_handle_sink_recover_client (mhsink, mhclient);
1731       if (newpos != mhclient->bufpos) {
1732         mhclient->dropped_buffers += mhclient->bufpos - newpos;
1733         mhclient->bufpos = newpos;
1734         mhclient->discont = TRUE;
1735         GST_INFO_OBJECT (sink, "%s client %p position reset to %d",
1736             mhclient->debug, mhclient, mhclient->bufpos);
1737       } else {
1738         GST_INFO_OBJECT (sink,
1739             "%s client %p not recovering position", mhclient->debug, mhclient);
1740       }
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     /* keep track of maximum buffer usage */
1764     if (mhclient->bufpos > max_buffer_usage) {
1765       max_buffer_usage = mhclient->bufpos;
1766     }
1767   }
1768
1769   /* make sure we respect bytes-min, buffers-min and time-min when they are set */
1770   {
1771     gint usage, max;
1772
1773     GST_LOG_OBJECT (sink,
1774         "extending queue %d to respect time_min %" GST_TIME_FORMAT
1775         ", bytes_min %d, buffers_min %d", max_buffer_usage,
1776         GST_TIME_ARGS (mhsink->time_min), mhsink->bytes_min,
1777         mhsink->buffers_min);
1778
1779     /* get index where the limits are ok, we don't really care if all limits
1780      * are ok, we just queue as much as we need. We also don't compare against
1781      * the max limits. */
1782     find_limits (mhsink, &usage, mhsink->bytes_min, mhsink->buffers_min,
1783         mhsink->time_min, &max, -1, -1, -1);
1784
1785     max_buffer_usage = MAX (max_buffer_usage, usage + 1);
1786     GST_LOG_OBJECT (sink, "extended queue to %d", max_buffer_usage);
1787   }
1788
1789   /* now look for sync points and make sure there is at least one
1790    * sync point in the queue. We only do this if the LATEST_KEYFRAME or 
1791    * BURST_KEYFRAME mode is selected */
1792   if (mhsink->def_sync_method == GST_SYNC_METHOD_LATEST_KEYFRAME ||
1793       mhsink->def_sync_method == GST_SYNC_METHOD_BURST_KEYFRAME) {
1794     /* no point in searching beyond the queue length */
1795     gint limit = queuelen;
1796     GstBuffer *buf;
1797
1798     /* no point in searching beyond the soft-max if any. */
1799     if (soft_max_buffers > 0) {
1800       limit = MIN (limit, soft_max_buffers);
1801     }
1802     GST_LOG_OBJECT (sink,
1803         "extending queue to include sync point, now at %d, limit is %d",
1804         max_buffer_usage, limit);
1805     for (i = 0; i < limit; i++) {
1806       buf = g_array_index (mhsink->bufqueue, GstBuffer *, i);
1807       if (is_sync_frame (mhsink, buf)) {
1808         /* found a sync frame, now extend the buffer usage to
1809          * include at least this frame. */
1810         max_buffer_usage = MAX (max_buffer_usage, i);
1811         break;
1812       }
1813     }
1814     GST_LOG_OBJECT (sink, "max buffer usage is now %d", max_buffer_usage);
1815   }
1816
1817   GST_LOG_OBJECT (sink, "len %d, usage %d", queuelen, max_buffer_usage);
1818
1819   /* nobody is referencing units after max_buffer_usage so we can
1820    * remove them from the queue. We remove them in reverse order as
1821    * this is the most optimal for GArray. */
1822   for (i = queuelen - 1; i > max_buffer_usage; i--) {
1823     GstBuffer *old;
1824
1825     /* queue exceeded max size */
1826     queuelen--;
1827     old = g_array_index (mhsink->bufqueue, GstBuffer *, i);
1828     mhsink->bufqueue = g_array_remove_index (mhsink->bufqueue, i);
1829
1830     /* unref tail buffer */
1831     gst_buffer_unref (old);
1832   }
1833   /* save for stats */
1834   mhsink->buffers_queued = max_buffer_usage;
1835   CLIENTS_UNLOCK (sink);
1836
1837   /* and send a signal to thread if handle_set changed */
1838   if (hash_changed && mhsinkclass->hash_changed) {
1839     mhsinkclass->hash_changed (mhsink);
1840   }
1841 }
1842
1843 static GstFlowReturn
1844 gst_multi_handle_sink_render (GstBaseSink * bsink, GstBuffer * buf)
1845 {
1846   gboolean in_caps;
1847 #if 0
1848   GstCaps *bufcaps, *padcaps;
1849 #endif
1850
1851   GstMultiHandleSink *sink = GST_MULTI_HANDLE_SINK (bsink);
1852
1853   g_return_val_if_fail (GST_OBJECT_FLAG_IS_SET (sink,
1854           GST_MULTI_HANDLE_SINK_OPEN), GST_FLOW_FLUSHING);
1855
1856 #if 0
1857   /* since we check every buffer for streamheader caps, we need to make
1858    * sure every buffer has caps set */
1859   bufcaps = gst_buffer_get_caps (buf);
1860   padcaps = GST_PAD_CAPS (GST_BASE_SINK_PAD (bsink));
1861
1862   /* make sure we have caps on the pad */
1863   if (!padcaps && !bufcaps)
1864     goto no_caps;
1865 #endif
1866
1867   /* get IN_CAPS first, code below might mess with the flags */
1868   in_caps = GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_HEADER);
1869
1870 #if 0
1871   /* stamp the buffer with previous caps if no caps set */
1872   if (!bufcaps) {
1873     if (!gst_buffer_is_writable (buf)) {
1874       /* metadata is not writable, copy will be made and original buffer
1875        * will be unreffed so we need to ref so that we don't lose the
1876        * buffer in the render method. */
1877       gst_buffer_ref (buf);
1878       /* the new buffer is ours only, we keep it out of the scope of this
1879        * function */
1880       buf = gst_buffer_make_writable (buf);
1881     } else {
1882       /* else the metadata is writable, we ref because we keep the buffer
1883        * out of the scope of this method */
1884       gst_buffer_ref (buf);
1885     }
1886     /* buffer metadata is writable now, set the caps */
1887     gst_buffer_set_caps (buf, padcaps);
1888   } else {
1889     gst_caps_unref (bufcaps);
1890
1891     /* since we keep this buffer out of the scope of this method */
1892     gst_buffer_ref (buf);
1893   }
1894 #endif
1895   gst_buffer_ref (buf);
1896
1897   GST_LOG_OBJECT (sink, "received buffer %p, in_caps: %s, offset %"
1898       G_GINT64_FORMAT ", offset_end %" G_GINT64_FORMAT
1899       ", timestamp %" GST_TIME_FORMAT ", duration %" GST_TIME_FORMAT,
1900       buf, in_caps ? "yes" : "no", GST_BUFFER_OFFSET (buf),
1901       GST_BUFFER_OFFSET_END (buf),
1902       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
1903       GST_TIME_ARGS (GST_BUFFER_DURATION (buf)));
1904
1905   /* if we get IN_CAPS buffers, but the previous buffer was not IN_CAPS,
1906    * it means we're getting new streamheader buffers, and we should clear
1907    * the old ones */
1908   if (in_caps && sink->previous_buffer_in_caps == FALSE) {
1909     GST_DEBUG_OBJECT (sink,
1910         "receiving new HEADER buffers, clearing old streamheader");
1911     g_slist_foreach (sink->streamheader, (GFunc) gst_mini_object_unref, NULL);
1912     g_slist_free (sink->streamheader);
1913     sink->streamheader = NULL;
1914   }
1915
1916   /* save the current in_caps */
1917   sink->previous_buffer_in_caps = in_caps;
1918
1919   /* if the incoming buffer is marked as IN CAPS, then we assume for now
1920    * it's a streamheader that needs to be sent to each new client, so we
1921    * put it on our internal list of streamheader buffers.
1922    * FIXME: we could check if the buffer's contents are in fact part of the
1923    * current streamheader.
1924    *
1925    * We don't send the buffer to the client, since streamheaders are sent
1926    * separately when necessary. */
1927   if (in_caps) {
1928     GST_DEBUG_OBJECT (sink, "appending HEADER buffer with length %"
1929         G_GSIZE_FORMAT " to streamheader", gst_buffer_get_size (buf));
1930     sink->streamheader = g_slist_append (sink->streamheader, buf);
1931   } else {
1932     /* queue the buffer, this is a regular data buffer. */
1933     gst_multi_handle_sink_queue_buffer (sink, buf);
1934
1935     sink->bytes_to_serve += gst_buffer_get_size (buf);
1936   }
1937   return GST_FLOW_OK;
1938
1939   /* ERRORS */
1940 #if 0
1941 no_caps:
1942   {
1943     GST_ELEMENT_ERROR (sink, CORE, NEGOTIATION, (NULL),
1944         ("Received first buffer without caps set"));
1945     return GST_FLOW_NOT_NEGOTIATED;
1946   }
1947 #endif
1948 }
1949
1950 static void
1951 gst_multi_handle_sink_set_property (GObject * object, guint prop_id,
1952     const GValue * value, GParamSpec * pspec)
1953 {
1954   GstMultiHandleSink *multihandlesink;
1955
1956   multihandlesink = GST_MULTI_HANDLE_SINK (object);
1957
1958   switch (prop_id) {
1959     case PROP_BUFFERS_MAX:
1960       multihandlesink->units_max = g_value_get_int (value);
1961       break;
1962     case PROP_BUFFERS_SOFT_MAX:
1963       multihandlesink->units_soft_max = g_value_get_int (value);
1964       break;
1965     case PROP_TIME_MIN:
1966       multihandlesink->time_min = g_value_get_int64 (value);
1967       break;
1968     case PROP_BYTES_MIN:
1969       multihandlesink->bytes_min = g_value_get_int (value);
1970       break;
1971     case PROP_BUFFERS_MIN:
1972       multihandlesink->buffers_min = g_value_get_int (value);
1973       break;
1974     case PROP_UNIT_FORMAT:
1975       multihandlesink->unit_format = g_value_get_enum (value);
1976       break;
1977     case PROP_UNITS_MAX:
1978       multihandlesink->units_max = g_value_get_int64 (value);
1979       break;
1980     case PROP_UNITS_SOFT_MAX:
1981       multihandlesink->units_soft_max = g_value_get_int64 (value);
1982       break;
1983     case PROP_RECOVER_POLICY:
1984       multihandlesink->recover_policy = g_value_get_enum (value);
1985       break;
1986     case PROP_TIMEOUT:
1987       multihandlesink->timeout = g_value_get_uint64 (value);
1988       break;
1989     case PROP_SYNC_METHOD:
1990       multihandlesink->def_sync_method = g_value_get_enum (value);
1991       break;
1992     case PROP_BURST_FORMAT:
1993       multihandlesink->def_burst_format = g_value_get_enum (value);
1994       break;
1995     case PROP_BURST_VALUE:
1996       multihandlesink->def_burst_value = g_value_get_uint64 (value);
1997       break;
1998     case PROP_QOS_DSCP:
1999       multihandlesink->qos_dscp = g_value_get_int (value);
2000       gst_multi_handle_sink_setup_dscp (multihandlesink);
2001       break;
2002
2003     case PROP_RESEND_STREAMHEADER:
2004       multihandlesink->resend_streamheader = g_value_get_boolean (value);
2005       break;
2006
2007     default:
2008       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2009       break;
2010   }
2011 }
2012
2013 static void
2014 gst_multi_handle_sink_get_property (GObject * object, guint prop_id,
2015     GValue * value, GParamSpec * pspec)
2016 {
2017   GstMultiHandleSink *multihandlesink;
2018
2019   multihandlesink = GST_MULTI_HANDLE_SINK (object);
2020
2021   switch (prop_id) {
2022     case PROP_BUFFERS_MAX:
2023       g_value_set_int (value, multihandlesink->units_max);
2024       break;
2025     case PROP_BUFFERS_SOFT_MAX:
2026       g_value_set_int (value, multihandlesink->units_soft_max);
2027       break;
2028     case PROP_TIME_MIN:
2029       g_value_set_int64 (value, multihandlesink->time_min);
2030       break;
2031     case PROP_BYTES_MIN:
2032       g_value_set_int (value, multihandlesink->bytes_min);
2033       break;
2034     case PROP_BUFFERS_MIN:
2035       g_value_set_int (value, multihandlesink->buffers_min);
2036       break;
2037     case PROP_BUFFERS_QUEUED:
2038       g_value_set_uint (value, multihandlesink->buffers_queued);
2039       break;
2040     case PROP_BYTES_QUEUED:
2041       g_value_set_uint (value, multihandlesink->bytes_queued);
2042       break;
2043     case PROP_TIME_QUEUED:
2044       g_value_set_uint64 (value, multihandlesink->time_queued);
2045       break;
2046     case PROP_UNIT_FORMAT:
2047       g_value_set_enum (value, multihandlesink->unit_format);
2048       break;
2049     case PROP_UNITS_MAX:
2050       g_value_set_int64 (value, multihandlesink->units_max);
2051       break;
2052     case PROP_UNITS_SOFT_MAX:
2053       g_value_set_int64 (value, multihandlesink->units_soft_max);
2054       break;
2055     case PROP_RECOVER_POLICY:
2056       g_value_set_enum (value, multihandlesink->recover_policy);
2057       break;
2058     case PROP_TIMEOUT:
2059       g_value_set_uint64 (value, multihandlesink->timeout);
2060       break;
2061     case PROP_SYNC_METHOD:
2062       g_value_set_enum (value, multihandlesink->def_sync_method);
2063       break;
2064     case PROP_BYTES_TO_SERVE:
2065       g_value_set_uint64 (value, multihandlesink->bytes_to_serve);
2066       break;
2067     case PROP_BYTES_SERVED:
2068       g_value_set_uint64 (value, multihandlesink->bytes_served);
2069       break;
2070     case PROP_BURST_FORMAT:
2071       g_value_set_enum (value, multihandlesink->def_burst_format);
2072       break;
2073     case PROP_BURST_VALUE:
2074       g_value_set_uint64 (value, multihandlesink->def_burst_value);
2075       break;
2076     case PROP_QOS_DSCP:
2077       g_value_set_int (value, multihandlesink->qos_dscp);
2078       break;
2079     case PROP_RESEND_STREAMHEADER:
2080       g_value_set_boolean (value, multihandlesink->resend_streamheader);
2081       break;
2082     case PROP_NUM_HANDLES:
2083       g_value_set_uint (value,
2084           g_hash_table_size (multihandlesink->handle_hash));
2085       break;
2086     default:
2087       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2088       break;
2089   }
2090 }
2091
2092 /* create a socket for sending to remote machine */
2093 static gboolean
2094 gst_multi_handle_sink_start (GstBaseSink * bsink)
2095 {
2096   GstMultiHandleSinkClass *mhsclass;
2097   GstMultiHandleSink *mhsink;
2098
2099   if (GST_OBJECT_FLAG_IS_SET (bsink, GST_MULTI_HANDLE_SINK_OPEN))
2100     return TRUE;
2101
2102   mhsink = GST_MULTI_HANDLE_SINK (bsink);
2103   mhsclass = GST_MULTI_HANDLE_SINK_GET_CLASS (mhsink);
2104
2105   if (!mhsclass->start_pre (mhsink))
2106     return FALSE;
2107
2108   mhsink->streamheader = NULL;
2109   mhsink->bytes_to_serve = 0;
2110   mhsink->bytes_served = 0;
2111
2112   if (mhsclass->init) {
2113     mhsclass->init (mhsink);
2114   }
2115
2116   mhsink->running = TRUE;
2117
2118   mhsink->thread = g_thread_new ("multihandlesink",
2119       (GThreadFunc) mhsclass->thread, mhsink);
2120
2121   GST_OBJECT_FLAG_SET (bsink, GST_MULTI_HANDLE_SINK_OPEN);
2122
2123   return TRUE;
2124 }
2125
2126 static gboolean
2127 gst_multi_handle_sink_stop (GstBaseSink * bsink)
2128 {
2129   GstMultiHandleSinkClass *mhclass;
2130   GstBuffer *buf;
2131   gint i;
2132   GstMultiHandleSink *mhsink = GST_MULTI_HANDLE_SINK (bsink);
2133
2134   mhclass = GST_MULTI_HANDLE_SINK_GET_CLASS (mhsink);
2135
2136   if (!GST_OBJECT_FLAG_IS_SET (bsink, GST_MULTI_HANDLE_SINK_OPEN))
2137     return TRUE;
2138
2139   mhsink->running = FALSE;
2140
2141   mhclass->stop_pre (mhsink);
2142
2143   if (mhsink->thread) {
2144     GST_DEBUG_OBJECT (mhsink, "joining thread");
2145     g_thread_join (mhsink->thread);
2146     GST_DEBUG_OBJECT (mhsink, "joined thread");
2147     mhsink->thread = NULL;
2148   }
2149
2150   /* free the clients */
2151   mhclass->clear (GST_MULTI_HANDLE_SINK (mhsink));
2152
2153   if (mhsink->streamheader) {
2154     g_slist_foreach (mhsink->streamheader, (GFunc) gst_mini_object_unref, NULL);
2155     g_slist_free (mhsink->streamheader);
2156     mhsink->streamheader = NULL;
2157   }
2158
2159   if (mhclass->close)
2160     mhclass->close (mhsink);
2161
2162   mhclass->stop_post (mhsink);
2163
2164   /* remove all queued buffers */
2165   if (mhsink->bufqueue) {
2166     GST_DEBUG_OBJECT (mhsink, "Emptying bufqueue with %d buffers",
2167         mhsink->bufqueue->len);
2168     for (i = mhsink->bufqueue->len - 1; i >= 0; --i) {
2169       buf = g_array_index (mhsink->bufqueue, GstBuffer *, i);
2170       GST_LOG_OBJECT (mhsink, "Removing buffer %p (%d) with refcount %d", buf,
2171           i, GST_MINI_OBJECT_REFCOUNT (buf));
2172       gst_buffer_unref (buf);
2173       mhsink->bufqueue = g_array_remove_index (mhsink->bufqueue, i);
2174     }
2175     /* freeing the array is done in _finalize */
2176   }
2177   GST_OBJECT_FLAG_UNSET (mhsink, GST_MULTI_HANDLE_SINK_OPEN);
2178
2179   return TRUE;
2180 }
2181
2182 static GstStateChangeReturn
2183 gst_multi_handle_sink_change_state (GstElement * element,
2184     GstStateChange transition)
2185 {
2186   GstMultiHandleSink *sink;
2187   GstStateChangeReturn ret;
2188
2189   sink = GST_MULTI_HANDLE_SINK (element);
2190
2191   /* we disallow changing the state from the streaming thread */
2192   if (g_thread_self () == sink->thread)
2193     return GST_STATE_CHANGE_FAILURE;
2194
2195
2196   switch (transition) {
2197     case GST_STATE_CHANGE_NULL_TO_READY:
2198       if (!gst_multi_handle_sink_start (GST_BASE_SINK (sink)))
2199         goto start_failed;
2200       break;
2201     case GST_STATE_CHANGE_READY_TO_PAUSED:
2202       break;
2203     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
2204       break;
2205     default:
2206       break;
2207   }
2208
2209   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
2210
2211   switch (transition) {
2212     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
2213       break;
2214     case GST_STATE_CHANGE_PAUSED_TO_READY:
2215       break;
2216     case GST_STATE_CHANGE_READY_TO_NULL:
2217       gst_multi_handle_sink_stop (GST_BASE_SINK (sink));
2218       break;
2219     default:
2220       break;
2221   }
2222   return ret;
2223
2224   /* ERRORS */
2225 start_failed:
2226   {
2227     /* error message was posted */
2228     return GST_STATE_CHANGE_FAILURE;
2229   }
2230 }