Merge remote-tracking branch 'origin/master' into 0.11
[platform/upstream/gstreamer.git] / gst / gstpoll.c
index 658fcf6..fed594f 100644 (file)
 #include "config.h"
 #endif
 
-#ifndef _MSC_VER
-#define _GNU_SOURCE 1
-#include <sys/poll.h>
-#include <sys/time.h>
-#endif
+#include "gst_private.h"
+#include "glib-compat-private.h"
 
 #include <sys/types.h>
 
 #include <winsock2.h>
 #define EINPROGRESS WSAEINPROGRESS
 #else
+#define _GNU_SOURCE 1
+#include <sys/poll.h>
+#include <sys/time.h>
 #include <sys/socket.h>
 #endif
 
 /* OS/X needs this because of bad headers */
 #include <string.h>
 
-#include "gst_private.h"
-
-#include "gstpoll.h"
-
-#ifndef G_OS_WIN32
-/* the poll/select call is also performed on a control socket, that way
- * we can send special commands to control it
+/* The poll() emulation on OS/X doesn't handle fds=NULL, nfds=0,
+ * so we prefer our own poll emulation.
  */
-#define SEND_COMMAND(set, command)                   \
-G_STMT_START {                                       \
-  unsigned char c = command;                         \
-  write (set->control_write_fd.fd, &c, 1);           \
-} G_STMT_END
+#if defined(BROKEN_POLL)
+#undef HAVE_POLL
+#endif
 
-#define READ_COMMAND(set, command, res)              \
-G_STMT_START {                                       \
-  res = read (set->control_read_fd.fd, &command, 1); \
-} G_STMT_END
+#include "gstpoll.h"
 
-#define GST_POLL_CMD_WAKEUP  'W'        /* restart the poll/select call */
+#define GST_CAT_DEFAULT GST_CAT_POLL
 
-#else /* G_OS_WIN32 */
+#ifdef G_OS_WIN32
 typedef struct _WinsockFd WinsockFd;
 
 struct _WinsockFd
@@ -131,15 +121,19 @@ struct _GstPoll
   GstPollMode mode;
 
   GMutex *lock;
-
+  /* array of fds, always written to and read from with lock */
   GArray *fds;
+  /* array of active fds, only written to from the waiting thread with the
+   * lock and read from with the lock or without the lock from the waiting
+   * thread */
   GArray *active_fds;
+
 #ifndef G_OS_WIN32
+  gchar buf[1];
   GstPollFD control_read_fd;
   GstPollFD control_write_fd;
 #else
   GArray *active_fds_ignored;
-
   GArray *events;
   GArray *active_events;
 
@@ -147,11 +141,88 @@ struct _GstPoll
 #endif
 
   gboolean controllable;
-  gboolean new_controllable;
-  gboolean waiting;
-  gboolean flushing;
+  volatile gint waiting;
+  volatile gint control_pending;
+  volatile gint flushing;
+  gboolean timer;
+  volatile gint rebuild;
 };
 
+static gboolean gst_poll_fd_ctl_read_unlocked (GstPoll * set, GstPollFD * fd,
+    gboolean active);
+static gboolean gst_poll_add_fd_unlocked (GstPoll * set, GstPollFD * fd);
+
+#define IS_FLUSHING(s)      (g_atomic_int_get(&(s)->flushing))
+#define SET_FLUSHING(s,val) (g_atomic_int_set(&(s)->flushing, (val)))
+
+#define INC_WAITING(s)      (G_ATOMIC_INT_ADD(&(s)->waiting, 1))
+#define DEC_WAITING(s)      (G_ATOMIC_INT_ADD(&(s)->waiting, -1))
+#define GET_WAITING(s)      (g_atomic_int_get(&(s)->waiting))
+
+#define TEST_REBUILD(s)     (g_atomic_int_compare_and_exchange(&(s)->rebuild, 1, 0))
+#define MARK_REBUILD(s)     (g_atomic_int_set(&(s)->rebuild, 1))
+
+#ifndef G_OS_WIN32
+#define WAKE_EVENT(s)       (write ((s)->control_write_fd.fd, "W", 1) == 1)
+#define RELEASE_EVENT(s)    (read ((s)->control_read_fd.fd, (s)->buf, 1) == 1)
+#else
+#define WAKE_EVENT(s)       (SetEvent ((s)->wakeup_event), errno = GetLastError () == NO_ERROR ? 0 : EACCES, errno == 0 ? 1 : 0)
+#define RELEASE_EVENT(s)    (ResetEvent ((s)->wakeup_event))
+#endif
+
+/* the poll/select call is also performed on a control socket, that way
+ * we can send special commands to control it */
+static inline gboolean
+raise_wakeup (GstPoll * set)
+{
+  gboolean result = TRUE;
+
+  if (G_ATOMIC_INT_ADD (&set->control_pending, 1) == 0) {
+    /* raise when nothing pending */
+    GST_LOG ("%p: raise", set);
+    result = WAKE_EVENT (set);
+  }
+  return result;
+}
+
+/* note how bad things can happen when the 2 threads both raise and release the
+ * wakeup. This is however not a problem because you must always pair a raise
+ * with a release */
+static inline gboolean
+release_wakeup (GstPoll * set)
+{
+  gboolean result = TRUE;
+
+  if (g_atomic_int_dec_and_test (&set->control_pending)) {
+    GST_LOG ("%p: release", set);
+    result = RELEASE_EVENT (set);
+  }
+  return result;
+}
+
+static inline gint
+release_all_wakeup (GstPoll * set)
+{
+  gint old;
+
+  while (TRUE) {
+    if (!(old = g_atomic_int_get (&set->control_pending)))
+      /* nothing pending, just exit */
+      break;
+
+    /* try to remove all pending control messages */
+    if (g_atomic_int_compare_and_exchange (&set->control_pending, old, 0)) {
+      /* we managed to remove all messages, read the control socket */
+      if (RELEASE_EVENT (set))
+        break;
+      else
+        /* retry again until we read it successfully */
+        G_ATOMIC_INT_ADD (&set->control_pending, 1);
+    }
+  }
+  return old;
+}
+
 static gint
 find_index (GArray * array, GstPollFD * fd)
 {
@@ -200,14 +271,22 @@ selectable_fds (const GstPoll * set)
 {
   guint i;
 
+  g_mutex_lock (set->lock);
   for (i = 0; i < set->fds->len; i++) {
     struct pollfd *pfd = &g_array_index (set->fds, struct pollfd, i);
 
     if (pfd->fd >= FD_SETSIZE)
-      return FALSE;
+      goto too_many;
   }
+  g_mutex_unlock (set->lock);
 
   return TRUE;
+
+too_many:
+  {
+    g_mutex_unlock (set->lock);
+    return FALSE;
+  }
 }
 
 /* check if the timeout will convert to a timeout value used for poll()
@@ -258,13 +337,15 @@ choose_mode (const GstPoll * set, GstClockTime timeout)
 
 #ifndef G_OS_WIN32
 static gint
-pollfd_to_fd_set (GstPoll * set, fd_set * readfds, fd_set * writefds)
+pollfd_to_fd_set (GstPoll * set, fd_set * readfds, fd_set * writefds,
+    fd_set * errorfds)
 {
   gint max_fd = -1;
   guint i;
 
   FD_ZERO (readfds);
   FD_ZERO (writefds);
+  FD_ZERO (errorfds);
 
   g_mutex_lock (set->lock);
 
@@ -276,7 +357,9 @@ pollfd_to_fd_set (GstPoll * set, fd_set * readfds, fd_set * writefds)
         FD_SET (pfd->fd, readfds);
       if (pfd->events & POLLOUT)
         FD_SET (pfd->fd, writefds);
-      if (pfd->fd > max_fd)
+      if (pfd->events)
+        FD_SET (pfd->fd, errorfds);
+      if (pfd->fd > max_fd && (pfd->events & (POLLIN | POLLOUT)))
         max_fd = pfd->fd;
     }
   }
@@ -287,7 +370,8 @@ pollfd_to_fd_set (GstPoll * set, fd_set * readfds, fd_set * writefds)
 }
 
 static void
-fd_set_to_pollfd (GstPoll * set, fd_set * readfds, fd_set * writefds)
+fd_set_to_pollfd (GstPoll * set, fd_set * readfds, fd_set * writefds,
+    fd_set * errorfds)
 {
   guint i;
 
@@ -297,10 +381,13 @@ fd_set_to_pollfd (GstPoll * set, fd_set * readfds, fd_set * writefds)
     struct pollfd *pfd = &g_array_index (set->active_fds, struct pollfd, i);
 
     if (pfd->fd < FD_SETSIZE) {
+      pfd->revents = 0;
       if (FD_ISSET (pfd->fd, readfds))
         pfd->revents |= POLLIN;
       if (FD_ISSET (pfd->fd, writefds))
         pfd->revents |= POLLOUT;
+      if (FD_ISSET (pfd->fd, errorfds))
+        pfd->revents |= POLLERR;
     }
   }
 
@@ -445,15 +532,17 @@ gst_poll_collect_winsock_events (GstPoll * set)
 #endif
 
 /**
- * gst_poll_new:
+ * gst_poll_new: (skip)
  * @controllable: whether it should be possible to control a wait.
  *
  * Create a new file descriptor set. If @controllable, it
  * is possible to restart or flush a call to gst_poll_wait() with
  * gst_poll_restart() and gst_poll_set_flushing() respectively.
  *
- * Returns: a new #GstPoll, or %NULL in case of an error. Free with
- * gst_poll_free().
+ * Free-function: gst_poll_free
+ *
+ * Returns: (transfer full): a new #GstPoll, or %NULL in case of an error.
+ *     Free with gst_poll_free().
  *
  * Since: 0.10.18
  */
@@ -462,6 +551,8 @@ gst_poll_new (gboolean controllable)
 {
   GstPoll *nset;
 
+  GST_DEBUG ("controllable : %d", controllable);
+
   nset = g_slice_new0 (GstPoll);
   nset->lock = g_mutex_new ();
 #ifndef G_OS_WIN32
@@ -470,6 +561,21 @@ gst_poll_new (gboolean controllable)
   nset->active_fds = g_array_new (FALSE, FALSE, sizeof (struct pollfd));
   nset->control_read_fd.fd = -1;
   nset->control_write_fd.fd = -1;
+  {
+    gint control_sock[2];
+
+    if (socketpair (PF_UNIX, SOCK_STREAM, 0, control_sock) < 0)
+      goto no_socket_pair;
+
+    fcntl (control_sock[0], F_SETFL, O_NONBLOCK);
+    fcntl (control_sock[1], F_SETFL, O_NONBLOCK);
+
+    nset->control_read_fd.fd = control_sock[0];
+    nset->control_write_fd.fd = control_sock[1];
+
+    gst_poll_add_fd_unlocked (nset, &nset->control_read_fd);
+    gst_poll_fd_ctl_read_unlocked (nset, &nset->control_read_fd, TRUE);
+  }
 #else
   nset->mode = GST_POLL_MODE_WINDOWS;
   nset->fds = g_array_new (FALSE, FALSE, sizeof (WinsockFd));
@@ -481,22 +587,59 @@ gst_poll_new (gboolean controllable)
   nset->wakeup_event = CreateEvent (NULL, TRUE, FALSE, NULL);
 #endif
 
-  if (!gst_poll_set_controllable (nset, controllable))
-    goto not_controllable;
+  /* ensure (re)build, though already sneakily set in non-windows case */
+  MARK_REBUILD (nset);
+
+  nset->controllable = controllable;
 
   return nset;
 
   /* ERRORS */
-not_controllable:
+#ifndef G_OS_WIN32
+no_socket_pair:
   {
+    GST_WARNING ("%p: can't create socket pair !", nset);
     gst_poll_free (nset);
     return NULL;
   }
+#endif
+}
+
+/**
+ * gst_poll_new_timer: (skip)
+ *
+ * Create a new poll object that can be used for scheduling cancellable
+ * timeouts.
+ *
+ * A timeout is performed with gst_poll_wait(). Multiple timeouts can be
+ * performed from different threads. 
+ *
+ * Free-function: gst_poll_free
+ *
+ * Returns: (transfer full): a new #GstPoll, or %NULL in case of an error.
+ *     Free with gst_poll_free().
+ *
+ * Since: 0.10.23
+ */
+GstPoll *
+gst_poll_new_timer (void)
+{
+  GstPoll *poll;
+
+  /* make a new controllable poll set */
+  if (!(poll = gst_poll_new (TRUE)))
+    goto done;
+
+  /* we are a timer */
+  poll->timer = TRUE;
+
+done:
+  return poll;
 }
 
 /**
  * gst_poll_free:
- * @set: a file descriptor set.
+ * @set: (transfer full): a file descriptor set.
  *
  * Free a file descriptor set.
  *
@@ -507,6 +650,8 @@ gst_poll_free (GstPoll * set)
 {
   g_return_if_fail (set != NULL);
 
+  GST_DEBUG ("%p: freeing", set);
+
 #ifndef G_OS_WIN32
   if (set->control_write_fd.fd >= 0)
     close (set->control_write_fd.fd);
@@ -534,6 +679,35 @@ gst_poll_free (GstPoll * set)
 }
 
 /**
+ * gst_poll_get_read_gpollfd:
+ * @set: a #GstPoll
+ * @fd: a #GPollFD
+ *
+ * Get a GPollFD for the reading part of the control socket. This is useful when
+ * integrating with a GSource and GMainLoop.
+ *
+ * Since: 0.10.32
+ */
+void
+gst_poll_get_read_gpollfd (GstPoll * set, GPollFD * fd)
+{
+  g_return_if_fail (set != NULL);
+  g_return_if_fail (fd != NULL);
+
+#ifndef G_OS_WIN32
+  fd->fd = set->control_read_fd.fd;
+#else
+#if GLIB_SIZEOF_VOID_P == 8
+  fd->fd = (gint64) set->wakeup_event;
+#else
+  fd->fd = (gint) set->wakeup_event;
+#endif
+#endif
+  fd->events = G_IO_IN | G_IO_HUP | G_IO_ERR;
+  fd->revents = 0;
+}
+
+/**
  * gst_poll_fd_init:
  * @fd: a #GstPollFD
  *
@@ -556,6 +730,8 @@ gst_poll_add_fd_unlocked (GstPoll * set, GstPollFD * fd)
 {
   gint idx;
 
+  GST_DEBUG ("%p: fd (fd:%d, idx:%d)", set, fd->fd, fd->idx);
+
   idx = find_index (set->fds, fd);
   if (idx < 0) {
 #ifndef G_OS_WIN32
@@ -583,6 +759,9 @@ gst_poll_add_fd_unlocked (GstPoll * set, GstPollFD * fd)
 
     fd->idx = set->fds->len - 1;
 #endif
+    MARK_REBUILD (set);
+  } else {
+    GST_WARNING ("%p: couldn't find fd !", set);
   }
 
   return TRUE;
@@ -637,6 +816,9 @@ gst_poll_remove_fd (GstPoll * set, GstPollFD * fd)
   g_return_val_if_fail (fd != NULL, FALSE);
   g_return_val_if_fail (fd->fd >= 0, FALSE);
 
+
+  GST_DEBUG ("%p: fd (fd:%d, idx:%d)", set, fd->fd, fd->idx);
+
   g_mutex_lock (set->lock);
 
   /* get the index, -1 is an fd that is not added */
@@ -653,6 +835,9 @@ gst_poll_remove_fd (GstPoll * set, GstPollFD * fd)
 
     /* mark fd as removed by setting the index to -1 */
     fd->idx = -1;
+    MARK_REBUILD (set);
+  } else {
+    GST_WARNING ("%p: couldn't find fd !", set);
   }
 
   g_mutex_unlock (set->lock);
@@ -682,6 +867,9 @@ gst_poll_fd_ctl_write (GstPoll * set, GstPollFD * fd, gboolean active)
   g_return_val_if_fail (fd != NULL, FALSE);
   g_return_val_if_fail (fd->fd >= 0, FALSE);
 
+  GST_DEBUG ("%p: fd (fd:%d, idx:%d), active : %d", set,
+      fd->fd, fd->idx, active);
+
   g_mutex_lock (set->lock);
 
   idx = find_index (set->fds, fd);
@@ -693,9 +881,15 @@ gst_poll_fd_ctl_write (GstPoll * set, GstPollFD * fd, gboolean active)
       pfd->events |= POLLOUT;
     else
       pfd->events &= ~POLLOUT;
+
+    GST_LOG ("pfd->events now %d (POLLOUT:%d)", pfd->events, POLLOUT);
 #else
-    gst_poll_update_winsock_event_mask (set, idx, FD_WRITE, active);
+    gst_poll_update_winsock_event_mask (set, idx, FD_WRITE | FD_CONNECT,
+        active);
 #endif
+    MARK_REBUILD (set);
+  } else {
+    GST_WARNING ("%p: couldn't find fd !", set);
   }
 
   g_mutex_unlock (set->lock);
@@ -708,6 +902,9 @@ gst_poll_fd_ctl_read_unlocked (GstPoll * set, GstPollFD * fd, gboolean active)
 {
   gint idx;
 
+  GST_DEBUG ("%p: fd (fd:%d, idx:%d), active : %d", set,
+      fd->fd, fd->idx, active);
+
   idx = find_index (set->fds, fd);
 
   if (idx >= 0) {
@@ -721,6 +918,9 @@ gst_poll_fd_ctl_read_unlocked (GstPoll * set, GstPollFD * fd, gboolean active)
 #else
     gst_poll_update_winsock_event_mask (set, idx, FD_READ | FD_ACCEPT, active);
 #endif
+    MARK_REBUILD (set);
+  } else {
+    GST_WARNING ("%p: couldn't find fd !", set);
   }
 
   return idx >= 0;
@@ -790,6 +990,7 @@ gst_poll_fd_ignored (GstPoll * set, GstPollFD * fd)
     WinsockFd *wfd = &g_array_index (set->fds, WinsockFd, idx);
 
     wfd->ignored_event_mask = wfd->event_mask & (FD_READ | FD_WRITE);
+    MARK_REBUILD (set);
   }
 
   g_mutex_unlock (set->lock);
@@ -817,6 +1018,8 @@ gst_poll_fd_has_closed (const GstPoll * set, GstPollFD * fd)
   g_return_val_if_fail (fd != NULL, FALSE);
   g_return_val_if_fail (fd->fd >= 0, FALSE);
 
+  GST_DEBUG ("%p: fd (fd:%d, idx:%d)", set, fd->fd, fd->idx);
+
   g_mutex_lock (set->lock);
 
   idx = find_index (set->active_fds, fd);
@@ -830,6 +1033,8 @@ gst_poll_fd_has_closed (const GstPoll * set, GstPollFD * fd)
 
     res = (wfd->events.lNetworkEvents & FD_CLOSE) != 0;
 #endif
+  } else {
+    GST_WARNING ("%p: couldn't find fd !", set);
   }
 
   g_mutex_unlock (set->lock);
@@ -858,6 +1063,8 @@ gst_poll_fd_has_error (const GstPoll * set, GstPollFD * fd)
   g_return_val_if_fail (fd != NULL, FALSE);
   g_return_val_if_fail (fd->fd >= 0, FALSE);
 
+  GST_DEBUG ("%p: fd (fd:%d, idx:%d)", set, fd->fd, fd->idx);
+
   g_mutex_lock (set->lock);
 
   idx = find_index (set->active_fds, fd);
@@ -872,8 +1079,11 @@ gst_poll_fd_has_error (const GstPoll * set, GstPollFD * fd)
     res = (wfd->events.iErrorCode[FD_CLOSE_BIT] != 0) ||
         (wfd->events.iErrorCode[FD_READ_BIT] != 0) ||
         (wfd->events.iErrorCode[FD_WRITE_BIT] != 0) ||
-        (wfd->events.iErrorCode[FD_ACCEPT_BIT] != 0);
+        (wfd->events.iErrorCode[FD_ACCEPT_BIT] != 0) ||
+        (wfd->events.iErrorCode[FD_CONNECT_BIT] != 0);
 #endif
+  } else {
+    GST_WARNING ("%p: couldn't find fd !", set);
   }
 
   g_mutex_unlock (set->lock);
@@ -887,6 +1097,8 @@ gst_poll_fd_can_read_unlocked (const GstPoll * set, GstPollFD * fd)
   gboolean res = FALSE;
   gint idx;
 
+  GST_DEBUG ("%p: fd (fd:%d, idx:%d)", set, fd->fd, fd->idx);
+
   idx = find_index (set->active_fds, fd);
   if (idx >= 0) {
 #ifndef G_OS_WIN32
@@ -898,6 +1110,8 @@ gst_poll_fd_can_read_unlocked (const GstPoll * set, GstPollFD * fd)
 
     res = (wfd->events.lNetworkEvents & (FD_READ | FD_ACCEPT)) != 0;
 #endif
+  } else {
+    GST_WARNING ("%p: couldn't find fd !", set);
   }
 
   return res;
@@ -953,6 +1167,8 @@ gst_poll_fd_can_write (const GstPoll * set, GstPollFD * fd)
   g_return_val_if_fail (fd != NULL, FALSE);
   g_return_val_if_fail (fd->fd >= 0, FALSE);
 
+  GST_DEBUG ("%p: fd (fd:%d, idx:%d)", set, fd->fd, fd->idx);
+
   g_mutex_lock (set->lock);
 
   idx = find_index (set->active_fds, fd);
@@ -966,6 +1182,8 @@ gst_poll_fd_can_write (const GstPoll * set, GstPollFD * fd)
 
     res = (wfd->events.lNetworkEvents & FD_WRITE) != 0;
 #endif
+  } else {
+    GST_WARNING ("%p: couldn't find fd !", set);
   }
 
   g_mutex_unlock (set->lock);
@@ -973,42 +1191,6 @@ gst_poll_fd_can_write (const GstPoll * set, GstPollFD * fd)
   return res;
 }
 
-static void
-gst_poll_check_ctrl_commands (GstPoll * set, gint res, gboolean * restarting)
-{
-  /* check if the poll/select was aborted due to a command */
-  if (set->controllable) {
-#ifndef G_OS_WIN32
-    while (TRUE) {
-      guchar cmd;
-      gint result;
-
-      /* we do not check the read status of the control socket here because
-       * there may have been a write to the socket between the time the
-       * poll/select finished and before we got the mutex back, and we need
-       * to clear out the control socket before leaving */
-      READ_COMMAND (set, cmd, result);
-      if (result <= 0) {
-        /* no more commands, quit the loop */
-        break;
-      }
-
-      /* if the control socket is the only socket with activity when we get
-       * here, we restart the _wait operation, else we allow the caller to
-       * process the other file descriptors */
-      if (res == 1 &&
-          gst_poll_fd_can_read_unlocked (set, &set->control_read_fd))
-        *restarting = TRUE;
-    }
-#else
-    if (WaitForSingleObject (set->wakeup_event, 0) == WAIT_OBJECT_0) {
-      ResetEvent (set->wakeup_event);
-      *restarting = TRUE;
-    }
-#endif
-  }
-}
-
 /**
  * gst_poll_wait:
  * @set: a #GstPoll.
@@ -1017,8 +1199,13 @@ gst_poll_check_ctrl_commands (GstPoll * set, gint res, gboolean * restarting)
  * Wait for activity on the file descriptors in @set. This function waits up to
  * the specified @timeout.  A timeout of #GST_CLOCK_TIME_NONE waits forever.
  *
- * When this function is called from multiple threads, -1 will be returned with
- * errno set to EPERM.
+ * For #GstPoll objects created with gst_poll_new(), this function can only be
+ * called from a single thread at a time.  If called from multiple threads,
+ * -1 will be returned with errno set to EPERM.
+ *
+ * This is not true for timer #GstPoll objects created with
+ * gst_poll_new_timer(), where it is allowed to have multiple threads waiting
+ * simultaneously.
  *
  * Returns: The number of #GstPollFD in @set that have activity or 0 when no
  * activity was detected after @timeout. If an error occurs, -1 is returned
@@ -1030,22 +1217,27 @@ gint
 gst_poll_wait (GstPoll * set, GstClockTime timeout)
 {
   gboolean restarting;
+  gboolean is_timer;
   int res;
+  gint old_waiting;
 
   g_return_val_if_fail (set != NULL, -1);
 
-  g_mutex_lock (set->lock);
+  GST_DEBUG ("timeout :%" GST_TIME_FORMAT, GST_TIME_ARGS (timeout));
+
+  is_timer = set->timer;
+
+  /* add one more waiter */
+  old_waiting = INC_WAITING (set);
 
-  /* we cannot wait from multiple threads */
-  if (set->waiting)
+  /* we cannot wait from multiple threads unless we are a timer */
+  if (G_UNLIKELY (old_waiting > 0 && !is_timer))
     goto already_waiting;
 
-  /* flushing, exit immediatly */
-  if (set->flushing)
+  /* flushing, exit immediately */
+  if (G_UNLIKELY (IS_FLUSHING (set)))
     goto flushing;
 
-  set->waiting = TRUE;
-
   do {
     GstPollMode mode;
 
@@ -1054,16 +1246,18 @@ gst_poll_wait (GstPoll * set, GstClockTime timeout)
 
     mode = choose_mode (set, timeout);
 
+    if (TEST_REBUILD (set)) {
+      g_mutex_lock (set->lock);
 #ifndef G_OS_WIN32
-    g_array_set_size (set->active_fds, set->fds->len);
-    memcpy (set->active_fds->data, set->fds->data,
-        set->fds->len * sizeof (struct pollfd));
+      g_array_set_size (set->active_fds, set->fds->len);
+      memcpy (set->active_fds->data, set->fds->data,
+          set->fds->len * sizeof (struct pollfd));
 #else
-    if (!gst_poll_prepare_winsock_active_sets (set))
-      goto winsock_error;
+      if (!gst_poll_prepare_winsock_active_sets (set))
+        goto winsock_error;
 #endif
-
-    g_mutex_unlock (set->lock);
+      g_mutex_unlock (set->lock);
+    }
 
     switch (mode) {
       case GST_POLL_MODE_AUTO:
@@ -1124,9 +1318,10 @@ gst_poll_wait (GstPoll * set, GstClockTime timeout)
 #ifndef G_OS_WIN32
         fd_set readfds;
         fd_set writefds;
+        fd_set errorfds;
         gint max_fd;
 
-        max_fd = pollfd_to_fd_set (set, &readfds, &writefds);
+        max_fd = pollfd_to_fd_set (set, &readfds, &writefds, &errorfds);
 
         if (mode == GST_POLL_MODE_SELECT) {
           struct timeval tv;
@@ -1139,7 +1334,9 @@ gst_poll_wait (GstPoll * set, GstClockTime timeout)
             tvptr = NULL;
           }
 
-          res = select (max_fd + 1, &readfds, &writefds, NULL, tvptr);
+          GST_DEBUG ("Calling select");
+          res = select (max_fd + 1, &readfds, &writefds, &errorfds, tvptr);
+          GST_DEBUG ("After select, res:%d", res);
         } else {
 #ifdef HAVE_PSELECT
           struct timespec ts;
@@ -1152,12 +1349,15 @@ gst_poll_wait (GstPoll * set, GstClockTime timeout)
             tsptr = NULL;
           }
 
-          res = pselect (max_fd + 1, &readfds, &writefds, NULL, tsptr, NULL);
+          GST_DEBUG ("Calling pselect");
+          res =
+              pselect (max_fd + 1, &readfds, &writefds, &errorfds, tsptr, NULL);
+          GST_DEBUG ("After pselect, res:%d", res);
 #endif
         }
 
-        if (res > 0) {
-          fd_set_to_pollfd (set, &readfds, &writefds);
+        if (res >= 0) {
+          fd_set_to_pollfd (set, &readfds, &writefds, &errorfds);
         }
 #else /* G_OS_WIN32 */
         g_assert_not_reached ();
@@ -1181,8 +1381,13 @@ gst_poll_wait (GstPoll * set, GstClockTime timeout)
           t = 0;
         }
 
-        wait_ret = WSAWaitForMultipleEvents (set->active_events->len,
-            (HANDLE *) set->active_events->data, FALSE, t, FALSE);
+        if (set->active_events->len != 0) {
+          wait_ret = WSAWaitForMultipleEvents (set->active_events->len,
+              (HANDLE *) set->active_events->data, FALSE, t, FALSE);
+        } else {
+          wait_ret = WSA_WAIT_FAILED;
+          WSASetLastError (WSA_INVALID_PARAMETER);
+        }
 
         if (ignore_count == 0 && wait_ret == WSA_WAIT_TIMEOUT) {
           res = 0;
@@ -1205,44 +1410,47 @@ gst_poll_wait (GstPoll * set, GstClockTime timeout)
       }
     }
 
-    g_mutex_lock (set->lock);
-
-    gst_poll_check_ctrl_commands (set, res, &restarting);
-
-    /* update the controllable state if needed */
-    set->controllable = set->new_controllable;
-
-    if (set->flushing) {
-      /* we got woken up and we are flushing, we need to stop */
-      errno = EBUSY;
-      res = -1;
-      break;
+    if (!is_timer) {
+      /* Applications needs to clear the control socket themselves for timer
+       * polls.
+       * For other polls, we need to clear the control socket. If there was only
+       * one socket with activity and it was the control socket, we need to
+       * restart */
+      if (release_all_wakeup (set) > 0 && res == 1)
+        restarting = TRUE;
     }
-  } while (restarting);
 
-  set->waiting = FALSE;
+    /* we got woken up and we are flushing, we need to stop */
+    if (G_UNLIKELY (IS_FLUSHING (set)))
+      goto flushing;
 
-  g_mutex_unlock (set->lock);
+  } while (G_UNLIKELY (restarting));
+
+  DEC_WAITING (set);
 
   return res;
 
   /* ERRORS */
 already_waiting:
   {
-    g_mutex_unlock (set->lock);
+    GST_LOG ("%p: we are already waiting", set);
+    DEC_WAITING (set);
     errno = EPERM;
     return -1;
   }
 flushing:
   {
-    g_mutex_unlock (set->lock);
+    GST_LOG ("%p: we are flushing", set);
+    DEC_WAITING (set);
     errno = EBUSY;
     return -1;
   }
 #ifdef G_OS_WIN32
 winsock_error:
   {
+    GST_LOG ("%p: winsock error", set);
     g_mutex_unlock (set->lock);
+    DEC_WAITING (set);
     return -1;
   }
 #endif
@@ -1266,45 +1474,11 @@ gst_poll_set_controllable (GstPoll * set, gboolean controllable)
 {
   g_return_val_if_fail (set != NULL, FALSE);
 
-  g_mutex_lock (set->lock);
-
-#ifndef G_OS_WIN32
-  if (controllable && set->control_read_fd.fd < 0) {
-    gint control_sock[2];
-
-    if (socketpair (PF_UNIX, SOCK_STREAM, 0, control_sock) < 0)
-      goto no_socket_pair;
+  GST_LOG ("%p: controllable : %d", set, controllable);
 
-    fcntl (control_sock[0], F_SETFL, O_NONBLOCK);
-    fcntl (control_sock[1], F_SETFL, O_NONBLOCK);
-
-    set->control_read_fd.fd = control_sock[0];
-    set->control_write_fd.fd = control_sock[1];
-
-    gst_poll_add_fd_unlocked (set, &set->control_read_fd);
-  }
-
-  if (set->control_read_fd.fd >= 0)
-    gst_poll_fd_ctl_read_unlocked (set, &set->control_read_fd, controllable);
-#endif
-
-  /* delay the change of the controllable state if we are waiting */
-  set->new_controllable = controllable;
-  if (!set->waiting)
-    set->controllable = controllable;
-
-  g_mutex_unlock (set->lock);
+  set->controllable = controllable;
 
   return TRUE;
-
-  /* ERRORS */
-#ifndef G_OS_WIN32
-no_socket_pair:
-  {
-    g_mutex_unlock (set->lock);
-    return FALSE;
-  }
-#endif
 }
 
 /**
@@ -1323,19 +1497,11 @@ gst_poll_restart (GstPoll * set)
 {
   g_return_if_fail (set != NULL);
 
-  g_mutex_lock (set->lock);
-
-  if (set->controllable && set->waiting) {
-#ifndef G_OS_WIN32
-    /* if we are waiting, we can send the command, else we do not have to
-     * bother, future calls will automatically pick up the new fdset */
-    SEND_COMMAND (set, GST_POLL_CMD_WAKEUP);
-#else
-    SetEvent (set->wakeup_event);
-#endif
+  if (set->controllable && GET_WAITING (set) > 0) {
+    /* we are controllable and waiting, wake up the waiter. The socket will be
+     * cleared by the _wait() thread and the poll will be restarted */
+    raise_wakeup (set);
   }
-
-  g_mutex_unlock (set->lock);
 }
 
 /**
@@ -1355,21 +1521,72 @@ gst_poll_set_flushing (GstPoll * set, gboolean flushing)
 {
   g_return_if_fail (set != NULL);
 
-  g_mutex_lock (set->lock);
+  GST_LOG ("%p: flushing: %d", set, flushing);
 
   /* update the new state first */
-  set->flushing = flushing;
+  SET_FLUSHING (set, flushing);
 
-  if (flushing && set->controllable && set->waiting) {
+  if (flushing && set->controllable && GET_WAITING (set) > 0) {
     /* we are flushing, controllable and waiting, wake up the waiter. When we
      * stop the flushing operation we don't clear the wakeup fd here, this will
      * happen in the _wait() thread. */
-#ifndef G_OS_WIN32
-    SEND_COMMAND (set, GST_POLL_CMD_WAKEUP);
-#else
-    SetEvent (set->wakeup_event);
-#endif
+    raise_wakeup (set);
   }
+}
 
-  g_mutex_unlock (set->lock);
+/**
+ * gst_poll_write_control:
+ * @set: a #GstPoll.
+ *
+ * Write a byte to the control socket of the controllable @set.
+ * This function is mostly useful for timer #GstPoll objects created with
+ * gst_poll_new_timer(). 
+ *
+ * It will make any current and future gst_poll_wait() function return with
+ * 1, meaning the control socket is set. After an equal amount of calls to
+ * gst_poll_read_control() have been performed, calls to gst_poll_wait() will
+ * block again until their timeout expired.
+ *
+ * Returns: %TRUE on success. %FALSE when @set is not controllable or when the
+ * byte could not be written.
+ *
+ * Since: 0.10.23
+ */
+gboolean
+gst_poll_write_control (GstPoll * set)
+{
+  gboolean res;
+
+  g_return_val_if_fail (set != NULL, FALSE);
+  g_return_val_if_fail (set->timer, FALSE);
+
+  res = raise_wakeup (set);
+
+  return res;
+}
+
+/**
+ * gst_poll_read_control:
+ * @set: a #GstPoll.
+ *
+ * Read a byte from the control socket of the controllable @set.
+ * This function is mostly useful for timer #GstPoll objects created with
+ * gst_poll_new_timer(). 
+ *
+ * Returns: %TRUE on success. %FALSE when @set is not controllable or when there
+ * was no byte to read.
+ *
+ * Since: 0.10.23
+ */
+gboolean
+gst_poll_read_control (GstPoll * set)
+{
+  gboolean res;
+
+  g_return_val_if_fail (set != NULL, FALSE);
+  g_return_val_if_fail (set->timer, FALSE);
+
+  res = release_wakeup (set);
+
+  return res;
 }