summaryrefslogtreecommitdiffstats
path: root/xbmc/platform/linux/FDEventMonitor.h
blob: c0b8395579d29d0fccbdeb52e2756c15012656f9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/*
 *  Copyright (C) 2014-2018 Team Kodi
 *  This file is part of Kodi - https://kodi.tv
 *
 *  SPDX-License-Identifier: GPL-2.0-or-later
 *  See LICENSES/README.md for more information.
 */

#pragma once

#include "platform/Platform.h"
#include "threads/CriticalSection.h"
#include "threads/Thread.h"

#include <map>
#include <vector>

#include <sys/epoll.h>

/**
 * Monitor a file descriptor with callback on poll() events.
 */
class CFDEventMonitor : public IPlatformService, private CThread
{
public:

  typedef void (*EventCallback)(int id, int fd, short revents, void *data);

  struct MonitoredFD
  {
    int fd = -1; /**< File descriptor to be monitored */
    short events = 0; /**< Events to be monitored (see poll(2)) */

    EventCallback callback = nullptr; /** Callback to be called on events */
    void *callbackData = nullptr; /** data parameter for EventCallback */

    MonitoredFD(int fd_, short events_, EventCallback callback_, void *callbackData_) :
      fd(fd_), events(events_), callback(callback_), callbackData(callbackData_) {}
    MonitoredFD() = default;
  };

  CFDEventMonitor();
  ~CFDEventMonitor() override;

  void AddFD(const MonitoredFD& monitoredFD, int& id);
  void AddFDs(const std::vector<MonitoredFD>& monitoredFDs, std::vector<int>& ids);

  void RemoveFD(int id);
  void RemoveFDs(const std::vector<int>& ids);

protected:
  void Process() override;

private:
  void AddFDLocked(const MonitoredFD& monitoredFD, int& id);

  void AddPollDesc(int id, int fd, short events);
  void UpdatePollDescs();

  void StartMonitoring();
  void InterruptPoll();

  std::map<int, MonitoredFD> m_monitoredFDs;

  /* these are kept synchronized */
  std::vector<int> m_monitoredFDbyPollDescs;
  std::vector<struct pollfd> m_pollDescs;

  int m_nextID = 0;
  int m_wakeupfd = -1;

  CCriticalSection m_mutex;
  CCriticalSection m_pollMutex;
};