b3d9475584cff1afcb247a5520f711af45ac41b9
[platform/upstream/gstreamer.git] / gst / tcp / gstmultifdsink.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  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Library General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Library General Public License for more details.
15  *
16  * You should have received a copy of the GNU Library General Public
17  * License along with this library; if not, write to the
18  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
19  * Boston, MA 02110-1301, USA.
20  */
21
22 /**
23  * SECTION:element-multifdsink
24  * @title: multifdsink
25  * @see_also: tcpserversink
26  *
27  * This plugin writes incoming data to a set of file descriptors. The
28  * file descriptors can be added to multifdsink by emitting the #GstMultiFdSink::add signal.
29  * For each descriptor added, the #GstMultiFdSink::client-added signal will be called.
30  *
31  * The multifdsink element needs to be set into READY, PAUSED or PLAYING state
32  * before operations such as adding clients are possible.
33  *
34  * A client can also be added with the #GstMultiFdSink::add-full signal
35  * that allows for more control over what and how much data a client
36  * initially receives.
37  *
38  * Clients can be removed from multifdsink by emitting the #GstMultiFdSink::remove signal. For
39  * each descriptor removed, the #GstMultiFdSink::client-removed signal will be called. The
40  * #GstMultiFdSink::client-removed signal can also be fired when multifdsink decides that a
41  * client is not active anymore or, depending on the value of the
42  * #GstMultiFdSink:recover-policy property, if the client is reading too slowly.
43  * In all cases, multifdsink will never close a file descriptor itself.
44  * The user of multifdsink is responsible for closing all file descriptors.
45  * This can for example be done in response to the #GstMultiFdSink::client-fd-removed signal.
46  * Note that multifdsink still has a reference to the file descriptor when the
47  * #GstMultiFdSink::client-removed signal is emitted, so that "get-stats" can be performed on
48  * the descriptor; it is therefore not safe to close the file descriptor in
49  * the #GstMultiFdSink::client-removed signal handler, and you should use the
50  * #GstMultiFdSink::client-fd-removed signal to safely close the fd.
51  *
52  * Multifdsink internally keeps a queue of the incoming buffers and uses a
53  * separate thread to send the buffers to the clients. This ensures that no
54  * client write can block the pipeline and that clients can read with different
55  * speeds.
56  *
57  * When adding a client to multifdsink, the #GstMultiFdSink:sync-method property will define
58  * which buffer in the queued buffers will be sent first to the client. Clients
59  * can be sent the most recent buffer (which might not be decodable by the
60  * client if it is not a keyframe), the next keyframe received in
61  * multifdsink (which can take some time depending on the keyframe rate), or the
62  * last received keyframe (which will cause a simple burst-on-connect).
63  * Multifdsink will always keep at least one keyframe in its internal buffers
64  * when the sync-mode is set to latest-keyframe.
65  *
66  * There are additional values for the #GstMultiFdSink:sync-method
67  * property to allow finer control over burst-on-connect behaviour. By selecting
68  * the 'burst' method a minimum burst size can be chosen, 'burst-keyframe'
69  * additionally requires that the burst begin with a keyframe, and
70  * 'burst-with-keyframe' attempts to burst beginning with a keyframe, but will
71  * prefer a minimum burst size even if it requires not starting with a keyframe.
72  *
73  * Multifdsink can be instructed to keep at least a minimum amount of data
74  * expressed in time or byte units in its internal queues with the
75  * #GstMultiFdSink:time-min and #GstMultiFdSink:bytes-min properties respectively.
76  * These properties are useful if the application adds clients with the
77  * #GstMultiFdSink::add-full signal to make sure that a burst connect can
78  * actually be honored.
79  *
80  * When streaming data, clients are allowed to read at a different rate than
81  * the rate at which multifdsink receives data. If the client is reading too
82  * fast, no data will be send to the client until multifdsink receives more
83  * data. If the client, however, reads too slowly, data for that client will be
84  * queued up in multifdsink. Two properties control the amount of data
85  * (buffers) that is queued in multifdsink: #GstMultiFdSink:buffers-max and
86  * #GstMultiFdSink:buffers-soft-max. A client that falls behind by
87  * #GstMultiFdSink:buffers-max is removed from multifdsink forcibly.
88  *
89  * A client with a lag of at least #GstMultiFdSink:buffers-soft-max enters the recovery
90  * procedure which is controlled with the #GstMultiFdSink:recover-policy property.
91  * A recover policy of NONE will do nothing, RESYNC_LATEST will send the most recently
92  * received buffer as the next buffer for the client, RESYNC_SOFT_LIMIT
93  * positions the client to the soft limit in the buffer queue and
94  * RESYNC_KEYFRAME positions the client at the most recent keyframe in the
95  * buffer queue.
96  *
97  * multifdsink will by default synchronize on the clock before serving the
98  * buffers to the clients. This behaviour can be disabled by setting the sync
99  * property to FALSE. Multifdsink will by default not do QoS and will never
100  * drop late buffers.
101  */
102
103 #ifdef HAVE_CONFIG_H
104 #include "config.h"
105 #endif
106
107 #include <gst/gst-i18n-plugin.h>
108
109 #include <sys/ioctl.h>
110
111 #ifdef HAVE_UNISTD_H
112 #include <unistd.h>
113 #endif
114
115 #include <string.h>
116 #include <fcntl.h>
117 #include <sys/types.h>
118 #include <sys/socket.h>
119 #include <sys/stat.h>
120 #include <netinet/in.h>
121
122 #ifdef HAVE_FIONREAD_IN_SYS_FILIO
123 #include <sys/filio.h>
124 #endif
125
126 #include "gstmultifdsink.h"
127
128 #define NOT_IMPLEMENTED 0
129
130 GST_DEBUG_CATEGORY_STATIC (multifdsink_debug);
131 #define GST_CAT_DEFAULT (multifdsink_debug)
132
133 /* MultiFdSink signals and args */
134 enum
135 {
136   /* methods */
137   SIGNAL_ADD,
138   SIGNAL_ADD_BURST,
139   SIGNAL_REMOVE,
140   SIGNAL_REMOVE_FLUSH,
141   SIGNAL_GET_STATS,
142
143   /* signals */
144   SIGNAL_CLIENT_ADDED,
145   SIGNAL_CLIENT_REMOVED,
146   SIGNAL_CLIENT_FD_REMOVED,
147
148   LAST_SIGNAL
149 };
150
151 /* this is really arbitrarily chosen */
152 #define DEFAULT_HANDLE_READ             TRUE
153
154 enum
155 {
156   PROP_0,
157   PROP_HANDLE_READ
158 };
159
160 static void gst_multi_fd_sink_stop_pre (GstMultiHandleSink * mhsink);
161 static void gst_multi_fd_sink_stop_post (GstMultiHandleSink * mhsink);
162 static gboolean gst_multi_fd_sink_start_pre (GstMultiHandleSink * mhsink);
163 static gpointer gst_multi_fd_sink_thread (GstMultiHandleSink * mhsink);
164
165 static void gst_multi_fd_sink_add (GstMultiFdSink * sink, int fd);
166 static void gst_multi_fd_sink_add_full (GstMultiFdSink * sink, int fd,
167     GstSyncMethod sync, GstFormat min_format, guint64 min_value,
168     GstFormat max_format, guint64 max_value);
169 static void gst_multi_fd_sink_remove (GstMultiFdSink * sink, int fd);
170 static void gst_multi_fd_sink_remove_flush (GstMultiFdSink * sink, int fd);
171 static GstStructure *gst_multi_fd_sink_get_stats (GstMultiFdSink * sink,
172     int fd);
173
174 static void gst_multi_fd_sink_emit_client_added (GstMultiHandleSink * mhsink,
175     GstMultiSinkHandle handle);
176 static void gst_multi_fd_sink_emit_client_removed (GstMultiHandleSink * mhsink,
177     GstMultiSinkHandle handle, GstClientStatus status);
178
179 static GstMultiHandleClient *gst_multi_fd_sink_new_client (GstMultiHandleSink *
180     mhsink, GstMultiSinkHandle handle, GstSyncMethod sync_method);
181 static void gst_multi_fd_sink_client_free (GstMultiHandleSink * m,
182     GstMultiHandleClient * client);
183 static int gst_multi_fd_sink_client_get_fd (GstMultiHandleClient * client);
184 static void gst_multi_fd_sink_handle_debug (GstMultiSinkHandle handle,
185     gchar debug[30]);
186 static gpointer gst_multi_fd_sink_handle_hash_key (GstMultiSinkHandle handle);
187 static void gst_multi_fd_sink_hash_adding (GstMultiHandleSink * mhsink,
188     GstMultiHandleClient * mhclient);
189 static void gst_multi_fd_sink_hash_removing (GstMultiHandleSink * mhsink,
190     GstMultiHandleClient * mhclient);
191
192 static void gst_multi_fd_sink_hash_changed (GstMultiHandleSink * mhsink);
193
194 static void gst_multi_fd_sink_set_property (GObject * object, guint prop_id,
195     const GValue * value, GParamSpec * pspec);
196 static void gst_multi_fd_sink_get_property (GObject * object, guint prop_id,
197     GValue * value, GParamSpec * pspec);
198
199 #define gst_multi_fd_sink_parent_class parent_class
200 G_DEFINE_TYPE (GstMultiFdSink, gst_multi_fd_sink, GST_TYPE_MULTI_HANDLE_SINK);
201
202 static guint gst_multi_fd_sink_signals[LAST_SIGNAL] = { 0 };
203
204 static void
205 gst_multi_fd_sink_class_init (GstMultiFdSinkClass * klass)
206 {
207   GObjectClass *gobject_class;
208   GstElementClass *gstelement_class;
209   GstMultiHandleSinkClass *gstmultihandlesink_class;
210
211   gobject_class = (GObjectClass *) klass;
212   gstelement_class = (GstElementClass *) klass;
213   gstmultihandlesink_class = (GstMultiHandleSinkClass *) klass;
214
215   gobject_class->set_property = gst_multi_fd_sink_set_property;
216   gobject_class->get_property = gst_multi_fd_sink_get_property;
217
218   /**
219    * GstMultiFdSink::handle-read
220    *
221    * Handle read requests from clients and discard the data.
222    */
223   g_object_class_install_property (gobject_class, PROP_HANDLE_READ,
224       g_param_spec_boolean ("handle-read", "Handle Read",
225           "Handle client reads and discard the data",
226           DEFAULT_HANDLE_READ, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
227
228   /**
229    * GstMultiFdSink::add:
230    * @gstmultifdsink: the multifdsink element to emit this signal on
231    * @fd:             the file descriptor to add to multifdsink
232    *
233    * Hand the given open file descriptor to multifdsink to write to.
234    */
235   gst_multi_fd_sink_signals[SIGNAL_ADD] =
236       g_signal_new ("add", G_TYPE_FROM_CLASS (klass),
237       G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
238       G_STRUCT_OFFSET (GstMultiFdSinkClass, add), NULL, NULL,
239       NULL, G_TYPE_NONE, 1, G_TYPE_INT);
240   /**
241    * GstMultiFdSink::add-full:
242    * @gstmultifdsink:  the multifdsink element to emit this signal on
243    * @fd:              the file descriptor to add to multifdsink
244    * @sync:            the sync method to use
245    * @format_min:      the format of @value_min
246    * @value_min:       the minimum amount of data to burst expressed in
247    *                   @format_min units.
248    * @format_max:      the format of @value_max
249    * @value_max:       the maximum amount of data to burst expressed in
250    *                   @format_max units.
251    *
252    * Hand the given open file descriptor to multifdsink to write to and
253    * specify the burst parameters for the new connection.
254    */
255   gst_multi_fd_sink_signals[SIGNAL_ADD_BURST] =
256       g_signal_new ("add-full", G_TYPE_FROM_CLASS (klass),
257       G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
258       G_STRUCT_OFFSET (GstMultiFdSinkClass, add_full), NULL, NULL,
259       NULL, G_TYPE_NONE, 6, G_TYPE_INT, GST_TYPE_SYNC_METHOD, GST_TYPE_FORMAT,
260       G_TYPE_UINT64, GST_TYPE_FORMAT, G_TYPE_UINT64);
261   /**
262    * GstMultiFdSink::remove:
263    * @gstmultifdsink: the multifdsink element to emit this signal on
264    * @fd:             the file descriptor to remove from multifdsink
265    *
266    * Remove the given open file descriptor from multifdsink.
267    */
268   gst_multi_fd_sink_signals[SIGNAL_REMOVE] =
269       g_signal_new ("remove", G_TYPE_FROM_CLASS (klass),
270       G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
271       G_STRUCT_OFFSET (GstMultiFdSinkClass, remove), NULL, NULL,
272       NULL, G_TYPE_NONE, 1, G_TYPE_INT);
273   /**
274    * GstMultiFdSink::remove-flush:
275    * @gstmultifdsink: the multifdsink element to emit this signal on
276    * @fd:             the file descriptor to remove from multifdsink
277    *
278    * Remove the given open file descriptor from multifdsink after flushing all
279    * the pending data to the fd.
280    */
281   gst_multi_fd_sink_signals[SIGNAL_REMOVE_FLUSH] =
282       g_signal_new ("remove-flush", G_TYPE_FROM_CLASS (klass),
283       G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
284       G_STRUCT_OFFSET (GstMultiFdSinkClass, remove_flush), NULL, NULL,
285       NULL, G_TYPE_NONE, 1, G_TYPE_INT);
286
287   /**
288    * GstMultiFdSink::get-stats:
289    * @gstmultifdsink: the multifdsink element to emit this signal on
290    * @fd:             the file descriptor to get stats of from multifdsink
291    *
292    * Get statistics about @fd. This function returns a #GstStructure to ease
293    * automatic wrapping for bindings.
294    *
295    * Returns: a #GstStructure with the statistics. The structures
296    *     contains guint64 values that represent respectively: total
297    *     number of bytes sent (bytes-sent), time when the client was
298    *     added (connect-time), time when the client was
299    *     disconnected/removed (disconnect-time), time the client
300    *     is/was active (connect-duration), last activity time (in
301    *     epoch seconds) (last-activity-time), number of buffers
302    *     dropped (buffers-dropped), the timestamp of the first buffer
303    *     (first-buffer-ts) and of the last buffer (last-buffer-ts).
304    *     All times are expressed in nanoseconds (GstClockTime).  The
305    *     structure can be empty if the client was not found.
306    */
307   gst_multi_fd_sink_signals[SIGNAL_GET_STATS] =
308       g_signal_new ("get-stats", G_TYPE_FROM_CLASS (klass),
309       G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
310       G_STRUCT_OFFSET (GstMultiFdSinkClass, get_stats), NULL, NULL,
311       NULL, GST_TYPE_STRUCTURE, 1, G_TYPE_INT);
312
313   /**
314    * GstMultiFdSink::client-added:
315    * @gstmultifdsink: the multifdsink element that emitted this signal
316    * @fd:             the file descriptor that was added to multifdsink
317    *
318    * The given file descriptor was added to multifdsink. This signal will
319    * be emitted from the streaming thread so application should be prepared
320    * for that.
321    */
322   gst_multi_fd_sink_signals[SIGNAL_CLIENT_ADDED] =
323       g_signal_new ("client-added", G_TYPE_FROM_CLASS (klass),
324       G_SIGNAL_RUN_LAST, 0, NULL, NULL, NULL, G_TYPE_NONE, 1, G_TYPE_INT);
325   /**
326    * GstMultiFdSink::client-removed:
327    * @gstmultifdsink: the multifdsink element that emitted this signal
328    * @fd:             the file descriptor that is to be removed from multifdsink
329    * @status:         the reason why the client was removed
330    *
331    * The given file descriptor is about to be removed from multifdsink. This
332    * signal will be emitted from the streaming thread so applications should
333    * be prepared for that.
334    *
335    * @gstmultifdsink still holds a handle to @fd so it is possible to call
336    * the get-stats signal from this callback. For the same reason it is
337    * not safe to `close()` and reuse @fd in this callback.
338    */
339   gst_multi_fd_sink_signals[SIGNAL_CLIENT_REMOVED] =
340       g_signal_new ("client-removed", G_TYPE_FROM_CLASS (klass),
341       G_SIGNAL_RUN_LAST, 0, NULL, NULL, NULL, G_TYPE_NONE, 2, G_TYPE_INT,
342       GST_TYPE_CLIENT_STATUS);
343   /**
344    * GstMultiFdSink::client-fd-removed:
345    * @gstmultifdsink: the multifdsink element that emitted this signal
346    * @fd:             the file descriptor that was removed from multifdsink
347    *
348    * The given file descriptor was removed from multifdsink. This signal will
349    * be emitted from the streaming thread so applications should be prepared
350    * for that.
351    *
352    * In this callback, @gstmultifdsink has removed all the information
353    * associated with @fd and it is therefore not possible to call get-stats
354    * with @fd. It is however safe to `close()` and reuse @fd in the callback.
355    */
356   gst_multi_fd_sink_signals[SIGNAL_CLIENT_FD_REMOVED] =
357       g_signal_new ("client-fd-removed", G_TYPE_FROM_CLASS (klass),
358       G_SIGNAL_RUN_LAST, 0, NULL, NULL, NULL, G_TYPE_NONE, 1, G_TYPE_INT);
359
360   gst_element_class_set_static_metadata (gstelement_class,
361       "Multi filedescriptor sink", "Sink/Network",
362       "Send data to multiple filedescriptors",
363       "Thomas Vander Stichele <thomas at apestaart dot org>, "
364       "Wim Taymans <wim@fluendo.com>");
365
366   klass->add = GST_DEBUG_FUNCPTR (gst_multi_fd_sink_add);
367   klass->add_full = GST_DEBUG_FUNCPTR (gst_multi_fd_sink_add_full);
368   klass->remove = GST_DEBUG_FUNCPTR (gst_multi_fd_sink_remove);
369   klass->remove_flush = GST_DEBUG_FUNCPTR (gst_multi_fd_sink_remove_flush);
370   klass->get_stats = GST_DEBUG_FUNCPTR (gst_multi_fd_sink_get_stats);
371
372   gstmultihandlesink_class->emit_client_added =
373       gst_multi_fd_sink_emit_client_added;
374   gstmultihandlesink_class->emit_client_removed =
375       gst_multi_fd_sink_emit_client_removed;
376
377   gstmultihandlesink_class->stop_pre =
378       GST_DEBUG_FUNCPTR (gst_multi_fd_sink_stop_pre);
379   gstmultihandlesink_class->stop_post =
380       GST_DEBUG_FUNCPTR (gst_multi_fd_sink_stop_post);
381   gstmultihandlesink_class->start_pre =
382       GST_DEBUG_FUNCPTR (gst_multi_fd_sink_start_pre);
383   gstmultihandlesink_class->thread =
384       GST_DEBUG_FUNCPTR (gst_multi_fd_sink_thread);
385   gstmultihandlesink_class->new_client =
386       GST_DEBUG_FUNCPTR (gst_multi_fd_sink_new_client);
387   gstmultihandlesink_class->client_free = gst_multi_fd_sink_client_free;
388   gstmultihandlesink_class->client_get_fd =
389       GST_DEBUG_FUNCPTR (gst_multi_fd_sink_client_get_fd);
390   gstmultihandlesink_class->handle_debug =
391       GST_DEBUG_FUNCPTR (gst_multi_fd_sink_handle_debug);
392   gstmultihandlesink_class->handle_hash_key =
393       GST_DEBUG_FUNCPTR (gst_multi_fd_sink_handle_hash_key);
394   gstmultihandlesink_class->hash_changed =
395       GST_DEBUG_FUNCPTR (gst_multi_fd_sink_hash_changed);
396   gstmultihandlesink_class->hash_adding =
397       GST_DEBUG_FUNCPTR (gst_multi_fd_sink_hash_adding);
398   gstmultihandlesink_class->hash_removing =
399       GST_DEBUG_FUNCPTR (gst_multi_fd_sink_hash_removing);
400
401   GST_DEBUG_CATEGORY_INIT (multifdsink_debug, "multifdsink", 0, "FD sink");
402 }
403
404 static void
405 gst_multi_fd_sink_init (GstMultiFdSink * this)
406 {
407   GstMultiHandleSink *mhsink = GST_MULTI_HANDLE_SINK (this);
408
409   mhsink->handle_hash = g_hash_table_new (g_direct_hash, g_direct_equal);
410
411   this->handle_read = DEFAULT_HANDLE_READ;
412 }
413
414 /* methods to emit signals */
415
416 static void
417 gst_multi_fd_sink_emit_client_added (GstMultiHandleSink * mhsink,
418     GstMultiSinkHandle handle)
419 {
420   g_signal_emit (mhsink, gst_multi_fd_sink_signals[SIGNAL_CLIENT_ADDED], 0,
421       handle.fd);
422 }
423
424 static void
425 gst_multi_fd_sink_emit_client_removed (GstMultiHandleSink * mhsink,
426     GstMultiSinkHandle handle, GstClientStatus status)
427 {
428   g_signal_emit (mhsink, gst_multi_fd_sink_signals[SIGNAL_CLIENT_REMOVED], 0,
429       handle.fd, status);
430 }
431
432 static void
433 gst_multi_fd_sink_client_free (GstMultiHandleSink * mhsink,
434     GstMultiHandleClient * client)
435 {
436   g_signal_emit (mhsink, gst_multi_fd_sink_signals[SIGNAL_CLIENT_FD_REMOVED],
437       0, client->handle.fd);
438 }
439
440 /* action signals */
441
442 static void
443 gst_multi_fd_sink_add (GstMultiFdSink * sink, int fd)
444 {
445   GstMultiSinkHandle handle;
446
447   handle.fd = fd;
448   gst_multi_handle_sink_add (GST_MULTI_HANDLE_SINK_CAST (sink), handle);
449 }
450
451 static void
452 gst_multi_fd_sink_add_full (GstMultiFdSink * sink, int fd,
453     GstSyncMethod sync, GstFormat min_format, guint64 min_value,
454     GstFormat max_format, guint64 max_value)
455 {
456   GstMultiSinkHandle handle;
457
458   handle.fd = fd;
459   gst_multi_handle_sink_add_full (GST_MULTI_HANDLE_SINK_CAST (sink), handle,
460       sync, min_format, min_value, max_format, max_value);
461 }
462
463 static void
464 gst_multi_fd_sink_remove (GstMultiFdSink * sink, int fd)
465 {
466   GstMultiSinkHandle handle;
467
468   handle.fd = fd;
469   gst_multi_handle_sink_remove (GST_MULTI_HANDLE_SINK_CAST (sink), handle);
470 }
471
472 static void
473 gst_multi_fd_sink_remove_flush (GstMultiFdSink * sink, int fd)
474 {
475   GstMultiSinkHandle handle;
476
477   handle.fd = fd;
478   gst_multi_handle_sink_remove_flush (GST_MULTI_HANDLE_SINK_CAST (sink),
479       handle);
480 }
481
482 static GstStructure *
483 gst_multi_fd_sink_get_stats (GstMultiFdSink * sink, int fd)
484 {
485   GstMultiSinkHandle handle;
486
487   handle.fd = fd;
488   return gst_multi_handle_sink_get_stats (GST_MULTI_HANDLE_SINK_CAST (sink),
489       handle);
490 }
491
492 /* vfuncs */
493
494 static GstMultiHandleClient *
495 gst_multi_fd_sink_new_client (GstMultiHandleSink * mhsink,
496     GstMultiSinkHandle handle, GstSyncMethod sync_method)
497 {
498   struct stat statbuf;
499   GstTCPClient *client;
500   GstMultiHandleClient *mhclient;
501   GstMultiFdSink *sink = GST_MULTI_FD_SINK (mhsink);
502   GstMultiHandleSinkClass *mhsinkclass =
503       GST_MULTI_HANDLE_SINK_GET_CLASS (mhsink);
504
505   /* create client datastructure */
506   client = g_new0 (GstTCPClient, 1);
507   mhclient = (GstMultiHandleClient *) client;
508
509   mhclient->handle = handle;
510
511   gst_poll_fd_init (&client->gfd);
512   client->gfd.fd = mhclient->handle.fd;
513
514   gst_multi_handle_sink_client_init (mhclient, sync_method);
515   mhsinkclass->handle_debug (handle, mhclient->debug);
516
517   /* set the socket to non blocking */
518   if (fcntl (handle.fd, F_SETFL, O_NONBLOCK) < 0) {
519     GST_ERROR_OBJECT (mhsink, "failed to make socket %s non-blocking: %s",
520         mhclient->debug, g_strerror (errno));
521   }
522
523   /* we always read from a client */
524   gst_poll_add_fd (sink->fdset, &client->gfd);
525
526   /* we don't try to read from write only fds */
527   if (sink->handle_read) {
528     gint flags;
529
530     flags = fcntl (handle.fd, F_GETFL, 0);
531     if ((flags & O_ACCMODE) != O_WRONLY) {
532       gst_poll_fd_ctl_read (sink->fdset, &client->gfd, TRUE);
533     }
534   }
535   /* figure out the mode, can't use send() for non sockets */
536   if (fstat (handle.fd, &statbuf) == 0 && S_ISSOCK (statbuf.st_mode)) {
537     client->is_socket = TRUE;
538     gst_multi_handle_sink_setup_dscp_client (mhsink, mhclient);
539   }
540
541   return mhclient;
542 }
543
544 static int
545 gst_multi_fd_sink_client_get_fd (GstMultiHandleClient * client)
546 {
547   GstTCPClient *tclient = (GstTCPClient *) client;
548
549   return tclient->gfd.fd;
550 }
551
552 static void
553 gst_multi_fd_sink_handle_debug (GstMultiSinkHandle handle, gchar debug[30])
554 {
555   g_snprintf (debug, 30, "[fd %5d]", handle.fd);
556 }
557
558 static gpointer
559 gst_multi_fd_sink_handle_hash_key (GstMultiSinkHandle handle)
560 {
561   return GINT_TO_POINTER (handle.fd);
562 }
563
564 static void
565 gst_multi_fd_sink_hash_changed (GstMultiHandleSink * mhsink)
566 {
567   GstMultiFdSink *sink = GST_MULTI_FD_SINK (mhsink);
568
569   gst_poll_restart (sink->fdset);
570 }
571
572 /* handle a read on a client fd,
573  * which either indicates a close or should be ignored
574  * returns FALSE if some error occurred or the client closed. */
575 static gboolean
576 gst_multi_fd_sink_handle_client_read (GstMultiFdSink * sink,
577     GstTCPClient * client)
578 {
579   int avail, fd;
580   gboolean ret;
581   GstMultiHandleClient *mhclient = (GstMultiHandleClient *) client;
582
583   fd = client->gfd.fd;
584
585   if (ioctl (fd, FIONREAD, &avail) < 0)
586     goto ioctl_failed;
587
588   GST_DEBUG_OBJECT (sink, "%s select reports client read of %d bytes",
589       mhclient->debug, avail);
590
591   ret = TRUE;
592
593   if (avail == 0) {
594     /* client sent close, so remove it */
595     GST_DEBUG_OBJECT (sink, "%s client asked for close, removing",
596         mhclient->debug);
597     mhclient->status = GST_CLIENT_STATUS_CLOSED;
598     ret = FALSE;
599   } else if (avail < 0) {
600     GST_WARNING_OBJECT (sink, "%s avail < 0, removing", mhclient->debug);
601     mhclient->status = GST_CLIENT_STATUS_ERROR;
602     ret = FALSE;
603   } else {
604     guint8 dummy[512];
605     gint nread;
606
607     /* just Read 'n' Drop, could also just drop the client as it's not supposed
608      * to write to us except for closing the socket, I guess it's because we
609      * like to listen to our customers. */
610     do {
611       /* this is the maximum we can read */
612       gint to_read = MIN (avail, 512);
613
614       GST_DEBUG_OBJECT (sink, "%s client wants us to read %d bytes",
615           mhclient->debug, to_read);
616
617       nread = read (fd, dummy, to_read);
618       if (nread < -1) {
619         GST_WARNING_OBJECT (sink, "%s could not read %d bytes: %s (%d)",
620             mhclient->debug, to_read, g_strerror (errno), errno);
621         mhclient->status = GST_CLIENT_STATUS_ERROR;
622         ret = FALSE;
623         break;
624       } else if (nread == 0) {
625         GST_WARNING_OBJECT (sink, "%s 0 bytes in read, removing",
626             mhclient->debug);
627         mhclient->status = GST_CLIENT_STATUS_ERROR;
628         ret = FALSE;
629         break;
630       }
631       avail -= nread;
632     }
633     while (avail > 0);
634   }
635   return ret;
636
637   /* ERRORS */
638 ioctl_failed:
639   {
640     GST_WARNING_OBJECT (sink, "%s ioctl failed: %s (%d)",
641         mhclient->debug, g_strerror (errno), errno);
642     mhclient->status = GST_CLIENT_STATUS_ERROR;
643     return FALSE;
644   }
645 }
646
647 /* Handle a write on a client,
648  * which indicates a read request from a client.
649  *
650  * For each client we maintain a queue of GstBuffers that contain the raw bytes
651  * we need to send to the client.
652  *
653  * We first check to see if we need to send streamheaders. If so, we queue them.
654  *
655  * Then we run into the main loop that tries to send as many buffers as
656  * possible. It will first exhaust the mhclient->sending queue and if the queue
657  * is empty, it will pick a buffer from the global queue.
658  *
659  * Sending the buffers from the mhclient->sending queue is basically writing
660  * the bytes to the socket and maintaining a count of the bytes that were
661  * sent. When the buffer is completely sent, it is removed from the
662  * mhclient->sending queue and we try to pick a new buffer for sending.
663  *
664  * When the sending returns a partial buffer we stop sending more data as
665  * the next send operation could block.
666  *
667  * This functions returns FALSE if some error occurred.
668  */
669 static gboolean
670 gst_multi_fd_sink_handle_client_write (GstMultiFdSink * sink,
671     GstTCPClient * client)
672 {
673   gboolean more;
674   gboolean flushing;
675   GstClockTime now;
676   GTimeVal nowtv;
677   GstMultiHandleSink *mhsink = GST_MULTI_HANDLE_SINK (sink);
678   GstMultiHandleSinkClass *mhsinkclass =
679       GST_MULTI_HANDLE_SINK_GET_CLASS (mhsink);
680   GstMultiHandleClient *mhclient = (GstMultiHandleClient *) client;
681   int fd = mhclient->handle.fd;
682
683   flushing = mhclient->status == GST_CLIENT_STATUS_FLUSHING;
684
685   more = TRUE;
686   do {
687     gint maxsize;
688
689     g_get_current_time (&nowtv);
690     now = GST_TIMEVAL_TO_TIME (nowtv);
691
692     if (!mhclient->sending) {
693       /* client is not working on a buffer */
694       if (mhclient->bufpos == -1) {
695         /* client is too fast, remove from write queue until new buffer is
696          * available */
697         /* FIXME: specific */
698         gst_poll_fd_ctl_write (sink->fdset, &client->gfd, FALSE);
699
700         /* if we flushed out all of the client buffers, we can stop */
701         if (mhclient->flushcount == 0)
702           goto flushed;
703
704         return TRUE;
705       } else {
706         /* client can pick a buffer from the global queue */
707         GstBuffer *buf;
708         GstClockTime timestamp;
709
710         /* for new connections, we need to find a good spot in the
711          * bufqueue to start streaming from */
712         if (mhclient->new_connection && !flushing) {
713           gint position =
714               gst_multi_handle_sink_new_client_position (mhsink, mhclient);
715
716           if (position >= 0) {
717             /* we got a valid spot in the queue */
718             mhclient->new_connection = FALSE;
719             mhclient->bufpos = position;
720           } else {
721             /* cannot send data to this client yet */
722             /* FIXME: specific */
723             gst_poll_fd_ctl_write (sink->fdset, &client->gfd, FALSE);
724             return TRUE;
725           }
726         }
727
728         /* we flushed all remaining buffers, no need to get a new one */
729         if (mhclient->flushcount == 0)
730           goto flushed;
731
732         /* grab buffer */
733         buf = g_array_index (mhsink->bufqueue, GstBuffer *, mhclient->bufpos);
734         mhclient->bufpos--;
735
736         /* update stats */
737         timestamp = GST_BUFFER_TIMESTAMP (buf);
738         if (mhclient->first_buffer_ts == GST_CLOCK_TIME_NONE)
739           mhclient->first_buffer_ts = timestamp;
740         if (timestamp != -1)
741           mhclient->last_buffer_ts = timestamp;
742
743         /* decrease flushcount */
744         if (mhclient->flushcount != -1)
745           mhclient->flushcount--;
746
747         GST_LOG_OBJECT (sink, "%s client %p at position %d",
748             mhclient->debug, client, mhclient->bufpos);
749
750         /* queueing a buffer will ref it */
751         mhsinkclass->client_queue_buffer (mhsink, mhclient, buf);
752
753         /* need to start from the first byte for this new buffer */
754         mhclient->bufoffset = 0;
755       }
756     }
757
758     /* see if we need to send something */
759     if (mhclient->sending) {
760       ssize_t wrote;
761       GstBuffer *head;
762       GstMapInfo info;
763       guint8 *data;
764
765       /* pick first buffer from list */
766       head = GST_BUFFER (mhclient->sending->data);
767
768       if (!gst_buffer_map (head, &info, GST_MAP_READ))
769         g_return_val_if_reached (FALSE);
770
771       data = info.data;
772       maxsize = info.size - mhclient->bufoffset;
773
774       /* FIXME: specific */
775       /* try to write the complete buffer */
776 #ifdef MSG_NOSIGNAL
777 #define FLAGS MSG_NOSIGNAL
778 #else
779 #define FLAGS 0
780 #endif
781       if (client->is_socket) {
782         wrote = send (fd, data + mhclient->bufoffset, maxsize, FLAGS);
783       } else {
784         wrote = write (fd, data + mhclient->bufoffset, maxsize);
785       }
786       gst_buffer_unmap (head, &info);
787
788       if (wrote < 0) {
789         /* hmm error.. */
790         if (errno == EAGAIN) {
791           /* nothing serious, resource was unavailable, try again later */
792           more = FALSE;
793         } else if (errno == ECONNRESET) {
794           goto connection_reset;
795         } else {
796           goto write_error;
797         }
798       } else {
799         if (wrote < maxsize) {
800           /* partial write means that the client cannot read more and we should
801            * stop sending more */
802           GST_LOG_OBJECT (sink,
803               "partial write on %s of %" G_GSSIZE_FORMAT " bytes",
804               mhclient->debug, wrote);
805           mhclient->bufoffset += wrote;
806           more = FALSE;
807         } else {
808           /* complete buffer was written, we can proceed to the next one */
809           mhclient->sending = g_slist_remove (mhclient->sending, head);
810           gst_buffer_unref (head);
811           /* make sure we start from byte 0 for the next buffer */
812           mhclient->bufoffset = 0;
813         }
814         /* update stats */
815         mhclient->bytes_sent += wrote;
816         mhclient->last_activity_time = now;
817         mhsink->bytes_served += wrote;
818       }
819     }
820   } while (more);
821
822   return TRUE;
823
824   /* ERRORS */
825 flushed:
826   {
827     GST_DEBUG_OBJECT (sink, "%s flushed, removing", mhclient->debug);
828     mhclient->status = GST_CLIENT_STATUS_REMOVED;
829     return FALSE;
830   }
831 connection_reset:
832   {
833     GST_DEBUG_OBJECT (sink, "%s connection reset by peer, removing",
834         mhclient->debug);
835     mhclient->status = GST_CLIENT_STATUS_CLOSED;
836     return FALSE;
837   }
838 write_error:
839   {
840     GST_WARNING_OBJECT (sink,
841         "%s could not write, removing client: %s (%d)", mhclient->debug,
842         g_strerror (errno), errno);
843     mhclient->status = GST_CLIENT_STATUS_ERROR;
844     return FALSE;
845   }
846 }
847
848 static void
849 gst_multi_fd_sink_hash_adding (GstMultiHandleSink * mhsink,
850     GstMultiHandleClient * mhclient)
851 {
852   GstMultiFdSink *sink = GST_MULTI_FD_SINK (mhsink);
853   GstTCPClient *client = (GstTCPClient *) mhclient;
854
855   gst_poll_fd_ctl_write (sink->fdset, &client->gfd, TRUE);
856 }
857
858 static void
859 gst_multi_fd_sink_hash_removing (GstMultiHandleSink * mhsink,
860     GstMultiHandleClient * mhclient)
861 {
862   GstMultiFdSink *sink = GST_MULTI_FD_SINK (mhsink);
863   GstTCPClient *client = (GstTCPClient *) mhclient;
864
865   gst_poll_remove_fd (sink->fdset, &client->gfd);
866 }
867
868
869 /* Handle the clients. Basically does a blocking select for one
870  * of the client fds to become read or writable. We also have a
871  * filedescriptor to receive commands on that we need to check.
872  *
873  * After going out of the select call, we read and write to all
874  * clients that can do so. Badly behaving clients are put on a
875  * garbage list and removed.
876  */
877 static void
878 gst_multi_fd_sink_handle_clients (GstMultiFdSink * sink)
879 {
880   int result;
881   GList *clients, *next;
882   gboolean try_again;
883   GstMultiFdSinkClass *fclass;
884   guint cookie;
885   GstMultiHandleSink *mhsink = GST_MULTI_HANDLE_SINK (sink);
886   int fd;
887
888
889   fclass = GST_MULTI_FD_SINK_GET_CLASS (sink);
890
891   do {
892     try_again = FALSE;
893
894     /* check for:
895      * - server socket input (ie, new client connections)
896      * - client socket input (ie, clients saying goodbye)
897      * - client socket output (ie, client reads)          */
898     GST_LOG_OBJECT (sink, "waiting on action on fdset");
899
900     result =
901         gst_poll_wait (sink->fdset,
902         mhsink->timeout != 0 ? mhsink->timeout : GST_CLOCK_TIME_NONE);
903
904     /* Handle the special case in which the sink is not receiving more buffers
905      * and will not disconnect inactive client in the streaming thread. */
906     if (G_UNLIKELY (result == 0)) {
907       GstClockTime now;
908       GTimeVal nowtv;
909
910       g_get_current_time (&nowtv);
911       now = GST_TIMEVAL_TO_TIME (nowtv);
912
913       CLIENTS_LOCK (mhsink);
914       for (clients = mhsink->clients; clients; clients = next) {
915         GstTCPClient *client;
916         GstMultiHandleClient *mhclient;
917
918         client = (GstTCPClient *) clients->data;
919         mhclient = (GstMultiHandleClient *) client;
920         next = g_list_next (clients);
921         if (mhsink->timeout > 0
922             && now - mhclient->last_activity_time > mhsink->timeout) {
923           mhclient->status = GST_CLIENT_STATUS_SLOW;
924           gst_multi_handle_sink_remove_client_link (mhsink, clients);
925         }
926       }
927       CLIENTS_UNLOCK (mhsink);
928       return;
929     } else if (result < 0) {
930       GST_WARNING_OBJECT (sink, "wait failed: %s (%d)", g_strerror (errno),
931           errno);
932       if (errno == EBADF) {
933         /* ok, so one or more of the fds is invalid. We loop over them to find
934          * the ones that give an error to the F_GETFL fcntl. */
935         CLIENTS_LOCK (mhsink);
936       restart:
937         cookie = mhsink->clients_cookie;
938         for (clients = mhsink->clients; clients; clients = next) {
939           GstTCPClient *client;
940           GstMultiHandleClient *mhclient;
941           long flags;
942           int res;
943
944           if (cookie != mhsink->clients_cookie) {
945             GST_DEBUG_OBJECT (sink, "Cookie changed finding bad fd");
946             goto restart;
947           }
948
949           client = (GstTCPClient *) clients->data;
950           mhclient = (GstMultiHandleClient *) client;
951           next = g_list_next (clients);
952
953           fd = client->gfd.fd;
954
955           res = fcntl (fd, F_GETFL, &flags);
956           if (res == -1) {
957             GST_WARNING_OBJECT (sink, "fcntl failed for %d, removing: %s (%d)",
958                 fd, g_strerror (errno), errno);
959             if (errno == EBADF) {
960               mhclient->status = GST_CLIENT_STATUS_ERROR;
961               /* releases the CLIENTS lock */
962               gst_multi_handle_sink_remove_client_link (mhsink, clients);
963             }
964           }
965         }
966         CLIENTS_UNLOCK (mhsink);
967         /* after this, go back in the select loop as the read/writefds
968          * are not valid */
969         try_again = TRUE;
970       } else if (errno == EINTR) {
971         /* interrupted system call, just redo the wait */
972         try_again = TRUE;
973       } else if (errno == EBUSY) {
974         /* the call to gst_poll_wait() was flushed */
975         return;
976       } else {
977         /* this is quite bad... */
978         GST_ELEMENT_ERROR (sink, RESOURCE, READ, (NULL),
979             ("select failed: %s (%d)", g_strerror (errno), errno));
980         return;
981       }
982     } else {
983       GST_LOG_OBJECT (sink, "wait done: %d sockets with events", result);
984     }
985   } while (try_again);
986
987   /* subclasses can check fdset with this virtual function */
988   if (fclass->wait)
989     fclass->wait (sink, sink->fdset);
990
991   /* Check the clients */
992   CLIENTS_LOCK (mhsink);
993
994 restart2:
995   cookie = mhsink->clients_cookie;
996   for (clients = mhsink->clients; clients; clients = next) {
997     GstTCPClient *client;
998     GstMultiHandleClient *mhclient;
999
1000     if (mhsink->clients_cookie != cookie) {
1001       GST_DEBUG_OBJECT (sink, "Restarting loop, cookie out of date");
1002       goto restart2;
1003     }
1004
1005     client = (GstTCPClient *) clients->data;
1006     mhclient = (GstMultiHandleClient *) client;
1007     next = g_list_next (clients);
1008
1009     if (mhclient->status != GST_CLIENT_STATUS_FLUSHING
1010         && mhclient->status != GST_CLIENT_STATUS_OK) {
1011       gst_multi_handle_sink_remove_client_link (mhsink, clients);
1012       continue;
1013     }
1014
1015     if (gst_poll_fd_has_closed (sink->fdset, &client->gfd)) {
1016       mhclient->status = GST_CLIENT_STATUS_CLOSED;
1017       gst_multi_handle_sink_remove_client_link (mhsink, clients);
1018       continue;
1019     }
1020     if (gst_poll_fd_has_error (sink->fdset, &client->gfd)) {
1021       GST_WARNING_OBJECT (sink, "gst_poll_fd_has_error for %d", client->gfd.fd);
1022       mhclient->status = GST_CLIENT_STATUS_ERROR;
1023       gst_multi_handle_sink_remove_client_link (mhsink, clients);
1024       continue;
1025     }
1026     if (gst_poll_fd_can_read (sink->fdset, &client->gfd)) {
1027       /* handle client read */
1028       if (!gst_multi_fd_sink_handle_client_read (sink, client)) {
1029         gst_multi_handle_sink_remove_client_link (mhsink, clients);
1030         continue;
1031       }
1032     }
1033     if (gst_poll_fd_can_write (sink->fdset, &client->gfd)) {
1034       /* handle client write */
1035       if (!gst_multi_fd_sink_handle_client_write (sink, client)) {
1036         gst_multi_handle_sink_remove_client_link (mhsink, clients);
1037         continue;
1038       }
1039     }
1040   }
1041   CLIENTS_UNLOCK (mhsink);
1042 }
1043
1044 /* we handle the client communication in another thread so that we do not block
1045  * the gstreamer thread while we select() on the client fds */
1046 static gpointer
1047 gst_multi_fd_sink_thread (GstMultiHandleSink * mhsink)
1048 {
1049   GstMultiFdSink *sink = GST_MULTI_FD_SINK (mhsink);
1050
1051   while (mhsink->running) {
1052     gst_multi_fd_sink_handle_clients (sink);
1053   }
1054   return NULL;
1055 }
1056
1057 static void
1058 gst_multi_fd_sink_set_property (GObject * object, guint prop_id,
1059     const GValue * value, GParamSpec * pspec)
1060 {
1061   GstMultiFdSink *multifdsink;
1062
1063   multifdsink = GST_MULTI_FD_SINK (object);
1064
1065   switch (prop_id) {
1066     case PROP_HANDLE_READ:
1067       multifdsink->handle_read = g_value_get_boolean (value);
1068       break;
1069
1070     default:
1071       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1072       break;
1073   }
1074 }
1075
1076 static void
1077 gst_multi_fd_sink_get_property (GObject * object, guint prop_id, GValue * value,
1078     GParamSpec * pspec)
1079 {
1080   GstMultiFdSink *multifdsink;
1081
1082   multifdsink = GST_MULTI_FD_SINK (object);
1083
1084   switch (prop_id) {
1085     case PROP_HANDLE_READ:
1086       g_value_set_boolean (value, multifdsink->handle_read);
1087       break;
1088
1089     default:
1090       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1091       break;
1092   }
1093 }
1094
1095 static gboolean
1096 gst_multi_fd_sink_start_pre (GstMultiHandleSink * mhsink)
1097 {
1098   GstMultiFdSink *mfsink = GST_MULTI_FD_SINK (mhsink);
1099
1100   GST_INFO_OBJECT (mfsink, "starting");
1101   if ((mfsink->fdset = gst_poll_new (TRUE)) == NULL)
1102     goto socket_pair;
1103
1104   return TRUE;
1105
1106   /* ERRORS */
1107 socket_pair:
1108   {
1109     GST_ELEMENT_ERROR (mfsink, RESOURCE, OPEN_READ_WRITE, (NULL),
1110         GST_ERROR_SYSTEM);
1111     return FALSE;
1112   }
1113 }
1114
1115 static gboolean
1116 multifdsink_hash_remove (gpointer key, gpointer value, gpointer data)
1117 {
1118   return TRUE;
1119 }
1120
1121 static void
1122 gst_multi_fd_sink_stop_pre (GstMultiHandleSink * mhsink)
1123 {
1124   GstMultiFdSink *mfsink = GST_MULTI_FD_SINK (mhsink);
1125
1126   gst_poll_set_flushing (mfsink->fdset, TRUE);
1127 }
1128
1129 static void
1130 gst_multi_fd_sink_stop_post (GstMultiHandleSink * mhsink)
1131 {
1132   GstMultiFdSink *mfsink = GST_MULTI_FD_SINK (mhsink);
1133
1134   if (mfsink->fdset) {
1135     gst_poll_free (mfsink->fdset);
1136     mfsink->fdset = NULL;
1137   }
1138   g_hash_table_foreach_remove (mhsink->handle_hash, multifdsink_hash_remove,
1139       mfsink);
1140 }