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