audiotestsrc: fix rounding errors that might cause segments to be one sample too...
[platform/upstream/gstreamer.git] / gst / tcp / gstmultioutputsink.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-multioutputsink
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 multioutputsink by emitting the #GstMultiOutputSink::add signal. 
30  * For each descriptor added, the #GstMultiOutputSink::client-added signal will be called.
31  *
32  * As of version 0.10.8, a client can also be added with the #GstMultiOutputSink::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 multioutputsink by emitting the #GstMultiOutputSink::remove signal. For
37  * each descriptor removed, the #GstMultiOutputSink::client-removed signal will be called. The
38  * #GstMultiOutputSink::client-removed signal can also be fired when multioutputsink decides that a
39  * client is not active anymore or, depending on the value of the
40  * #GstMultiOutputSink:recover-policy property, if the client is reading too slowly.
41  * In all cases, multioutputsink will never close a file descriptor itself.
42  * The user of multioutputsink is responsible for closing all file descriptors.
43  * This can for example be done in response to the #GstMultiOutputSink::client-fd-removed signal.
44  * Note that multioutputsink still has a reference to the file descriptor when the
45  * #GstMultiOutputSink::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 #GstMultiOutputSink::client-removed signal handler, and you should use the 
48  * #GstMultiOutputSink::client-fd-removed signal to safely close the fd.
49  *
50  * Multioutputsink 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 multioutputsink, the #GstMultiOutputSink: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  * multioutputsink (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  * Multioutputsink 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 #GstMultiOutputSink: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  * Multioutputsink 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  * #GstMultiOutputSink:time-min and #GstMultiOutputSink:bytes-min properties respectively.
74  * These properties are useful if the application adds clients with the 
75  * #GstMultiOutputSink::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 multioutputsink receives data. If the client is reading too
80  * fast, no data will be send to the client until multioutputsink receives more
81  * data. If the client, however, reads too slowly, data for that client will be 
82  * queued up in multioutputsink. Two properties control the amount of data 
83  * (buffers) that is queued in multioutputsink: #GstMultiOutputSink:buffers-max and 
84  * #GstMultiOutputSink:buffers-soft-max. A client that falls behind by
85  * #GstMultiOutputSink:buffers-max is removed from multioutputsink forcibly.
86  *
87  * A client with a lag of at least #GstMultiOutputSink:buffers-soft-max enters the recovery
88  * procedure which is controlled with the #GstMultiOutputSink: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  * multioutputsink 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. Multioutputsink 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 "gstmultioutputsink.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 (multioutputsink_debug);
124 #define GST_CAT_DEFAULT (multioutputsink_debug)
125
126 /* MultiOutputSink signals and args */
127 enum
128 {
129   /* methods */
130   SIGNAL_ADD,
131   SIGNAL_ADD_BURST,
132   SIGNAL_REMOVE,
133   SIGNAL_REMOVE_FLUSH,
134   SIGNAL_CLEAR,
135   SIGNAL_GET_STATS,
136
137   /* signals */
138   SIGNAL_CLIENT_ADDED,
139   SIGNAL_CLIENT_REMOVED,
140   SIGNAL_CLIENT_OUTPUT_REMOVED,
141
142   LAST_SIGNAL
143 };
144
145
146 /* this is really arbitrarily chosen */
147 #define DEFAULT_MODE                    1
148 #define DEFAULT_BUFFERS_MAX             -1
149 #define DEFAULT_BUFFERS_SOFT_MAX        -1
150 #define DEFAULT_TIME_MIN                -1
151 #define DEFAULT_BYTES_MIN               -1
152 #define DEFAULT_BUFFERS_MIN             -1
153 #define DEFAULT_UNIT_TYPE               GST_FORMAT_BUFFERS
154 #define DEFAULT_UNITS_MAX               -1
155 #define DEFAULT_UNITS_SOFT_MAX          -1
156 #define DEFAULT_RECOVER_POLICY          GST_RECOVER_POLICY_NONE
157 #define DEFAULT_TIMEOUT                 0
158 #define DEFAULT_SYNC_METHOD             GST_SYNC_METHOD_LATEST
159
160 #define DEFAULT_BURST_FORMAT            GST_FORMAT_UNDEFINED
161 #define DEFAULT_BURST_VALUE             0
162
163 #define DEFAULT_QOS_DSCP                -1
164 #define DEFAULT_HANDLE_READ             TRUE
165
166 #define DEFAULT_RESEND_STREAMHEADER      TRUE
167
168 enum
169 {
170   PROP_0,
171   PROP_MODE,
172   PROP_BUFFERS_QUEUED,
173   PROP_BYTES_QUEUED,
174   PROP_TIME_QUEUED,
175
176   PROP_UNIT_TYPE,
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_HANDLE_READ,
199
200   PROP_RESEND_STREAMHEADER,
201
202   PROP_NUM_OUTPUTS,
203
204   PROP_LAST
205 };
206
207 #define GST_TYPE_RECOVER_POLICY (gst_multi_output_sink_recover_policy_get_type())
208 static GType
209 gst_multi_output_sink_recover_policy_get_type (void)
210 {
211   static GType recover_policy_type = 0;
212   static const GEnumValue recover_policy[] = {
213     {GST_RECOVER_POLICY_NONE,
214         "Do not try to recover", "none"},
215     {GST_RECOVER_POLICY_RESYNC_LATEST,
216         "Resync client to latest buffer", "latest"},
217     {GST_RECOVER_POLICY_RESYNC_SOFT_LIMIT,
218         "Resync client to soft limit", "soft-limit"},
219     {GST_RECOVER_POLICY_RESYNC_KEYFRAME,
220         "Resync client to most recent keyframe", "keyframe"},
221     {0, NULL, NULL},
222   };
223
224   if (!recover_policy_type) {
225     recover_policy_type =
226         g_enum_register_static ("GstMultiOutputSinkRecoverPolicy",
227         recover_policy);
228   }
229   return recover_policy_type;
230 }
231
232 #define GST_TYPE_SYNC_METHOD (gst_multi_output_sink_sync_method_get_type())
233 static GType
234 gst_multi_output_sink_sync_method_get_type (void)
235 {
236   static GType sync_method_type = 0;
237   static const GEnumValue sync_method[] = {
238     {GST_SYNC_METHOD_LATEST,
239         "Serve starting from the latest buffer", "latest"},
240     {GST_SYNC_METHOD_NEXT_KEYFRAME,
241         "Serve starting from the next keyframe", "next-keyframe"},
242     {GST_SYNC_METHOD_LATEST_KEYFRAME,
243           "Serve everything since the latest keyframe (burst)",
244         "latest-keyframe"},
245     {GST_SYNC_METHOD_BURST, "Serve burst-value data to client", "burst"},
246     {GST_SYNC_METHOD_BURST_KEYFRAME,
247           "Serve burst-value data starting on a keyframe",
248         "burst-keyframe"},
249     {GST_SYNC_METHOD_BURST_WITH_KEYFRAME,
250           "Serve burst-value data preferably starting on a keyframe",
251         "burst-with-keyframe"},
252     {0, NULL, NULL},
253   };
254
255   if (!sync_method_type) {
256     sync_method_type =
257         g_enum_register_static ("GstMultiOutputSinkSyncMethod", sync_method);
258   }
259   return sync_method_type;
260 }
261
262 #define GST_TYPE_CLIENT_STATUS (gst_multi_output_sink_client_status_get_type())
263 static GType
264 gst_multi_output_sink_client_status_get_type (void)
265 {
266   static GType client_status_type = 0;
267   static const GEnumValue client_status[] = {
268     {GST_CLIENT_STATUS_OK, "ok", "ok"},
269     {GST_CLIENT_STATUS_CLOSED, "Closed", "closed"},
270     {GST_CLIENT_STATUS_REMOVED, "Removed", "removed"},
271     {GST_CLIENT_STATUS_SLOW, "Too slow", "slow"},
272     {GST_CLIENT_STATUS_ERROR, "Error", "error"},
273     {GST_CLIENT_STATUS_DUPLICATE, "Duplicate", "duplicate"},
274     {GST_CLIENT_STATUS_FLUSHING, "Flushing", "flushing"},
275     {0, NULL, NULL},
276   };
277
278   if (!client_status_type) {
279     client_status_type =
280         g_enum_register_static ("GstMultiOutputSinkClientStatus",
281         client_status);
282   }
283   return client_status_type;
284 }
285
286 static void gst_multi_output_sink_finalize (GObject * object);
287
288 static void gst_multi_output_sink_remove_client_link (GstMultiOutputSink * sink,
289     GList * link);
290 static gboolean gst_multi_output_sink_output_condition (GstOutput * output,
291     GIOCondition condition, GstMultiOutputSink * sink);
292
293 static GstFlowReturn gst_multi_output_sink_render (GstBaseSink * bsink,
294     GstBuffer * buf);
295 #if 0
296 static gboolean gst_multi_output_sink_unlock (GstBaseSink * bsink);
297 static gboolean gst_multi_output_sink_unlock_stop (GstBaseSink * bsink);
298 #endif
299 static GstStateChangeReturn gst_multi_output_sink_change_state (GstElement *
300     element, GstStateChange transition);
301
302 static void gst_multi_output_sink_set_property (GObject * object, guint prop_id,
303     const GValue * value, GParamSpec * pspec);
304 static void gst_multi_output_sink_get_property (GObject * object, guint prop_id,
305     GValue * value, GParamSpec * pspec);
306
307 #define gst_multi_output_sink_parent_class parent_class
308 G_DEFINE_TYPE (GstMultiOutputSink, gst_multi_output_sink, GST_TYPE_BASE_SINK);
309
310 static guint gst_multi_output_sink_signals[LAST_SIGNAL] = { 0 };
311
312 static void
313 gst_multi_output_sink_class_init (GstMultiOutputSinkClass * klass)
314 {
315   GObjectClass *gobject_class;
316   GstElementClass *gstelement_class;
317   GstBaseSinkClass *gstbasesink_class;
318
319   gobject_class = (GObjectClass *) klass;
320   gstelement_class = (GstElementClass *) klass;
321   gstbasesink_class = (GstBaseSinkClass *) klass;
322
323   gobject_class->set_property = gst_multi_output_sink_set_property;
324   gobject_class->get_property = gst_multi_output_sink_get_property;
325   gobject_class->finalize = gst_multi_output_sink_finalize;
326
327   g_object_class_install_property (gobject_class, PROP_BUFFERS_MAX,
328       g_param_spec_int ("buffers-max", "Buffers max",
329           "max number of buffers to queue for a client (-1 = no limit)", -1,
330           G_MAXINT, DEFAULT_BUFFERS_MAX,
331           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
332   g_object_class_install_property (gobject_class, PROP_BUFFERS_SOFT_MAX,
333       g_param_spec_int ("buffers-soft-max", "Buffers soft max",
334           "Recover client when going over this limit (-1 = no limit)", -1,
335           G_MAXINT, DEFAULT_BUFFERS_SOFT_MAX,
336           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
337
338   g_object_class_install_property (gobject_class, PROP_BYTES_MIN,
339       g_param_spec_int ("bytes-min", "Bytes min",
340           "min number of bytes to queue (-1 = as little as possible)", -1,
341           G_MAXINT, DEFAULT_BYTES_MIN,
342           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
343   g_object_class_install_property (gobject_class, PROP_TIME_MIN,
344       g_param_spec_int64 ("time-min", "Time min",
345           "min number of time to queue (-1 = as little as possible)", -1,
346           G_MAXINT64, DEFAULT_TIME_MIN,
347           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
348   g_object_class_install_property (gobject_class, PROP_BUFFERS_MIN,
349       g_param_spec_int ("buffers-min", "Buffers min",
350           "min number of buffers to queue (-1 = as few as possible)", -1,
351           G_MAXINT, DEFAULT_BUFFERS_MIN,
352           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
353
354   g_object_class_install_property (gobject_class, PROP_UNIT_TYPE,
355       g_param_spec_enum ("unit-type", "Units type",
356           "The unit to measure the max/soft-max/queued properties",
357           GST_TYPE_FORMAT, DEFAULT_UNIT_TYPE,
358           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
359   g_object_class_install_property (gobject_class, PROP_UNITS_MAX,
360       g_param_spec_int64 ("units-max", "Units max",
361           "max number of units to queue (-1 = no limit)", -1, G_MAXINT64,
362           DEFAULT_UNITS_MAX, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
363   g_object_class_install_property (gobject_class, PROP_UNITS_SOFT_MAX,
364       g_param_spec_int64 ("units-soft-max", "Units soft max",
365           "Recover client when going over this limit (-1 = no limit)", -1,
366           G_MAXINT64, DEFAULT_UNITS_SOFT_MAX,
367           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
368
369   g_object_class_install_property (gobject_class, PROP_BUFFERS_QUEUED,
370       g_param_spec_uint ("buffers-queued", "Buffers queued",
371           "Number of buffers currently queued", 0, G_MAXUINT, 0,
372           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
373 #if NOT_IMPLEMENTED
374   g_object_class_install_property (gobject_class, PROP_BYTES_QUEUED,
375       g_param_spec_uint ("bytes-queued", "Bytes queued",
376           "Number of bytes currently queued", 0, G_MAXUINT, 0,
377           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
378   g_object_class_install_property (gobject_class, PROP_TIME_QUEUED,
379       g_param_spec_uint64 ("time-queued", "Time queued",
380           "Number of time currently queued", 0, G_MAXUINT64, 0,
381           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
382 #endif
383
384   g_object_class_install_property (gobject_class, PROP_RECOVER_POLICY,
385       g_param_spec_enum ("recover-policy", "Recover Policy",
386           "How to recover when client reaches the soft max",
387           GST_TYPE_RECOVER_POLICY, DEFAULT_RECOVER_POLICY,
388           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
389   g_object_class_install_property (gobject_class, PROP_TIMEOUT,
390       g_param_spec_uint64 ("timeout", "Timeout",
391           "Maximum inactivity timeout in nanoseconds for a client (0 = no limit)",
392           0, G_MAXUINT64, DEFAULT_TIMEOUT,
393           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
394   g_object_class_install_property (gobject_class, PROP_SYNC_METHOD,
395       g_param_spec_enum ("sync-method", "Sync Method",
396           "How to sync new clients to the stream", GST_TYPE_SYNC_METHOD,
397           DEFAULT_SYNC_METHOD, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
398   g_object_class_install_property (gobject_class, PROP_BYTES_TO_SERVE,
399       g_param_spec_uint64 ("bytes-to-serve", "Bytes to serve",
400           "Number of bytes received to serve to clients", 0, G_MAXUINT64, 0,
401           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
402   g_object_class_install_property (gobject_class, PROP_BYTES_SERVED,
403       g_param_spec_uint64 ("bytes-served", "Bytes served",
404           "Total number of bytes send to all clients", 0, G_MAXUINT64, 0,
405           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
406
407   g_object_class_install_property (gobject_class, PROP_BURST_FORMAT,
408       g_param_spec_enum ("burst-format", "Burst format",
409           "The format of the burst units (when sync-method is burst[[-with]-keyframe])",
410           GST_TYPE_FORMAT, DEFAULT_BURST_FORMAT,
411           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
412   g_object_class_install_property (gobject_class, PROP_BURST_VALUE,
413       g_param_spec_uint64 ("burst-value", "Burst value",
414           "The amount of burst expressed in burst-unit", 0, G_MAXUINT64,
415           DEFAULT_BURST_VALUE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
416
417   g_object_class_install_property (gobject_class, PROP_QOS_DSCP,
418       g_param_spec_int ("qos-dscp", "QoS diff srv code point",
419           "Quality of Service, differentiated services code point (-1 default)",
420           -1, 63, DEFAULT_QOS_DSCP,
421           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
422
423   /**
424    * GstMultiOutputSink::handle-read
425    *
426    * Handle read requests from clients and discard the data.
427    *
428    * Since: 0.10.23
429    */
430   g_object_class_install_property (gobject_class, PROP_HANDLE_READ,
431       g_param_spec_boolean ("handle-read", "Handle Read",
432           "Handle client reads and discard the data",
433           DEFAULT_HANDLE_READ, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
434   /**
435    * GstMultiOutputSink::resend-streamheader
436    *
437    * Resend the streamheaders to existing clients when they change.
438    *
439    * Since: 0.10.23
440    */
441   g_object_class_install_property (gobject_class, PROP_RESEND_STREAMHEADER,
442       g_param_spec_boolean ("resend-streamheader", "Resend streamheader",
443           "Resend the streamheader if it changes in the caps",
444           DEFAULT_RESEND_STREAMHEADER,
445           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
446
447   g_object_class_install_property (gobject_class, PROP_NUM_OUTPUTS,
448       g_param_spec_uint ("num-outputs", "Number of outputs",
449           "The current number of client outputs",
450           0, G_MAXUINT, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
451
452   /**
453    * GstMultiOutputSink::add:
454    * @gstmultioutputsink: the multioutputsink element to emit this signal on
455    * @output:             the output to add to multioutputsink
456    *
457    * Hand the given open output to multioutputsink to write to.
458    */
459   gst_multi_output_sink_signals[SIGNAL_ADD] =
460       g_signal_new ("add", G_TYPE_FROM_CLASS (klass),
461       G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
462       G_STRUCT_OFFSET (GstMultiOutputSinkClass, add), NULL, NULL,
463       g_cclosure_marshal_VOID__OBJECT, G_TYPE_NONE, 1, G_TYPE_OUTPUT);
464   /**
465    * GstMultiOutputSink::add-full:
466    * @gstmultioutputsink: the multioutputsink element to emit this signal on
467    * @output:         the output to add to multioutputsink
468    * @sync:           the sync method to use
469    * @format_min:     the format of @value_min
470    * @value_min:      the minimum amount of data to burst expressed in
471    *                  @format_min units.
472    * @format_max:     the format of @value_max
473    * @value_max:      the maximum amount of data to burst expressed in
474    *                  @format_max units.
475    *
476    * Hand the given open output to multioutputsink to write to and
477    * specify the burst parameters for the new connection.
478    */
479   gst_multi_output_sink_signals[SIGNAL_ADD_BURST] =
480       g_signal_new ("add-full", G_TYPE_FROM_CLASS (klass),
481       G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
482       G_STRUCT_OFFSET (GstMultiOutputSinkClass, add_full), NULL, NULL,
483       gst_tcp_marshal_VOID__OBJECT_ENUM_ENUM_UINT64_ENUM_UINT64, G_TYPE_NONE, 6,
484       G_TYPE_OUTPUT, GST_TYPE_SYNC_METHOD, GST_TYPE_FORMAT, G_TYPE_UINT64,
485       GST_TYPE_FORMAT, G_TYPE_UINT64);
486   /**
487    * GstMultiOutputSink::remove:
488    * @gstmultioutputsink: the multioutputsink element to emit this signal on
489    * @output:             the output to remove from multioutputsink
490    *
491    * Remove the given open output from multioutputsink.
492    */
493   gst_multi_output_sink_signals[SIGNAL_REMOVE] =
494       g_signal_new ("remove", G_TYPE_FROM_CLASS (klass),
495       G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
496       G_STRUCT_OFFSET (GstMultiOutputSinkClass, remove), NULL, NULL,
497       g_cclosure_marshal_VOID__OBJECT, G_TYPE_NONE, 1, G_TYPE_OUTPUT);
498   /**
499    * GstMultiOutputSink::remove-flush:
500    * @gstmultioutputsink: the multioutputsink element to emit this signal on
501    * @output:             the output to remove from multioutputsink
502    *
503    * Remove the given open output from multioutputsink after flushing all
504    * the pending data to the output.
505    */
506   gst_multi_output_sink_signals[SIGNAL_REMOVE_FLUSH] =
507       g_signal_new ("remove-flush", G_TYPE_FROM_CLASS (klass),
508       G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
509       G_STRUCT_OFFSET (GstMultiOutputSinkClass, remove_flush), NULL, NULL,
510       g_cclosure_marshal_VOID__OBJECT, G_TYPE_NONE, 1, G_TYPE_OUTPUT);
511   /**
512    * GstMultiOutputSink::clear:
513    * @gstmultioutputsink: the multioutputsink element to emit this signal on
514    *
515    * Remove all outputs from multioutputsink.  Since multioutputsink did not
516    * open outputs itself, it does not explicitly close the outputs. The application
517    * should do so by connecting to the client-output-removed callback.
518    */
519   gst_multi_output_sink_signals[SIGNAL_CLEAR] =
520       g_signal_new ("clear", G_TYPE_FROM_CLASS (klass),
521       G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
522       G_STRUCT_OFFSET (GstMultiOutputSinkClass, clear), NULL, NULL,
523       g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
524
525   /**
526    * GstMultiOutputSink::get-stats:
527    * @gstmultioutputsink: the multioutputsink element to emit this signal on
528    * @output:             the output to get stats of from multioutputsink
529    *
530    * Get statistics about @output. This function returns a GstStructure.
531    *
532    * Returns: a GstStructure with the statistics. The structure contains
533    *     values that represent: total number of bytes sent, time
534    *     when the client was added, time when the client was
535    *     disconnected/removed, time the client is/was active, last activity
536    *     time (in epoch seconds), number of buffers dropped.
537    *     All times are expressed in nanoseconds (GstClockTime).
538    */
539   gst_multi_output_sink_signals[SIGNAL_GET_STATS] =
540       g_signal_new ("get-stats", G_TYPE_FROM_CLASS (klass),
541       G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
542       G_STRUCT_OFFSET (GstMultiOutputSinkClass, get_stats), NULL, NULL,
543       gst_tcp_marshal_BOXED__OBJECT, GST_TYPE_STRUCTURE, 1, G_TYPE_OUTPUT);
544
545   /**
546    * GstMultiOutputSink::client-added:
547    * @gstmultioutputsink: the multioutputsink element that emitted this signal
548    * @output:             the output that was added to multioutputsink
549    *
550    * The given output was added to multioutputsink. This signal will
551    * be emitted from the streaming thread so application should be prepared
552    * for that.
553    */
554   gst_multi_output_sink_signals[SIGNAL_CLIENT_ADDED] =
555       g_signal_new ("client-added", G_TYPE_FROM_CLASS (klass),
556       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstMultiOutputSinkClass,
557           client_added), NULL, NULL, g_cclosure_marshal_VOID__OBJECT,
558       G_TYPE_NONE, 1, G_TYPE_OBJECT);
559   /**
560    * GstMultiOutputSink::client-removed:
561    * @gstmultioutputsink: the multioutputsink element that emitted this signal
562    * @output:             the output that is to be removed from multioutputsink
563    * @status:             the reason why the client was removed
564    *
565    * The given output is about to be removed from multioutputsink. This
566    * signal will be emitted from the streaming thread so applications should
567    * be prepared for that.
568    *
569    * @gstmultioutputsink still holds a handle to @output so it is possible to call
570    * the get-stats signal from this callback. For the same reason it is
571    * not safe to close() and reuse @output in this callback.
572    */
573   gst_multi_output_sink_signals[SIGNAL_CLIENT_REMOVED] =
574       g_signal_new ("client-removed", G_TYPE_FROM_CLASS (klass),
575       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstMultiOutputSinkClass,
576           client_removed), NULL, NULL, gst_tcp_marshal_VOID__OBJECT_ENUM,
577       G_TYPE_NONE, 2, G_TYPE_INT, GST_TYPE_CLIENT_STATUS);
578   /**
579    * GstMultiOutputSink::client-output-removed:
580    * @gstmultioutputsink: the multioutputsink element that emitted this signal
581    * @output:             the output that was removed from multioutputsink
582    *
583    * The given output was removed from multioutputsink. This signal will
584    * be emitted from the streaming thread so applications should be prepared
585    * for that.
586    *
587    * In this callback, @gstmultioutputsink has removed all the information
588    * associated with @output and it is therefore not possible to call get-stats
589    * with @output. It is however safe to close() and reuse @fd in the callback.
590    *
591    * Since: 0.10.7
592    */
593   gst_multi_output_sink_signals[SIGNAL_CLIENT_OUTPUT_REMOVED] =
594       g_signal_new ("client-output-removed", G_TYPE_FROM_CLASS (klass),
595       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstMultiOutputSinkClass,
596           client_output_removed), NULL, NULL, g_cclosure_marshal_VOID__OBJECT,
597       G_TYPE_NONE, 1, G_TYPE_OUTPUT);
598
599   gst_element_class_add_pad_template (gstelement_class,
600       gst_static_pad_template_get (&sinktemplate));
601
602   gst_element_class_set_static_metadata (gstelement_class,
603       "Multi output sink", "Sink/Network",
604       "Send data to multiple outputs",
605       "Thomas Vander Stichele <thomas at apestaart dot org>, "
606       "Wim Taymans <wim@fluendo.com>, "
607       "Sebastian Dröge <sebastian.droege@collabora.co.uk>");
608
609   gstelement_class->change_state =
610       GST_DEBUG_FUNCPTR (gst_multi_output_sink_change_state);
611
612   gstbasesink_class->render = GST_DEBUG_FUNCPTR (gst_multi_output_sink_render);
613 #if 0
614   gstbasesink_class->unlock = GST_DEBUG_FUNCPTR (gst_multi_output_sink_unlock);
615   gstbasesink_class->unlock_stop =
616       GST_DEBUG_FUNCPTR (gst_multi_output_sink_unlock_stop);
617 #endif
618   klass->add = GST_DEBUG_FUNCPTR (gst_multi_output_sink_add);
619   klass->add_full = GST_DEBUG_FUNCPTR (gst_multi_output_sink_add_full);
620   klass->remove = GST_DEBUG_FUNCPTR (gst_multi_output_sink_remove);
621   klass->remove_flush = GST_DEBUG_FUNCPTR (gst_multi_output_sink_remove_flush);
622   klass->clear = GST_DEBUG_FUNCPTR (gst_multi_output_sink_clear);
623   klass->get_stats = GST_DEBUG_FUNCPTR (gst_multi_output_sink_get_stats);
624
625   GST_DEBUG_CATEGORY_INIT (multioutputsink_debug, "multioutputsink", 0,
626       "Multi output sink");
627 }
628
629 static void
630 gst_multi_output_sink_init (GstMultiOutputSink * this)
631 {
632   GST_OBJECT_FLAG_UNSET (this, GST_MULTI_OUTPUT_SINK_OPEN);
633
634   CLIENTS_LOCK_INIT (this);
635   this->clients = NULL;
636   this->output_hash = g_hash_table_new (g_direct_hash, g_int_equal);
637
638   this->bufqueue = g_array_new (FALSE, TRUE, sizeof (GstBuffer *));
639   this->unit_type = DEFAULT_UNIT_TYPE;
640   this->units_max = DEFAULT_UNITS_MAX;
641   this->units_soft_max = DEFAULT_UNITS_SOFT_MAX;
642   this->time_min = DEFAULT_TIME_MIN;
643   this->bytes_min = DEFAULT_BYTES_MIN;
644   this->buffers_min = DEFAULT_BUFFERS_MIN;
645   this->recover_policy = DEFAULT_RECOVER_POLICY;
646
647   this->timeout = DEFAULT_TIMEOUT;
648   this->def_sync_method = DEFAULT_SYNC_METHOD;
649   this->def_burst_format = DEFAULT_BURST_FORMAT;
650   this->def_burst_value = DEFAULT_BURST_VALUE;
651
652   this->qos_dscp = DEFAULT_QOS_DSCP;
653   this->handle_read = DEFAULT_HANDLE_READ;
654
655   this->resend_streamheader = DEFAULT_RESEND_STREAMHEADER;
656
657   this->header_flags = 0;
658 #if 0
659   this->cancellable = g_cancellable_new ();
660 #endif
661 }
662
663 static void
664 gst_multi_output_sink_finalize (GObject * object)
665 {
666   GstMultiOutputSink *this;
667
668   this = GST_MULTI_OUTPUT_SINK (object);
669
670   CLIENTS_LOCK_CLEAR (this);
671   g_hash_table_destroy (this->output_hash);
672   g_array_free (this->bufqueue, TRUE);
673
674   if (this->cancellable) {
675     g_object_unref (this->cancellable);
676     this->cancellable = NULL;
677   }
678
679   G_OBJECT_CLASS (parent_class)->finalize (object);
680 }
681
682 static gint
683 setup_dscp_client (GstMultiOutputSink * sink, GstOutputClient * client)
684 {
685 #ifndef IP_TOS
686   return 0;
687 #else
688   gint tos;
689   gint ret;
690   int fd;
691   union gst_sockaddr
692   {
693     struct sockaddr sa;
694     struct sockaddr_in6 sa_in6;
695     struct sockaddr_storage sa_stor;
696   } sa;
697   socklen_t slen = sizeof (sa);
698   gint af;
699
700   /* don't touch */
701   if (sink->qos_dscp < 0)
702     return 0;
703
704   fd = g_output_get_fd (client->output);
705
706   if ((ret = getsockname (fd, &sa.sa, &slen)) < 0) {
707     GST_DEBUG_OBJECT (sink, "could not get sockname: %s", g_strerror (errno));
708     return ret;
709   }
710
711   af = sa.sa.sa_family;
712
713   /* if this is an IPv4-mapped address then do IPv4 QoS */
714   if (af == AF_INET6) {
715
716     GST_DEBUG_OBJECT (sink, "check IP6 output");
717     if (IN6_IS_ADDR_V4MAPPED (&(sa.sa_in6.sin6_addr))) {
718       GST_DEBUG_OBJECT (sink, "mapped to IPV4");
719       af = AF_INET;
720     }
721   }
722
723   /* extract and shift 6 bits of the DSCP */
724   tos = (sink->qos_dscp & 0x3f) << 2;
725
726   switch (af) {
727     case AF_INET:
728       ret = setsockopt (fd, IPPROTO_IP, IP_TOS, &tos, sizeof (tos));
729       break;
730     case AF_INET6:
731 #ifdef IPV6_TCLASS
732       ret = setsockopt (fd, IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof (tos));
733       break;
734 #endif
735     default:
736       ret = 0;
737       GST_ERROR_OBJECT (sink, "unsupported AF");
738       break;
739   }
740   if (ret)
741     GST_DEBUG_OBJECT (sink, "could not set DSCP: %s", g_strerror (errno));
742
743   return ret;
744 #endif
745 }
746
747 static void
748 setup_dscp (GstMultiOutputSink * sink)
749 {
750   GList *clients;
751
752   CLIENTS_LOCK (sink);
753   for (clients = sink->clients; clients; clients = clients->next) {
754     GstOutputClient *client;
755
756     client = clients->data;
757
758     setup_dscp_client (sink, client);
759   }
760   CLIENTS_UNLOCK (sink);
761 }
762
763 /* "add-full" signal implementation */
764 void
765 gst_multi_output_sink_add_full (GstMultiOutputSink * sink, GstOutput * output,
766     GstSyncMethod sync_method, GstFormat min_format, guint64 min_value,
767     GstFormat max_format, guint64 max_value)
768 {
769   GstOutputClient *client;
770   GList *clink;
771   GTimeVal now;
772
773   GST_DEBUG_OBJECT (sink, "[output %p] adding client, sync_method %d, "
774       "min_format %d, min_value %" G_GUINT64_FORMAT
775       ", max_format %d, max_value %" G_GUINT64_FORMAT, output,
776       sync_method, min_format, min_value, max_format, max_value);
777
778   /* do limits check if we can */
779   if (min_format == max_format) {
780     if (max_value != -1 && min_value != -1 && max_value < min_value)
781       goto wrong_limits;
782   }
783
784   /* create client datastructure */
785   client = g_new0 (GstOutputClient, 1);
786   client->output = G_OUTPUT (g_object_ref (output));
787   client->status = GST_CLIENT_STATUS_OK;
788   client->bufpos = -1;
789   client->flushcount = -1;
790   client->bufoffset = 0;
791   client->sending = NULL;
792   client->bytes_sent = 0;
793   client->dropped_buffers = 0;
794   client->avg_queue_size = 0;
795   client->first_buffer_ts = GST_CLOCK_TIME_NONE;
796   client->last_buffer_ts = GST_CLOCK_TIME_NONE;
797   client->new_connection = TRUE;
798   client->burst_min_format = min_format;
799   client->burst_min_value = min_value;
800   client->burst_max_format = max_format;
801   client->burst_max_value = max_value;
802   client->sync_method = sync_method;
803   client->currently_removing = FALSE;
804
805   /* update start time */
806   g_get_current_time (&now);
807   client->connect_time = GST_TIMEVAL_TO_TIME (now);
808   client->disconnect_time = 0;
809   /* set last activity time to connect time */
810   client->last_activity_time = client->connect_time;
811
812   CLIENTS_LOCK (sink);
813
814   /* check the hash to find a duplicate fd */
815   clink = g_hash_table_lookup (sink->output_hash, output);
816   if (clink != NULL)
817     goto duplicate;
818
819   /* we can add the fd now */
820   clink = sink->clients = g_list_prepend (sink->clients, client);
821   g_hash_table_insert (sink->output_hash, output, clink);
822   sink->clients_cookie++;
823
824   /* set the output to non blocking */
825   g_output_set_blocking (output, FALSE);
826
827   /* we always read from a client */
828   if (sink->main_context) {
829     client->source =
830         g_output_create_source (client->output,
831         G_IO_IN | G_IO_OUT | G_IO_PRI | G_IO_ERR | G_IO_HUP, sink->cancellable);
832     g_source_set_callback (client->source,
833         (GSourceFunc) gst_multi_output_sink_output_condition,
834         gst_object_ref (sink), (GDestroyNotify) gst_object_unref);
835     g_source_attach (client->source, sink->main_context);
836   }
837
838   setup_dscp_client (sink, client);
839
840   CLIENTS_UNLOCK (sink);
841
842   g_signal_emit (G_OBJECT (sink),
843       gst_multi_output_sink_signals[SIGNAL_CLIENT_ADDED], 0, output);
844
845   return;
846
847   /* errors */
848 wrong_limits:
849   {
850     GST_WARNING_OBJECT (sink,
851         "[output %p] wrong values min =%" G_GUINT64_FORMAT ", max=%"
852         G_GUINT64_FORMAT ", format %d specified when adding client", output,
853         min_value, max_value, min_format);
854     return;
855   }
856 duplicate:
857   {
858     client->status = GST_CLIENT_STATUS_DUPLICATE;
859     CLIENTS_UNLOCK (sink);
860     GST_WARNING_OBJECT (sink, "[output %p] duplicate client found, refusing",
861         output);
862     g_signal_emit (G_OBJECT (sink),
863         gst_multi_output_sink_signals[SIGNAL_CLIENT_REMOVED], 0, output,
864         client->status);
865     g_free (client);
866     return;
867   }
868 }
869
870 /* "add" signal implementation */
871 void
872 gst_multi_output_sink_add (GstMultiOutputSink * sink, GstOutput * output)
873 {
874   gst_multi_output_sink_add_full (sink, output, sink->def_sync_method,
875       sink->def_burst_format, sink->def_burst_value, sink->def_burst_format,
876       -1);
877 }
878
879 /* "remove" signal implementation */
880 void
881 gst_multi_output_sink_remove (GstMultiOutputSink * sink, GstOutput * output)
882 {
883   GList *clink;
884
885   GST_DEBUG_OBJECT (sink, "[output %p] removing client", output);
886
887   CLIENTS_LOCK (sink);
888   clink = g_hash_table_lookup (sink->output_hash, output);
889   if (clink != NULL) {
890     GstOutputClient *client = clink->data;
891
892     if (client->status != GST_CLIENT_STATUS_OK) {
893       GST_INFO_OBJECT (sink,
894           "[output %p] Client already disconnecting with status %d",
895           output, client->status);
896       goto done;
897     }
898
899     client->status = GST_CLIENT_STATUS_REMOVED;
900     gst_multi_output_sink_remove_client_link (sink, clink);
901   } else {
902     GST_WARNING_OBJECT (sink, "[output %p] no client with this output found!",
903         output);
904   }
905
906 done:
907   CLIENTS_UNLOCK (sink);
908 }
909
910 /* "remove-flush" signal implementation */
911 void
912 gst_multi_output_sink_remove_flush (GstMultiOutputSink * sink,
913     GstOutput * output)
914 {
915   GList *clink;
916
917   GST_DEBUG_OBJECT (sink, "[output %p] flushing client", output);
918
919   CLIENTS_LOCK (sink);
920   clink = g_hash_table_lookup (sink->output_hash, output);
921   if (clink != NULL) {
922     GstOutputClient *client = clink->data;
923
924     if (client->status != GST_CLIENT_STATUS_OK) {
925       GST_INFO_OBJECT (sink,
926           "[output %p] Client already disconnecting with status %d",
927           output, client->status);
928       goto done;
929     }
930
931     /* take the position of the client as the number of buffers left to flush.
932      * If the client was at position -1, we flush 0 buffers, 0 == flush 1
933      * buffer, etc... */
934     client->flushcount = client->bufpos + 1;
935     /* mark client as flushing. We can not remove the client right away because
936      * it might have some buffers to flush in the ->sending queue. */
937     client->status = GST_CLIENT_STATUS_FLUSHING;
938   } else {
939     GST_WARNING_OBJECT (sink, "[output %p] no client with this fd found!",
940         output);
941   }
942 done:
943   CLIENTS_UNLOCK (sink);
944 }
945
946 /* can be called both through the signal (i.e. from any thread) or when 
947  * stopping, after the writing thread has shut down */
948 void
949 gst_multi_output_sink_clear (GstMultiOutputSink * sink)
950 {
951   GList *clients;
952   guint32 cookie;
953
954   GST_DEBUG_OBJECT (sink, "clearing all clients");
955
956   CLIENTS_LOCK (sink);
957 restart:
958   cookie = sink->clients_cookie;
959   for (clients = sink->clients; clients; clients = clients->next) {
960     GstOutputClient *client;
961
962     if (cookie != sink->clients_cookie) {
963       GST_DEBUG_OBJECT (sink, "cookie changed while removing all clients");
964       goto restart;
965     }
966
967     client = clients->data;
968     client->status = GST_CLIENT_STATUS_REMOVED;
969     gst_multi_output_sink_remove_client_link (sink, clients);
970   }
971
972   CLIENTS_UNLOCK (sink);
973 }
974
975 /* "get-stats" signal implementation
976  */
977 GstStructure *
978 gst_multi_output_sink_get_stats (GstMultiOutputSink * sink, GstOutput * output)
979 {
980   GstOutputClient *client;
981   GstStructure *result = NULL;
982   GList *clink;
983
984   CLIENTS_LOCK (sink);
985   clink = g_hash_table_lookup (sink->output_hash, output);
986   if (clink == NULL)
987     goto noclient;
988
989   client = clink->data;
990   if (client != NULL) {
991     guint64 interval;
992
993     result = gst_structure_new_empty ("multioutputsink-stats");
994
995     if (client->disconnect_time == 0) {
996       GTimeVal nowtv;
997
998       g_get_current_time (&nowtv);
999
1000       interval = GST_TIMEVAL_TO_TIME (nowtv) - client->connect_time;
1001     } else {
1002       interval = client->disconnect_time - client->connect_time;
1003     }
1004
1005     gst_structure_set (result,
1006         "bytes-sent", G_TYPE_UINT64, client->bytes_sent,
1007         "connect-time", G_TYPE_UINT64, client->connect_time,
1008         "disconnect-time", G_TYPE_UINT64, client->disconnect_time,
1009         "connected-duration", G_TYPE_UINT64, interval,
1010         "last-activatity-time", G_TYPE_UINT64, client->last_activity_time,
1011         "dropped-buffers", G_TYPE_UINT64, client->dropped_buffers,
1012         "first-buffer-ts", G_TYPE_UINT64, client->first_buffer_ts,
1013         "last-buffer-ts", G_TYPE_UINT64, client->last_buffer_ts, NULL);
1014   }
1015
1016 noclient:
1017   CLIENTS_UNLOCK (sink);
1018
1019   /* python doesn't like a NULL pointer yet */
1020   if (result == NULL) {
1021     GST_WARNING_OBJECT (sink, "[output %p] no client with this found!", output);
1022     result = gst_structure_new_empty ("multioutputsink-stats");
1023   }
1024
1025   return result;
1026 }
1027
1028 /* should be called with the clientslock held.
1029  * Note that we don't close the fd as we didn't open it in the first
1030  * place. An application should connect to the client-fd-removed signal and
1031  * close the fd itself.
1032  */
1033 static void
1034 gst_multi_output_sink_remove_client_link (GstMultiOutputSink * sink,
1035     GList * link)
1036 {
1037   GstOutput *output;
1038   GTimeVal now;
1039   GstOutputClient *client = link->data;
1040   GstMultiOutputSinkClass *fclass;
1041
1042   fclass = GST_MULTI_OUTPUT_SINK_GET_CLASS (sink);
1043
1044   output = client->output;
1045
1046   if (client->currently_removing) {
1047     GST_WARNING_OBJECT (sink, "[output %p] client is already being removed",
1048         output);
1049     return;
1050   } else {
1051     client->currently_removing = TRUE;
1052   }
1053
1054   /* FIXME: if we keep track of ip we can log it here and signal */
1055   switch (client->status) {
1056     case GST_CLIENT_STATUS_OK:
1057       GST_WARNING_OBJECT (sink, "[output %p] removing client %p for no reason",
1058           output, client);
1059       break;
1060     case GST_CLIENT_STATUS_CLOSED:
1061       GST_DEBUG_OBJECT (sink, "[output %p] removing client %p because of close",
1062           output, client);
1063       break;
1064     case GST_CLIENT_STATUS_REMOVED:
1065       GST_DEBUG_OBJECT (sink,
1066           "[output %p] removing client %p because the app removed it", output,
1067           client);
1068       break;
1069     case GST_CLIENT_STATUS_SLOW:
1070       GST_INFO_OBJECT (sink,
1071           "[output %p] removing client %p because it was too slow", output,
1072           client);
1073       break;
1074     case GST_CLIENT_STATUS_ERROR:
1075       GST_WARNING_OBJECT (sink,
1076           "[output %p] removing client %p because of error", output, client);
1077       break;
1078     case GST_CLIENT_STATUS_FLUSHING:
1079     default:
1080       GST_WARNING_OBJECT (sink,
1081           "[output %p] removing client %p with invalid reason %d", output,
1082           client, client->status);
1083       break;
1084   }
1085
1086   /* FIXME: convert to vfunc to cleanup a client */
1087
1088   fclass->delete_client (sink, client);
1089
1090   g_get_current_time (&now);
1091   client->disconnect_time = GST_TIMEVAL_TO_TIME (now);
1092
1093   /* free client buffers */
1094   g_slist_foreach (client->sending, (GFunc) gst_mini_object_unref, NULL);
1095   g_slist_free (client->sending);
1096   client->sending = NULL;
1097
1098   if (client->caps)
1099     gst_caps_unref (client->caps);
1100   client->caps = NULL;
1101
1102   /* unlock the mutex before signaling because the signal handler
1103    * might query some properties */
1104   CLIENTS_UNLOCK (sink);
1105
1106   g_signal_emit (G_OBJECT (sink),
1107       gst_multi_output_sink_signals[SIGNAL_CLIENT_REMOVED], 0, output,
1108       client->status);
1109
1110   /* lock again before we remove the client completely */
1111   CLIENTS_LOCK (sink);
1112
1113   /* fd cannot be reused in the above signal callback so we can safely
1114    * remove it from the hashtable here */
1115   if (!g_hash_table_remove (sink->output_hash, output)) {
1116     GST_WARNING_OBJECT (sink,
1117         "[output %p] error removing client %p from hash", output, client);
1118   }
1119   /* after releasing the lock above, the link could be invalid, more
1120    * precisely, the next and prev pointers could point to invalid list
1121    * links. One optimisation could be to add a cookie to the linked list
1122    * and take a shortcut when it did not change between unlocking and locking
1123    * our mutex. For now we just walk the list again. */
1124   sink->clients = g_list_remove (sink->clients, client);
1125   sink->clients_cookie++;
1126
1127   if (fclass->removed)
1128     fclass->removed (sink, output);
1129
1130   g_free (client);
1131   CLIENTS_UNLOCK (sink);
1132
1133   /* and the fd is really gone now */
1134   g_signal_emit (G_OBJECT (sink),
1135       gst_multi_output_sink_signals[SIGNAL_CLIENT_OUTPUT_REMOVED], 0, output);
1136   g_object_unref (output);
1137
1138   CLIENTS_LOCK (sink);
1139 }
1140
1141 /* handle a read on a client output,
1142  * which either indicates a close or should be ignored
1143  * returns FALSE if some error occured or the client closed. */
1144 static gboolean
1145 gst_multi_output_sink_handle_client_read (GstMultiOutputSink * sink,
1146     GstOutputClient * client)
1147 {
1148   gboolean ret;
1149   gchar dummy[256];
1150   gssize nread;
1151   GError *err = NULL;
1152   gboolean first = TRUE;
1153
1154   GST_DEBUG_OBJECT (sink, "[output %p] select reports client read",
1155       client->output);
1156
1157   ret = TRUE;
1158
1159   /* just Read 'n' Drop, could also just drop the client as it's not supposed
1160    * to write to us except for closing the output, I guess it's because we
1161    * like to listen to our customers. */
1162   do {
1163     gssize navail;
1164
1165     GST_DEBUG_OBJECT (sink, "[output %p] client wants us to read",
1166         client->output);
1167
1168     navail = g_output_get_available_bytes (client->output);
1169     if (navail < 0)
1170       break;
1171
1172     nread =
1173         g_output_receive (client->output, dummy, MIN (navail, sizeof (dummy)),
1174         sink->cancellable, &err);
1175     if (first && nread == 0) {
1176       /* client sent close, so remove it */
1177       GST_DEBUG_OBJECT (sink, "[output %p] client asked for close, removing",
1178           client->output);
1179       client->status = GST_CLIENT_STATUS_CLOSED;
1180       ret = FALSE;
1181     } else if (nread < 0) {
1182       GST_WARNING_OBJECT (sink, "[output %p] could not read: %s",
1183           client->output, err->message);
1184       client->status = GST_CLIENT_STATUS_ERROR;
1185       ret = FALSE;
1186       break;
1187     }
1188     first = FALSE;
1189   } while (nread > 0);
1190   g_clear_error (&err);
1191
1192   return ret;
1193 }
1194
1195 static gboolean
1196 is_sync_frame (GstMultiOutputSink * sink, GstBuffer * buffer)
1197 {
1198   if (GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT)) {
1199     return FALSE;
1200   } else if (!GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_IN_CAPS)) {
1201     return TRUE;
1202   }
1203
1204   return FALSE;
1205 }
1206
1207 #if 0
1208 /* queue the given buffer for the given client */
1209 static gboolean
1210 gst_multi_output_sink_client_queue_buffer (GstMultiOutputSink * sink,
1211     GstOutputClient * client, GstBuffer * buffer)
1212 {
1213   GstCaps *caps;
1214
1215   /* TRUE: send them if the new caps have them */
1216   gboolean send_streamheader = FALSE;
1217   GstStructure *s;
1218
1219   /* before we queue the buffer, we check if we need to queue streamheader
1220    * buffers (because it's a new client, or because they changed) */
1221   caps = gst_pad_get_current_caps (GST_BASE_SINK_PAD (sink));
1222
1223   if (!client->caps) {
1224     GST_DEBUG_OBJECT (sink,
1225         "[output %p] no previous caps for this client, send streamheader",
1226         client->output);
1227     send_streamheader = TRUE;
1228     client->caps = gst_caps_ref (caps);
1229   } else {
1230     /* there were previous caps recorded, so compare */
1231     if (!gst_caps_is_equal (caps, client->caps)) {
1232       const GValue *sh1, *sh2;
1233
1234       /* caps are not equal, but could still have the same streamheader */
1235       s = gst_caps_get_structure (caps, 0);
1236       if (!gst_structure_has_field (s, "streamheader")) {
1237         /* no new streamheader, so nothing new to send */
1238         GST_DEBUG_OBJECT (sink,
1239             "[output %p] new caps do not have streamheader, not sending",
1240             client->output);
1241       } else {
1242         /* there is a new streamheader */
1243         s = gst_caps_get_structure (client->caps, 0);
1244         if (!gst_structure_has_field (s, "streamheader")) {
1245           /* no previous streamheader, so send the new one */
1246           GST_DEBUG_OBJECT (sink,
1247               "[output %p] previous caps did not have streamheader, sending",
1248               client->output);
1249           send_streamheader = TRUE;
1250         } else {
1251           /* both old and new caps have streamheader set */
1252           if (!sink->resend_streamheader) {
1253             GST_DEBUG_OBJECT (sink,
1254                 "[output %p] asked to not resend the streamheader, not sending",
1255                 client->output);
1256             send_streamheader = FALSE;
1257           } else {
1258             sh1 = gst_structure_get_value (s, "streamheader");
1259             s = gst_caps_get_structure (caps, 0);
1260             sh2 = gst_structure_get_value (s, "streamheader");
1261             if (gst_value_compare (sh1, sh2) != GST_VALUE_EQUAL) {
1262               GST_DEBUG_OBJECT (sink,
1263                   "[output %p] new streamheader different from old, sending",
1264                   client->output);
1265               send_streamheader = TRUE;
1266             }
1267           }
1268         }
1269       }
1270     }
1271     /* Replace the old caps */
1272     gst_caps_unref (client->caps);
1273     client->caps = gst_caps_ref (caps);
1274   }
1275
1276   if (G_UNLIKELY (send_streamheader)) {
1277     const GValue *sh;
1278     GArray *buffers;
1279     int i;
1280
1281     GST_LOG_OBJECT (sink,
1282         "[output %p] sending streamheader from caps %" GST_PTR_FORMAT,
1283         client->output, caps);
1284     s = gst_caps_get_structure (caps, 0);
1285     if (!gst_structure_has_field (s, "streamheader")) {
1286       GST_DEBUG_OBJECT (sink,
1287           "[output %p] no new streamheader, so nothing to send",
1288           client->output);
1289     } else {
1290       GST_LOG_OBJECT (sink,
1291           "[output %p] sending streamheader from caps %" GST_PTR_FORMAT,
1292           client->output, caps);
1293       sh = gst_structure_get_value (s, "streamheader");
1294       g_assert (G_VALUE_TYPE (sh) == GST_TYPE_ARRAY);
1295       buffers = g_value_peek_pointer (sh);
1296       GST_DEBUG_OBJECT (sink, "%d streamheader buffers", buffers->len);
1297       for (i = 0; i < buffers->len; ++i) {
1298         GValue *bufval;
1299         GstBuffer *buffer;
1300
1301         bufval = &g_array_index (buffers, GValue, i);
1302         g_assert (G_VALUE_TYPE (bufval) == GST_TYPE_BUFFER);
1303         buffer = g_value_peek_pointer (bufval);
1304         GST_DEBUG_OBJECT (sink,
1305             "[output %p] queueing streamheader buffer of length %"
1306             G_GSIZE_FORMAT, client->output, gst_buffer_get_size (buffer));
1307         gst_buffer_ref (buffer);
1308
1309         client->sending = g_slist_append (client->sending, buffer);
1310       }
1311     }
1312   }
1313
1314   gst_caps_unref (caps);
1315   caps = NULL;
1316
1317   GST_LOG_OBJECT (sink,
1318       "[output %p] queueing buffer of length %" G_GSIZE_FORMAT, client->output,
1319       gst_buffer_get_size (buffer));
1320
1321   gst_buffer_ref (buffer);
1322   client->sending = g_slist_append (client->sending, buffer);
1323
1324   return TRUE;
1325 }
1326 #endif
1327
1328 /* find the keyframe in the list of buffers starting the
1329  * search from @idx. @direction as -1 will search backwards, 
1330  * 1 will search forwards.
1331  * Returns: the index or -1 if there is no keyframe after idx.
1332  */
1333 static gint
1334 find_syncframe (GstMultiOutputSink * sink, gint idx, gint direction)
1335 {
1336   gint i, len, result;
1337
1338   /* take length of queued buffers */
1339   len = sink->bufqueue->len;
1340
1341   /* assume we don't find a keyframe */
1342   result = -1;
1343
1344   /* then loop over all buffers to find the first keyframe */
1345   for (i = idx; i >= 0 && i < len; i += direction) {
1346     GstBuffer *buf;
1347
1348     buf = g_array_index (sink->bufqueue, GstBuffer *, i);
1349     if (is_sync_frame (sink, buf)) {
1350       GST_LOG_OBJECT (sink, "found keyframe at %d from %d, direction %d",
1351           i, idx, direction);
1352       result = i;
1353       break;
1354     }
1355   }
1356   return result;
1357 }
1358
1359 #define find_next_syncframe(s,i)        find_syncframe(s,i,1)
1360 #define find_prev_syncframe(s,i)        find_syncframe(s,i,-1)
1361
1362 /* Get the number of buffers from the buffer queue needed to satisfy
1363  * the maximum max in the configured units.
1364  * If units are not BUFFERS, and there are insufficient buffers in the
1365  * queue to satify the limit, return len(queue) + 1 */
1366 static gint
1367 get_buffers_max (GstMultiOutputSink * sink, gint64 max)
1368 {
1369   switch (sink->unit_type) {
1370     case GST_FORMAT_BUFFERS:
1371       return max;
1372     case GST_FORMAT_TIME:
1373     {
1374       GstBuffer *buf;
1375       int i;
1376       int len;
1377       gint64 diff;
1378       GstClockTime first = GST_CLOCK_TIME_NONE;
1379
1380       len = sink->bufqueue->len;
1381
1382       for (i = 0; i < len; i++) {
1383         buf = g_array_index (sink->bufqueue, GstBuffer *, i);
1384         if (GST_BUFFER_TIMESTAMP_IS_VALID (buf)) {
1385           if (first == -1)
1386             first = GST_BUFFER_TIMESTAMP (buf);
1387
1388           diff = first - GST_BUFFER_TIMESTAMP (buf);
1389
1390           if (diff > max)
1391             return i + 1;
1392         }
1393       }
1394       return len + 1;
1395     }
1396     case GST_FORMAT_BYTES:
1397     {
1398       GstBuffer *buf;
1399       int i;
1400       int len;
1401       gint acc = 0;
1402
1403       len = sink->bufqueue->len;
1404
1405       for (i = 0; i < len; i++) {
1406         buf = g_array_index (sink->bufqueue, GstBuffer *, i);
1407         acc += gst_buffer_get_size (buf);
1408
1409         if (acc > max)
1410           return i + 1;
1411       }
1412       return len + 1;
1413     }
1414     default:
1415       return max;
1416   }
1417 }
1418
1419 /* find the positions in the buffer queue where *_min and *_max
1420  * is satisfied
1421  */
1422 /* count the amount of data in the buffers and return the index
1423  * that satifies the given limits.
1424  *
1425  * Returns: index @idx in the buffer queue so that the given limits are
1426  * satisfied. TRUE if all the limits could be satisfied, FALSE if not
1427  * enough data was in the queue.
1428  *
1429  * FIXME, this code might now work if any of the units is in buffers...
1430  */
1431 static gboolean
1432 find_limits (GstMultiOutputSink * sink,
1433     gint * min_idx, gint bytes_min, gint buffers_min, gint64 time_min,
1434     gint * max_idx, gint bytes_max, gint buffers_max, gint64 time_max)
1435 {
1436   GstClockTime first, time;
1437   gint i, len, bytes;
1438   gboolean result, max_hit;
1439
1440   /* take length of queue */
1441   len = sink->bufqueue->len;
1442
1443   /* this must hold */
1444   g_assert (len > 0);
1445
1446   GST_LOG_OBJECT (sink,
1447       "bytes_min %d, buffers_min %d, time_min %" GST_TIME_FORMAT
1448       ", bytes_max %d, buffers_max %d, time_max %" GST_TIME_FORMAT, bytes_min,
1449       buffers_min, GST_TIME_ARGS (time_min), bytes_max, buffers_max,
1450       GST_TIME_ARGS (time_max));
1451
1452   /* do the trivial buffer limit test */
1453   if (buffers_min != -1 && len < buffers_min) {
1454     *min_idx = len - 1;
1455     *max_idx = len - 1;
1456     return FALSE;
1457   }
1458
1459   result = FALSE;
1460   /* else count bytes and time */
1461   first = -1;
1462   bytes = 0;
1463   /* unset limits */
1464   *min_idx = -1;
1465   *max_idx = -1;
1466   max_hit = FALSE;
1467
1468   i = 0;
1469   /* loop through the buffers, when a limit is ok, mark it 
1470    * as -1, we have at least one buffer in the queue. */
1471   do {
1472     GstBuffer *buf;
1473
1474     /* if we checked all min limits, update result */
1475     if (bytes_min == -1 && time_min == -1 && *min_idx == -1) {
1476       /* don't go below 0 */
1477       *min_idx = MAX (i - 1, 0);
1478     }
1479     /* if we reached one max limit break out */
1480     if (max_hit) {
1481       /* i > 0 when we get here, we subtract one to get the position
1482        * of the previous buffer. */
1483       *max_idx = i - 1;
1484       /* we have valid complete result if we found a min_idx too */
1485       result = *min_idx != -1;
1486       break;
1487     }
1488     buf = g_array_index (sink->bufqueue, GstBuffer *, i);
1489
1490     bytes += gst_buffer_get_size (buf);
1491
1492     /* take timestamp and save for the base first timestamp */
1493     if ((time = GST_BUFFER_TIMESTAMP (buf)) != -1) {
1494       GST_LOG_OBJECT (sink, "Ts %" GST_TIME_FORMAT " on buffer",
1495           GST_TIME_ARGS (time));
1496       if (first == -1)
1497         first = time;
1498
1499       /* increase max usage if we did not fill enough. Note that
1500        * buffers are sorted from new to old, so the first timestamp is
1501        * bigger than the next one. */
1502       if (time_min != -1 && first - time >= time_min)
1503         time_min = -1;
1504       if (time_max != -1 && first - time >= time_max)
1505         max_hit = TRUE;
1506     } else {
1507       GST_LOG_OBJECT (sink, "No timestamp on buffer");
1508     }
1509     /* time is OK or unknown, check and increase if not enough bytes */
1510     if (bytes_min != -1) {
1511       if (bytes >= bytes_min)
1512         bytes_min = -1;
1513     }
1514     if (bytes_max != -1) {
1515       if (bytes >= bytes_max) {
1516         max_hit = TRUE;
1517       }
1518     }
1519     i++;
1520   }
1521   while (i < len);
1522
1523   /* if we did not hit the max or min limit, set to buffer size */
1524   if (*max_idx == -1)
1525     *max_idx = len - 1;
1526   /* make sure min does not exceed max */
1527   if (*min_idx == -1)
1528     *min_idx = *max_idx;
1529
1530   return result;
1531 }
1532
1533 /* parse the unit/value pair and assign it to the result value of the
1534  * right type, leave the other values untouched 
1535  *
1536  * Returns: FALSE if the unit is unknown or undefined. TRUE otherwise.
1537  */
1538 static gboolean
1539 assign_value (GstFormat format, guint64 value, gint * bytes, gint * buffers,
1540     GstClockTime * time)
1541 {
1542   gboolean res = TRUE;
1543
1544   /* set only the limit of the given format to the given value */
1545   switch (format) {
1546     case GST_FORMAT_BUFFERS:
1547       *buffers = (gint) value;
1548       break;
1549     case GST_FORMAT_TIME:
1550       *time = value;
1551       break;
1552     case GST_FORMAT_BYTES:
1553       *bytes = (gint) value;
1554       break;
1555     case GST_FORMAT_UNDEFINED:
1556     default:
1557       res = FALSE;
1558       break;
1559   }
1560   return res;
1561 }
1562
1563 /* count the index in the buffer queue to satisfy the given unit
1564  * and value pair starting from buffer at index 0.
1565  *
1566  * Returns: TRUE if there was enough data in the queue to satisfy the
1567  * burst values. @idx contains the index in the buffer that contains enough
1568  * data to satisfy the limits or the last buffer in the queue when the
1569  * function returns FALSE.
1570  */
1571 static gboolean
1572 count_burst_unit (GstMultiOutputSink * sink, gint * min_idx,
1573     GstFormat min_format, guint64 min_value, gint * max_idx,
1574     GstFormat max_format, guint64 max_value)
1575 {
1576   gint bytes_min = -1, buffers_min = -1;
1577   gint bytes_max = -1, buffers_max = -1;
1578   GstClockTime time_min = GST_CLOCK_TIME_NONE, time_max = GST_CLOCK_TIME_NONE;
1579
1580   assign_value (min_format, min_value, &bytes_min, &buffers_min, &time_min);
1581   assign_value (max_format, max_value, &bytes_max, &buffers_max, &time_max);
1582
1583   return find_limits (sink, min_idx, bytes_min, buffers_min, time_min,
1584       max_idx, bytes_max, buffers_max, time_max);
1585 }
1586
1587 /* decide where in the current buffer queue this new client should start
1588  * receiving buffers from.
1589  * This function is called whenever a client is connected and has not yet
1590  * received a buffer.
1591  * If this returns -1, it means that we haven't found a good point to
1592  * start streaming from yet, and this function should be called again later
1593  * when more buffers have arrived.
1594  */
1595 static gint
1596 gst_multi_output_sink_new_client (GstMultiOutputSink * sink,
1597     GstOutputClient * client)
1598 {
1599   gint result;
1600
1601   GST_DEBUG_OBJECT (sink,
1602       "[output %p] new client, deciding where to start in queue",
1603       client->output);
1604   GST_DEBUG_OBJECT (sink, "queue is currently %d buffers long",
1605       sink->bufqueue->len);
1606   switch (client->sync_method) {
1607     case GST_SYNC_METHOD_LATEST:
1608       /* no syncing, we are happy with whatever the client is going to get */
1609       result = client->bufpos;
1610       GST_DEBUG_OBJECT (sink,
1611           "[output %p] SYNC_METHOD_LATEST, position %d", client->output,
1612           result);
1613       break;
1614     case GST_SYNC_METHOD_NEXT_KEYFRAME:
1615     {
1616       /* if one of the new buffers (between client->bufpos and 0) in the queue
1617        * is a sync point, we can proceed, otherwise we need to keep waiting */
1618       GST_LOG_OBJECT (sink,
1619           "[output %p] new client, bufpos %d, waiting for keyframe",
1620           client->output, client->bufpos);
1621
1622       result = find_prev_syncframe (sink, client->bufpos);
1623       if (result != -1) {
1624         GST_DEBUG_OBJECT (sink,
1625             "[output %p] SYNC_METHOD_NEXT_KEYFRAME: result %d",
1626             client->output, result);
1627         break;
1628       }
1629
1630       /* client is not on a syncbuffer, need to skip these buffers and
1631        * wait some more */
1632       GST_LOG_OBJECT (sink,
1633           "[output %p] new client, skipping buffer(s), no syncpoint found",
1634           client->output);
1635       client->bufpos = -1;
1636       break;
1637     }
1638     case GST_SYNC_METHOD_LATEST_KEYFRAME:
1639     {
1640       GST_DEBUG_OBJECT (sink,
1641           "[output %p] SYNC_METHOD_LATEST_KEYFRAME", client->output);
1642
1643       /* for new clients we initially scan the complete buffer queue for
1644        * a sync point when a buffer is added. If we don't find a keyframe,
1645        * we need to wait for the next keyframe and so we change the client's
1646        * sync method to GST_SYNC_METHOD_NEXT_KEYFRAME.
1647        */
1648       result = find_next_syncframe (sink, 0);
1649       if (result != -1) {
1650         GST_DEBUG_OBJECT (sink,
1651             "[output %p] SYNC_METHOD_LATEST_KEYFRAME: result %d",
1652             client->output, result);
1653         break;
1654       }
1655
1656       GST_DEBUG_OBJECT (sink,
1657           "[output %p] SYNC_METHOD_LATEST_KEYFRAME: no keyframe found, "
1658           "switching to SYNC_METHOD_NEXT_KEYFRAME", client->output);
1659       /* throw client to the waiting state */
1660       client->bufpos = -1;
1661       /* and make client sync to next keyframe */
1662       client->sync_method = GST_SYNC_METHOD_NEXT_KEYFRAME;
1663       break;
1664     }
1665     case GST_SYNC_METHOD_BURST:
1666     {
1667       gboolean ok;
1668       gint max;
1669
1670       /* move to the position where we satisfy the client's burst
1671        * parameters. If we could not satisfy the parameters because there
1672        * is not enough data, we just send what we have (which is in result).
1673        * We use the max value to limit the search
1674        */
1675       ok = count_burst_unit (sink, &result, client->burst_min_format,
1676           client->burst_min_value, &max, client->burst_max_format,
1677           client->burst_max_value);
1678       GST_DEBUG_OBJECT (sink,
1679           "[output %p] SYNC_METHOD_BURST: burst_unit returned %d, result %d",
1680           client->output, ok, result);
1681
1682       GST_LOG_OBJECT (sink, "min %d, max %d", result, max);
1683
1684       /* we hit the max and it is below the min, use that then */
1685       if (max != -1 && max <= result) {
1686         result = MAX (max - 1, 0);
1687         GST_DEBUG_OBJECT (sink,
1688             "[output %p] SYNC_METHOD_BURST: result above max, taken down to %d",
1689             client->output, result);
1690       }
1691       break;
1692     }
1693     case GST_SYNC_METHOD_BURST_KEYFRAME:
1694     {
1695       gint min_idx, max_idx;
1696       gint next_syncframe, prev_syncframe;
1697
1698       /* BURST_KEYFRAME:
1699        *
1700        * _always_ start sending a keyframe to the client. We first search
1701        * a keyframe between min/max limits. If there is none, we send it the
1702        * last keyframe before min. If there is none, the behaviour is like
1703        * NEXT_KEYFRAME.
1704        */
1705       /* gather burst limits */
1706       count_burst_unit (sink, &min_idx, client->burst_min_format,
1707           client->burst_min_value, &max_idx, client->burst_max_format,
1708           client->burst_max_value);
1709
1710       GST_LOG_OBJECT (sink, "min %d, max %d", min_idx, max_idx);
1711
1712       /* first find a keyframe after min_idx */
1713       next_syncframe = find_next_syncframe (sink, min_idx);
1714       if (next_syncframe != -1 && next_syncframe < max_idx) {
1715         /* we have a valid keyframe and it's below the max */
1716         GST_LOG_OBJECT (sink, "found keyframe in min/max limits");
1717         result = next_syncframe;
1718         break;
1719       }
1720
1721       /* no valid keyframe, try to find one below min */
1722       prev_syncframe = find_prev_syncframe (sink, min_idx);
1723       if (prev_syncframe != -1) {
1724         GST_WARNING_OBJECT (sink,
1725             "using keyframe below min in BURST_KEYFRAME sync mode");
1726         result = prev_syncframe;
1727         break;
1728       }
1729
1730       /* no prev keyframe or not enough data  */
1731       GST_WARNING_OBJECT (sink,
1732           "no prev keyframe found in BURST_KEYFRAME sync mode, waiting for next");
1733
1734       /* throw client to the waiting state */
1735       client->bufpos = -1;
1736       /* and make client sync to next keyframe */
1737       client->sync_method = GST_SYNC_METHOD_NEXT_KEYFRAME;
1738       result = -1;
1739       break;
1740     }
1741     case GST_SYNC_METHOD_BURST_WITH_KEYFRAME:
1742     {
1743       gint min_idx, max_idx;
1744       gint next_syncframe;
1745
1746       /* BURST_WITH_KEYFRAME:
1747        *
1748        * try to start sending a keyframe to the client. We first search
1749        * a keyframe between min/max limits. If there is none, we send it the
1750        * amount of data up 'till min.
1751        */
1752       /* gather enough data to burst */
1753       count_burst_unit (sink, &min_idx, client->burst_min_format,
1754           client->burst_min_value, &max_idx, client->burst_max_format,
1755           client->burst_max_value);
1756
1757       GST_LOG_OBJECT (sink, "min %d, max %d", min_idx, max_idx);
1758
1759       /* first find a keyframe after min_idx */
1760       next_syncframe = find_next_syncframe (sink, min_idx);
1761       if (next_syncframe != -1 && next_syncframe < max_idx) {
1762         /* we have a valid keyframe and it's below the max */
1763         GST_LOG_OBJECT (sink, "found keyframe in min/max limits");
1764         result = next_syncframe;
1765         break;
1766       }
1767
1768       /* no keyframe, send data from min_idx */
1769       GST_WARNING_OBJECT (sink, "using min in BURST_WITH_KEYFRAME sync mode");
1770
1771       /* make sure we don't go over the max limit */
1772       if (max_idx != -1 && max_idx <= min_idx) {
1773         result = MAX (max_idx - 1, 0);
1774       } else {
1775         result = min_idx;
1776       }
1777
1778       break;
1779     }
1780     default:
1781       g_warning ("unknown sync method %d", client->sync_method);
1782       result = client->bufpos;
1783       break;
1784   }
1785   return result;
1786 }
1787
1788 /* Handle a write on a client,
1789  * which indicates a read request from a client.
1790  *
1791  * For each client we maintain a queue of GstBuffers that contain the raw bytes
1792  * we need to send to the client.
1793  *
1794  * We first check to see if we need to send streamheaders. If so, we queue them.
1795  *
1796  * Then we run into the main loop that tries to send as many buffers as
1797  * possible. It will first exhaust the client->sending queue and if the queue
1798  * is empty, it will pick a buffer from the global queue.
1799  *
1800  * Sending the buffers from the client->sending queue is basically writing
1801  * the bytes to the output and maintaining a count of the bytes that were
1802  * sent. When the buffer is completely sent, it is removed from the
1803  * client->sending queue and we try to pick a new buffer for sending.
1804  *
1805  * When the sending returns a partial buffer we stop sending more data as
1806  * the next send operation could block.
1807  *
1808  * This functions returns FALSE if some error occured.
1809  */
1810 static gboolean
1811 gst_multi_output_sink_handle_client_write (GstMultiOutputSink * sink,
1812     GstOutputClient * client)
1813 {
1814   GstOutput *output = client->output;
1815   gboolean more;
1816   gboolean flushing;
1817   GstClockTime now;
1818   GTimeVal nowtv;
1819   GError *err = NULL;
1820
1821   g_get_current_time (&nowtv);
1822   now = GST_TIMEVAL_TO_TIME (nowtv);
1823
1824   flushing = client->status == GST_CLIENT_STATUS_FLUSHING;
1825
1826   more = TRUE;
1827   do {
1828     gint maxsize;
1829
1830     if (!client->sending) {
1831       /* client is not working on a buffer */
1832       if (client->bufpos == -1) {
1833         /* client is too fast, remove from write queue until new buffer is
1834          * available */
1835         if (client->source) {
1836           g_source_destroy (client->source);
1837           g_source_unref (client->source);
1838           client->source = NULL;
1839         }
1840         /* if we flushed out all of the client buffers, we can stop */
1841         if (client->flushcount == 0)
1842           goto flushed;
1843
1844         return TRUE;
1845       } else {
1846         /* client can pick a buffer from the global queue */
1847         GstBuffer *buf;
1848         GstClockTime timestamp;
1849
1850         /* for new connections, we need to find a good spot in the
1851          * bufqueue to start streaming from */
1852         if (client->new_connection && !flushing) {
1853           gint position = gst_multi_output_sink_new_client (sink, client);
1854
1855           if (position >= 0) {
1856             /* we got a valid spot in the queue */
1857             client->new_connection = FALSE;
1858             client->bufpos = position;
1859           } else {
1860             /* cannot send data to this client yet */
1861             if (client->source) {
1862               g_source_destroy (client->source);
1863               g_source_unref (client->source);
1864               client->source = NULL;
1865             }
1866             return TRUE;
1867           }
1868         }
1869
1870         /* we flushed all remaining buffers, no need to get a new one */
1871         if (client->flushcount == 0)
1872           goto flushed;
1873
1874         /* grab buffer */
1875         buf = g_array_index (sink->bufqueue, GstBuffer *, client->bufpos);
1876         client->bufpos--;
1877
1878         /* update stats */
1879         timestamp = GST_BUFFER_TIMESTAMP (buf);
1880         if (client->first_buffer_ts == GST_CLOCK_TIME_NONE)
1881           client->first_buffer_ts = timestamp;
1882         if (timestamp != -1)
1883           client->last_buffer_ts = timestamp;
1884
1885         /* decrease flushcount */
1886         if (client->flushcount != -1)
1887           client->flushcount--;
1888
1889         GST_LOG_OBJECT (sink, "[output %p] client %p at position %d",
1890             output, client, client->bufpos);
1891
1892         /* queueing a buffer will ref it */
1893         gst_multi_output_sink_client_queue_buffer (sink, client, buf);
1894
1895         /* need to start from the first byte for this new buffer */
1896         client->bufoffset = 0;
1897       }
1898     }
1899
1900     /* see if we need to send something */
1901     if (client->sending) {
1902       gssize wrote;
1903       GstBuffer *head;
1904       GstMapInfo map;
1905
1906       /* pick first buffer from list */
1907       head = GST_BUFFER (client->sending->data);
1908
1909       gst_buffer_map (head, &map, GST_MAP_READ);
1910       maxsize = map.size - client->bufoffset;
1911
1912       /* try to write the complete buffer */
1913
1914       wrote =
1915           g_output_send (output, (gchar *) map.data + client->bufoffset,
1916           maxsize, sink->cancellable, &err);
1917       gst_buffer_unmap (head, &map);
1918
1919       if (wrote < 0) {
1920         /* hmm error.. */
1921         if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_CLOSED)) {
1922           goto connection_reset;
1923         } else {
1924           goto write_error;
1925         }
1926       } else {
1927         if (wrote < maxsize) {
1928           /* partial write means that the client cannot read more and we should
1929            * stop sending more */
1930           GST_LOG_OBJECT (sink,
1931               "partial write on %p of %" G_GSSIZE_FORMAT " bytes", output,
1932               wrote);
1933           client->bufoffset += wrote;
1934           more = FALSE;
1935         } else {
1936           /* complete buffer was written, we can proceed to the next one */
1937           client->sending = g_slist_remove (client->sending, head);
1938           gst_buffer_unref (head);
1939           /* make sure we start from byte 0 for the next buffer */
1940           client->bufoffset = 0;
1941         }
1942         /* update stats */
1943         client->bytes_sent += wrote;
1944         client->last_activity_time = now;
1945         sink->bytes_served += wrote;
1946       }
1947     }
1948   } while (more);
1949
1950   return TRUE;
1951
1952   /* ERRORS */
1953 flushed:
1954   {
1955     GST_DEBUG_OBJECT (sink, "[output %p] flushed, removing", output);
1956     client->status = GST_CLIENT_STATUS_REMOVED;
1957     return FALSE;
1958   }
1959 connection_reset:
1960   {
1961     GST_DEBUG_OBJECT (sink, "[output %p] connection reset by peer, removing",
1962         output);
1963     client->status = GST_CLIENT_STATUS_CLOSED;
1964     g_clear_error (&err);
1965     return FALSE;
1966   }
1967 write_error:
1968   {
1969     GST_WARNING_OBJECT (sink,
1970         "[output %p] could not write, removing client: %s", output,
1971         err->message);
1972     g_clear_error (&err);
1973     client->status = GST_CLIENT_STATUS_ERROR;
1974     return FALSE;
1975   }
1976 }
1977
1978 /* calculate the new position for a client after recovery. This function
1979  * does not update the client position but merely returns the required
1980  * position.
1981  */
1982 static gint
1983 gst_multi_output_sink_recover_client (GstMultiOutputSink * sink,
1984     GstOutputClient * client)
1985 {
1986   gint newbufpos;
1987
1988   GST_WARNING_OBJECT (sink,
1989       "[output %p] client %p is lagging at %d, recover using policy %d",
1990       client->output, client, client->bufpos, sink->recover_policy);
1991
1992   switch (sink->recover_policy) {
1993     case GST_RECOVER_POLICY_NONE:
1994       /* do nothing, client will catch up or get kicked out when it reaches
1995        * the hard max */
1996       newbufpos = client->bufpos;
1997       break;
1998     case GST_RECOVER_POLICY_RESYNC_LATEST:
1999       /* move to beginning of queue */
2000       newbufpos = -1;
2001       break;
2002     case GST_RECOVER_POLICY_RESYNC_SOFT_LIMIT:
2003       /* move to beginning of soft max */
2004       newbufpos = get_buffers_max (sink, sink->units_soft_max);
2005       break;
2006     case GST_RECOVER_POLICY_RESYNC_KEYFRAME:
2007       /* find keyframe in buffers, we search backwards to find the
2008        * closest keyframe relative to what this client already received. */
2009       newbufpos = MIN (sink->bufqueue->len - 1,
2010           get_buffers_max (sink, sink->units_soft_max) - 1);
2011
2012       while (newbufpos >= 0) {
2013         GstBuffer *buf;
2014
2015         buf = g_array_index (sink->bufqueue, GstBuffer *, newbufpos);
2016         if (is_sync_frame (sink, buf)) {
2017           /* found a buffer that is not a delta unit */
2018           break;
2019         }
2020         newbufpos--;
2021       }
2022       break;
2023     default:
2024       /* unknown recovery procedure */
2025       newbufpos = get_buffers_max (sink, sink->units_soft_max);
2026       break;
2027   }
2028   return newbufpos;
2029 }
2030
2031 /* Queue a buffer on the global queue.
2032  *
2033  * This function adds the buffer to the front of a GArray. It removes the
2034  * tail buffer if the max queue size is exceeded, unreffing the queued buffer.
2035  * Note that unreffing the buffer is not a problem as clients who
2036  * started writing out this buffer will still have a reference to it in the
2037  * client->sending queue.
2038  *
2039  * After adding the buffer, we update all client positions in the queue. If
2040  * a client moves over the soft max, we start the recovery procedure for this
2041  * slow client. If it goes over the hard max, it is put into the slow list
2042  * and removed.
2043  *
2044  * Special care is taken of clients that were waiting for a new buffer (they
2045  * had a position of -1) because they can proceed after adding this new buffer.
2046  * This is done by adding the client back into the write fd_set and signaling
2047  * the select thread that the fd_set changed.
2048  */
2049 static void
2050 gst_multi_output_sink_queue_buffer (GstMultiOutputSink * sink, GstBuffer * buf)
2051 {
2052   GList *clients, *next;
2053   gint queuelen;
2054   gint max_buffer_usage;
2055   gint i;
2056   GTimeVal nowtv;
2057   GstClockTime now;
2058   gint max_buffers, soft_max_buffers;
2059   guint cookie;
2060
2061   g_get_current_time (&nowtv);
2062   now = GST_TIMEVAL_TO_TIME (nowtv);
2063
2064   CLIENTS_LOCK (sink);
2065   /* add buffer to queue */
2066   gst_buffer_ref (buf);
2067   g_array_prepend_val (sink->bufqueue, buf);
2068   queuelen = sink->bufqueue->len;
2069
2070   if (sink->units_max > 0)
2071     max_buffers = get_buffers_max (sink, sink->units_max);
2072   else
2073     max_buffers = -1;
2074
2075   if (sink->units_soft_max > 0)
2076     soft_max_buffers = get_buffers_max (sink, sink->units_soft_max);
2077   else
2078     soft_max_buffers = -1;
2079   GST_LOG_OBJECT (sink, "Using max %d, softmax %d", max_buffers,
2080       soft_max_buffers);
2081
2082   /* then loop over the clients and update the positions */
2083   max_buffer_usage = 0;
2084
2085 restart:
2086   cookie = sink->clients_cookie;
2087   for (clients = sink->clients; clients; clients = next) {
2088     GstOutputClient *client;
2089
2090     if (cookie != sink->clients_cookie) {
2091       GST_DEBUG_OBJECT (sink, "Clients cookie outdated, restarting");
2092       goto restart;
2093     }
2094
2095     client = clients->data;
2096     next = g_list_next (clients);
2097
2098     client->bufpos++;
2099     GST_LOG_OBJECT (sink, "[output %p] client %p at position %d",
2100         client->output, client, client->bufpos);
2101     /* check soft max if needed, recover client */
2102     if (soft_max_buffers > 0 && client->bufpos >= soft_max_buffers) {
2103       gint newpos;
2104
2105       newpos = gst_multi_output_sink_recover_client (sink, client);
2106       if (newpos != client->bufpos) {
2107         client->dropped_buffers += client->bufpos - newpos;
2108         client->bufpos = newpos;
2109         client->discont = TRUE;
2110         GST_INFO_OBJECT (sink, "[output %p] client %p position reset to %d",
2111             client->output, client, client->bufpos);
2112       } else {
2113         GST_INFO_OBJECT (sink,
2114             "[output %p] client %p not recovering position",
2115             client->output, client);
2116       }
2117     }
2118     /* check hard max and timeout, remove client */
2119     if ((max_buffers > 0 && client->bufpos >= max_buffers) ||
2120         (sink->timeout > 0
2121             && now - client->last_activity_time > sink->timeout)) {
2122       /* remove client */
2123       GST_WARNING_OBJECT (sink, "[output %p] client %p is too slow, removing",
2124           client->output, client);
2125       /* remove the client, the fd set will be cleared and the select thread
2126        * will be signaled */
2127       client->status = GST_CLIENT_STATUS_SLOW;
2128       /* set client to invalid position while being removed */
2129       client->bufpos = -1;
2130       gst_multi_output_sink_remove_client_link (sink, clients);
2131       continue;
2132     } else if (client->bufpos == 0 || client->new_connection) {
2133       /* can send data to this client now. need to signal the select thread that
2134        * the fd_set changed */
2135       if (!client->source) {
2136         client->source =
2137             g_output_create_source (client->output,
2138             G_IO_IN | G_IO_OUT | G_IO_PRI | G_IO_ERR | G_IO_HUP,
2139             sink->cancellable);
2140         g_source_set_callback (client->source,
2141             (GSourceFunc) gst_multi_output_sink_output_condition,
2142             gst_object_ref (sink), (GDestroyNotify) gst_object_unref);
2143         g_source_attach (client->source, sink->main_context);
2144       }
2145     }
2146     /* keep track of maximum buffer usage */
2147     if (client->bufpos > max_buffer_usage) {
2148       max_buffer_usage = client->bufpos;
2149     }
2150   }
2151
2152   /* make sure we respect bytes-min, buffers-min and time-min when they are set */
2153   {
2154     gint usage, max;
2155
2156     GST_LOG_OBJECT (sink,
2157         "extending queue %d to respect time_min %" GST_TIME_FORMAT
2158         ", bytes_min %d, buffers_min %d", max_buffer_usage,
2159         GST_TIME_ARGS (sink->time_min), sink->bytes_min, sink->buffers_min);
2160
2161     /* get index where the limits are ok, we don't really care if all limits
2162      * are ok, we just queue as much as we need. We also don't compare against
2163      * the max limits. */
2164     find_limits (sink, &usage, sink->bytes_min, sink->buffers_min,
2165         sink->time_min, &max, -1, -1, -1);
2166
2167     max_buffer_usage = MAX (max_buffer_usage, usage + 1);
2168     GST_LOG_OBJECT (sink, "extended queue to %d", max_buffer_usage);
2169   }
2170
2171   /* now look for sync points and make sure there is at least one
2172    * sync point in the queue. We only do this if the LATEST_KEYFRAME or 
2173    * BURST_KEYFRAME mode is selected */
2174   if (sink->def_sync_method == GST_SYNC_METHOD_LATEST_KEYFRAME ||
2175       sink->def_sync_method == GST_SYNC_METHOD_BURST_KEYFRAME) {
2176     /* no point in searching beyond the queue length */
2177     gint limit = queuelen;
2178     GstBuffer *buf;
2179
2180     /* no point in searching beyond the soft-max if any. */
2181     if (soft_max_buffers > 0) {
2182       limit = MIN (limit, soft_max_buffers);
2183     }
2184     GST_LOG_OBJECT (sink,
2185         "extending queue to include sync point, now at %d, limit is %d",
2186         max_buffer_usage, limit);
2187     for (i = 0; i < limit; i++) {
2188       buf = g_array_index (sink->bufqueue, GstBuffer *, i);
2189       if (is_sync_frame (sink, buf)) {
2190         /* found a sync frame, now extend the buffer usage to
2191          * include at least this frame. */
2192         max_buffer_usage = MAX (max_buffer_usage, i);
2193         break;
2194       }
2195     }
2196     GST_LOG_OBJECT (sink, "max buffer usage is now %d", max_buffer_usage);
2197   }
2198
2199   GST_LOG_OBJECT (sink, "len %d, usage %d", queuelen, max_buffer_usage);
2200
2201   /* nobody is referencing units after max_buffer_usage so we can
2202    * remove them from the queue. We remove them in reverse order as
2203    * this is the most optimal for GArray. */
2204   for (i = queuelen - 1; i > max_buffer_usage; i--) {
2205     GstBuffer *old;
2206
2207     /* queue exceeded max size */
2208     queuelen--;
2209     old = g_array_index (sink->bufqueue, GstBuffer *, i);
2210     sink->bufqueue = g_array_remove_index (sink->bufqueue, i);
2211
2212     /* unref tail buffer */
2213     gst_buffer_unref (old);
2214   }
2215   /* save for stats */
2216   sink->buffers_queued = max_buffer_usage;
2217   CLIENTS_UNLOCK (sink);
2218 }
2219
2220 /* Handle the clients. This is called when a output becomes ready
2221  * to read or writable. Badly behaving clients are put on a
2222  * garbage list and removed.
2223  */
2224 static gboolean
2225 gst_multi_output_sink_output_condition (GstOutput * output,
2226     GIOCondition condition, GstMultiOutputSink * sink)
2227 {
2228   GList *clink;
2229   GstOutputClient *client;
2230   gboolean ret = TRUE;
2231
2232   CLIENTS_LOCK (sink);
2233   clink = g_hash_table_lookup (sink->output_hash, output);
2234   if (clink == NULL) {
2235     ret = FALSE;
2236     goto done;
2237   }
2238
2239   client = clink->data;
2240
2241   if (client->status != GST_CLIENT_STATUS_FLUSHING
2242       && client->status != GST_CLIENT_STATUS_OK) {
2243     gst_multi_output_sink_remove_client_link (sink, clink);
2244     ret = FALSE;
2245     goto done;
2246   }
2247
2248   if ((condition & G_IO_ERR)) {
2249     GST_WARNING_OBJECT (sink, "Output %p has error", client->output);
2250     client->status = GST_CLIENT_STATUS_ERROR;
2251     gst_multi_output_sink_remove_client_link (sink, clink);
2252     ret = FALSE;
2253     goto done;
2254   } else if ((condition & G_IO_HUP)) {
2255     client->status = GST_CLIENT_STATUS_CLOSED;
2256     gst_multi_output_sink_remove_client_link (sink, clink);
2257     ret = FALSE;
2258     goto done;
2259   } else if ((condition & G_IO_IN) || (condition & G_IO_PRI)) {
2260     /* handle client read */
2261     if (!gst_multi_output_sink_handle_client_read (sink, client)) {
2262       gst_multi_output_sink_remove_client_link (sink, clink);
2263       ret = FALSE;
2264       goto done;
2265     }
2266   } else if ((condition & G_IO_OUT)) {
2267     /* handle client write */
2268     if (!gst_multi_output_sink_handle_client_write (sink, client)) {
2269       gst_multi_output_sink_remove_client_link (sink, clink);
2270       ret = FALSE;
2271       goto done;
2272     }
2273   }
2274
2275 done:
2276   CLIENTS_UNLOCK (sink);
2277
2278   return ret;
2279 }
2280
2281 static gboolean
2282 gst_multi_output_sink_timeout (GstMultiOutputSink * sink)
2283 {
2284   GstClockTime now;
2285   GTimeVal nowtv;
2286   GList *clients;
2287
2288   g_get_current_time (&nowtv);
2289   now = GST_TIMEVAL_TO_TIME (nowtv);
2290
2291   CLIENTS_LOCK (sink);
2292   for (clients = sink->clients; clients; clients = clients->next) {
2293     GstOutputClient *client;
2294
2295     client = clients->data;
2296     if (sink->timeout > 0 && now - client->last_activity_time > sink->timeout) {
2297       client->status = GST_CLIENT_STATUS_SLOW;
2298       gst_multi_output_sink_remove_client_link (sink, clients);
2299     }
2300   }
2301   CLIENTS_UNLOCK (sink);
2302
2303   return FALSE;
2304 }
2305
2306 /* we handle the client communication in another thread so that we do not block
2307  * the gstreamer thread while we select() on the client fds */
2308 static gpointer
2309 gst_multi_output_sink_thread (GstMultiOutputSink * sink)
2310 {
2311   GSource *timeout = NULL;
2312
2313   while (sink->running) {
2314     if (sink->timeout > 0) {
2315       timeout = g_timeout_source_new (sink->timeout / GST_MSECOND);
2316
2317       g_source_set_callback (timeout,
2318           (GSourceFunc) gst_multi_output_sink_timeout, gst_object_ref (sink),
2319           (GDestroyNotify) gst_object_unref);
2320       g_source_attach (timeout, sink->main_context);
2321     }
2322
2323     /* Returns after handling all pending events or when
2324      * _wakeup() was called. In any case we have to add
2325      * a new timeout because something happened.
2326      */
2327     g_main_context_iteration (sink->main_context, TRUE);
2328
2329     if (timeout) {
2330       g_source_destroy (timeout);
2331       g_source_unref (timeout);
2332     }
2333   }
2334
2335   return NULL;
2336 }
2337
2338 static GstFlowReturn
2339 gst_multi_output_sink_render (GstBaseSink * bsink, GstBuffer * buf)
2340 {
2341   GstMultiOutputSink *sink;
2342   gboolean in_caps;
2343 #if 0
2344   GstCaps *bufcaps, *padcaps;
2345 #endif
2346
2347   sink = GST_MULTI_OUTPUT_SINK (bsink);
2348
2349   g_return_val_if_fail (GST_OBJECT_FLAG_IS_SET (sink,
2350           GST_MULTI_OUTPUT_SINK_OPEN), GST_FLOW_WRONG_STATE);
2351
2352 #if 0
2353   /* since we check every buffer for streamheader caps, we need to make
2354    * sure every buffer has caps set */
2355   bufcaps = gst_buffer_get_caps (buf);
2356   padcaps = GST_PAD_CAPS (GST_BASE_SINK_PAD (bsink));
2357
2358   /* make sure we have caps on the pad */
2359   if (!padcaps && !bufcaps)
2360     goto no_caps;
2361 #endif
2362
2363   /* get IN_CAPS first, code below might mess with the flags */
2364   in_caps = GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_IN_CAPS);
2365
2366 #if 0
2367   /* stamp the buffer with previous caps if no caps set */
2368   if (!bufcaps) {
2369     if (!gst_buffer_is_writable (buf)) {
2370       /* metadata is not writable, copy will be made and original buffer
2371        * will be unreffed so we need to ref so that we don't lose the
2372        * buffer in the render method. */
2373       gst_buffer_ref (buf);
2374       /* the new buffer is ours only, we keep it out of the scope of this
2375        * function */
2376       buf = gst_buffer_make_writable (buf);
2377     } else {
2378       /* else the metadata is writable, we ref because we keep the buffer
2379        * out of the scope of this method */
2380       gst_buffer_ref (buf);
2381     }
2382     /* buffer metadata is writable now, set the caps */
2383     gst_buffer_set_caps (buf, padcaps);
2384   } else {
2385     gst_caps_unref (bufcaps);
2386
2387     /* since we keep this buffer out of the scope of this method */
2388     gst_buffer_ref (buf);
2389   }
2390 #endif
2391
2392   GST_LOG_OBJECT (sink, "received buffer %p, in_caps: %s, offset %"
2393       G_GINT64_FORMAT ", offset_end %" G_GINT64_FORMAT
2394       ", timestamp %" GST_TIME_FORMAT ", duration %" GST_TIME_FORMAT,
2395       buf, in_caps ? "yes" : "no", GST_BUFFER_OFFSET (buf),
2396       GST_BUFFER_OFFSET_END (buf),
2397       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
2398       GST_TIME_ARGS (GST_BUFFER_DURATION (buf)));
2399
2400   /* if we get IN_CAPS buffers, but the previous buffer was not IN_CAPS,
2401    * it means we're getting new streamheader buffers, and we should clear
2402    * the old ones */
2403   if (in_caps && sink->previous_buffer_in_caps == FALSE) {
2404     GST_DEBUG_OBJECT (sink,
2405         "receiving new IN_CAPS buffers, clearing old streamheader");
2406     g_slist_foreach (sink->streamheader, (GFunc) gst_mini_object_unref, NULL);
2407     g_slist_free (sink->streamheader);
2408     sink->streamheader = NULL;
2409   }
2410
2411   /* save the current in_caps */
2412   sink->previous_buffer_in_caps = in_caps;
2413
2414   /* if the incoming buffer is marked as IN CAPS, then we assume for now
2415    * it's a streamheader that needs to be sent to each new client, so we
2416    * put it on our internal list of streamheader buffers.
2417    * FIXME: we could check if the buffer's contents are in fact part of the
2418    * current streamheader.
2419    *
2420    * We don't send the buffer to the client, since streamheaders are sent
2421    * separately when necessary. */
2422   if (in_caps) {
2423     GST_DEBUG_OBJECT (sink, "appending IN_CAPS buffer with length %"
2424         G_GSIZE_FORMAT " to streamheader", gst_buffer_get_size (buf));
2425     sink->streamheader = g_slist_append (sink->streamheader, buf);
2426   } else {
2427     /* queue the buffer, this is a regular data buffer. */
2428     this->class->queue_buffer (sink, buf);
2429
2430     sink->bytes_to_serve += gst_buffer_get_size (buf);
2431   }
2432   return GST_FLOW_OK;
2433
2434   /* ERRORS */
2435 #if 0
2436 no_caps:
2437   {
2438     GST_ELEMENT_ERROR (sink, CORE, NEGOTIATION, (NULL),
2439         ("Received first buffer without caps set"));
2440     return GST_FLOW_NOT_NEGOTIATED;
2441   }
2442 #endif
2443 }
2444
2445 static void
2446 gst_multi_output_sink_set_property (GObject * object, guint prop_id,
2447     const GValue * value, GParamSpec * pspec)
2448 {
2449   GstMultiOutputSink *multioutputsink;
2450
2451   multioutputsink = GST_MULTI_OUTPUT_SINK (object);
2452
2453   switch (prop_id) {
2454     case PROP_BUFFERS_MAX:
2455       multioutputsink->units_max = g_value_get_int (value);
2456       break;
2457     case PROP_BUFFERS_SOFT_MAX:
2458       multioutputsink->units_soft_max = g_value_get_int (value);
2459       break;
2460     case PROP_TIME_MIN:
2461       multioutputsink->time_min = g_value_get_int64 (value);
2462       break;
2463     case PROP_BYTES_MIN:
2464       multioutputsink->bytes_min = g_value_get_int (value);
2465       break;
2466     case PROP_BUFFERS_MIN:
2467       multioutputsink->buffers_min = g_value_get_int (value);
2468       break;
2469     case PROP_UNIT_TYPE:
2470       multioutputsink->unit_type = g_value_get_enum (value);
2471       break;
2472     case PROP_UNITS_MAX:
2473       multioutputsink->units_max = g_value_get_int64 (value);
2474       break;
2475     case PROP_UNITS_SOFT_MAX:
2476       multioutputsink->units_soft_max = g_value_get_int64 (value);
2477       break;
2478     case PROP_RECOVER_POLICY:
2479       multioutputsink->recover_policy = g_value_get_enum (value);
2480       break;
2481     case PROP_TIMEOUT:
2482       multioutputsink->timeout = g_value_get_uint64 (value);
2483       break;
2484     case PROP_SYNC_METHOD:
2485       multioutputsink->def_sync_method = g_value_get_enum (value);
2486       break;
2487     case PROP_BURST_FORMAT:
2488       multioutputsink->def_burst_format = g_value_get_enum (value);
2489       break;
2490     case PROP_BURST_VALUE:
2491       multioutputsink->def_burst_value = g_value_get_uint64 (value);
2492       break;
2493     case PROP_QOS_DSCP:
2494       multioutputsink->qos_dscp = g_value_get_int (value);
2495       setup_dscp (multioutputsink);
2496       break;
2497     case PROP_HANDLE_READ:
2498       multioutputsink->handle_read = g_value_get_boolean (value);
2499       break;
2500     case PROP_RESEND_STREAMHEADER:
2501       multioutputsink->resend_streamheader = g_value_get_boolean (value);
2502       break;
2503
2504     default:
2505       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2506       break;
2507   }
2508 }
2509
2510 static void
2511 gst_multi_output_sink_get_property (GObject * object, guint prop_id,
2512     GValue * value, GParamSpec * pspec)
2513 {
2514   GstMultiOutputSink *multioutputsink;
2515
2516   multioutputsink = GST_MULTI_OUTPUT_SINK (object);
2517
2518   switch (prop_id) {
2519     case PROP_BUFFERS_MAX:
2520       g_value_set_int (value, multioutputsink->units_max);
2521       break;
2522     case PROP_BUFFERS_SOFT_MAX:
2523       g_value_set_int (value, multioutputsink->units_soft_max);
2524       break;
2525     case PROP_TIME_MIN:
2526       g_value_set_int64 (value, multioutputsink->time_min);
2527       break;
2528     case PROP_BYTES_MIN:
2529       g_value_set_int (value, multioutputsink->bytes_min);
2530       break;
2531     case PROP_BUFFERS_MIN:
2532       g_value_set_int (value, multioutputsink->buffers_min);
2533       break;
2534     case PROP_BUFFERS_QUEUED:
2535       g_value_set_uint (value, multioutputsink->buffers_queued);
2536       break;
2537     case PROP_BYTES_QUEUED:
2538       g_value_set_uint (value, multioutputsink->bytes_queued);
2539       break;
2540     case PROP_TIME_QUEUED:
2541       g_value_set_uint64 (value, multioutputsink->time_queued);
2542       break;
2543     case PROP_UNIT_TYPE:
2544       g_value_set_enum (value, multioutputsink->unit_type);
2545       break;
2546     case PROP_UNITS_MAX:
2547       g_value_set_int64 (value, multioutputsink->units_max);
2548       break;
2549     case PROP_UNITS_SOFT_MAX:
2550       g_value_set_int64 (value, multioutputsink->units_soft_max);
2551       break;
2552     case PROP_RECOVER_POLICY:
2553       g_value_set_enum (value, multioutputsink->recover_policy);
2554       break;
2555     case PROP_TIMEOUT:
2556       g_value_set_uint64 (value, multioutputsink->timeout);
2557       break;
2558     case PROP_SYNC_METHOD:
2559       g_value_set_enum (value, multioutputsink->def_sync_method);
2560       break;
2561     case PROP_BYTES_TO_SERVE:
2562       g_value_set_uint64 (value, multioutputsink->bytes_to_serve);
2563       break;
2564     case PROP_BYTES_SERVED:
2565       g_value_set_uint64 (value, multioutputsink->bytes_served);
2566       break;
2567     case PROP_BURST_FORMAT:
2568       g_value_set_enum (value, multioutputsink->def_burst_format);
2569       break;
2570     case PROP_BURST_VALUE:
2571       g_value_set_uint64 (value, multioutputsink->def_burst_value);
2572       break;
2573     case PROP_QOS_DSCP:
2574       g_value_set_int (value, multioutputsink->qos_dscp);
2575       break;
2576     case PROP_HANDLE_READ:
2577       g_value_set_boolean (value, multioutputsink->handle_read);
2578       break;
2579     case PROP_RESEND_STREAMHEADER:
2580       g_value_set_boolean (value, multioutputsink->resend_streamheader);
2581       break;
2582     case PROP_NUM_OUTPUTS:
2583       g_value_set_uint (value,
2584           g_hash_table_size (multioutputsink->output_hash));
2585       break;
2586
2587     default:
2588       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2589       break;
2590   }
2591 }
2592
2593
2594 /* create a output for sending to remote machine */
2595 static gboolean
2596 gst_multi_output_sink_start (GstBaseSink * bsink)
2597 {
2598   GstMultiOutputSinkClass *fclass;
2599   GstMultiOutputSink *this;
2600   GList *clients;
2601
2602   if (GST_OBJECT_FLAG_IS_SET (bsink, GST_MULTI_OUTPUT_SINK_OPEN))
2603     return TRUE;
2604
2605   this = GST_MULTI_OUTPUT_SINK (bsink);
2606   fclass = GST_MULTI_OUTPUT_SINK_GET_CLASS (this);
2607
2608   GST_INFO_OBJECT (this, "starting");
2609   /* FIXME: until here the same */
2610
2611 #if 0
2612   this->main_context = g_main_context_new ();
2613
2614   CLIENTS_LOCK (this);
2615   for (clients = this->clients; clients; clients = clients->next) {
2616     GstOutputClient *client;
2617
2618     client = clients->data;
2619     if (client->source)
2620       continue;
2621     client->source =
2622         g_output_create_source (client->output,
2623         G_IO_IN | G_IO_OUT | G_IO_PRI | G_IO_ERR | G_IO_HUP, this->cancellable);
2624     g_source_set_callback (client->source,
2625         (GSourceFunc) gst_multi_output_sink_output_condition,
2626         gst_object_ref (this), (GDestroyNotify) gst_object_unref);
2627     g_source_attach (client->source, this->main_context);
2628   }
2629   CLIENTS_UNLOCK (this);
2630
2631   /* FIXME: this bit shared */
2632 #endif
2633   this->streamheader = NULL;
2634   this->bytes_to_serve = 0;
2635   this->bytes_served = 0;
2636
2637   if (fclass->init) {
2638     fclass->init (this);
2639   }
2640
2641   this->running = TRUE;
2642
2643   this->thread = g_thread_new ("multioutputsink",
2644       (GThreadFunc) gst_multi_output_sink_thread, this);
2645
2646   GST_OBJECT_FLAG_SET (this, GST_MULTI_OUTPUT_SINK_OPEN);
2647
2648   return TRUE;
2649 }
2650
2651 static gboolean
2652 multioutputsink_hash_remove (gpointer key, gpointer value, gpointer data)
2653 {
2654   return TRUE;
2655 }
2656
2657 static gboolean
2658 gst_multi_output_sink_stop (GstBaseSink * bsink)
2659 {
2660   GstMultiOutputSinkClass *fclass;
2661   GstMultiOutputSink *this;
2662   GstBuffer *buf;
2663   gint i;
2664
2665   this = GST_MULTI_OUTPUT_SINK (bsink);
2666   fclass = GST_MULTI_OUTPUT_SINK_GET_CLASS (this);
2667
2668   if (!GST_OBJECT_FLAG_IS_SET (bsink, GST_MULTI_OUTPUT_SINK_OPEN))
2669     return TRUE;
2670
2671   this->running = FALSE;
2672
2673   if (parent_class->wakeup)
2674     parent_class->wakeup (this);
2675
2676
2677   if (this->thread) {
2678     GST_DEBUG_OBJECT (this, "joining thread");
2679     g_thread_join (this->thread);
2680     GST_DEBUG_OBJECT (this, "joined thread");
2681     this->thread = NULL;
2682   }
2683
2684   /* free the clients */
2685   gst_multi_output_sink_clear (this);
2686
2687   if (this->streamheader) {
2688     g_slist_foreach (this->streamheader, (GFunc) gst_mini_object_unref, NULL);
2689     g_slist_free (this->streamheader);
2690     this->streamheader = NULL;
2691   }
2692
2693   if (fclass->close)
2694     fclass->close (this);
2695
2696 #ifdef 0
2697   if (this->main_context) {
2698     g_main_context_unref (this->main_context);
2699     this->main_context = NULL;
2700   }
2701 #endif
2702
2703   g_hash_table_foreach_remove (this->output_hash, multioutputsink_hash_remove,
2704       this);
2705
2706   /* remove all queued buffers */
2707   if (this->bufqueue) {
2708     GST_DEBUG_OBJECT (this, "Emptying bufqueue with %d buffers",
2709         this->bufqueue->len);
2710     for (i = this->bufqueue->len - 1; i >= 0; --i) {
2711       buf = g_array_index (this->bufqueue, GstBuffer *, i);
2712       GST_LOG_OBJECT (this, "Removing buffer %p (%d) with refcount %d", buf, i,
2713           GST_MINI_OBJECT_REFCOUNT (buf));
2714       gst_buffer_unref (buf);
2715       this->bufqueue = g_array_remove_index (this->bufqueue, i);
2716     }
2717     /* freeing the array is done in _finalize */
2718   }
2719   GST_OBJECT_FLAG_UNSET (this, GST_MULTI_OUTPUT_SINK_OPEN);
2720
2721   return TRUE;
2722 }
2723
2724 static GstStateChangeReturn
2725 gst_multi_output_sink_change_state (GstElement * element,
2726     GstStateChange transition)
2727 {
2728   GstMultiOutputSink *sink;
2729   GstStateChangeReturn ret;
2730
2731   sink = GST_MULTI_OUTPUT_SINK (element);
2732
2733   /* we disallow changing the state from the streaming thread */
2734   if (g_thread_self () == sink->thread)
2735     return GST_STATE_CHANGE_FAILURE;
2736
2737
2738   switch (transition) {
2739     case GST_STATE_CHANGE_NULL_TO_READY:
2740       if (!parent_class->start (GST_BASE_SINK (sink)))
2741         goto start_failed;
2742       break;
2743     case GST_STATE_CHANGE_READY_TO_PAUSED:
2744       break;
2745     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
2746       break;
2747     default:
2748       break;
2749   }
2750
2751   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
2752
2753   switch (transition) {
2754     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
2755       break;
2756     case GST_STATE_CHANGE_PAUSED_TO_READY:
2757       break;
2758     case GST_STATE_CHANGE_READY_TO_NULL:
2759       gst_multi_output_sink_stop (GST_BASE_SINK (sink));
2760       break;
2761     default:
2762       break;
2763   }
2764   return ret;
2765
2766   /* ERRORS */
2767 start_failed:
2768   {
2769     /* error message was posted */
2770     return GST_STATE_CHANGE_FAILURE;
2771   }
2772 }
2773
2774 #if 0
2775 static gboolean
2776 gst_multi_output_sink_unlock (GstBaseSink * bsink)
2777 {
2778   GstMultiOutputSink *sink;
2779
2780   sink = GST_MULTI_OUTPUT_SINK (bsink);
2781
2782   GST_DEBUG_OBJECT (sink, "set to flushing");
2783   g_cancellable_cancel (sink->cancellable);
2784   if (sink->main_context)
2785     g_main_context_wakeup (sink->main_context);
2786
2787   return TRUE;
2788 }
2789
2790 /* will be called only between calls to start() and stop() */
2791 static gboolean
2792 gst_multi_output_sink_unlock_stop (GstBaseSink * bsink)
2793 {
2794   GstMultiOutputSink *sink;
2795
2796   sink = GST_MULTI_OUTPUT_SINK (bsink);
2797
2798   GST_DEBUG_OBJECT (sink, "unset flushing");
2799   g_cancellable_reset (sink->cancellable);
2800
2801   return TRUE;
2802 }
2803 #endif