10 #define BACKLOG_SIZE 1048576
11 #define EPOLL_MAX_EVENTS 8192
12 #define EPOLL_TIMEOUT_MS 20
13 #define MAX_CLIENT_REQUEST 16384
16 // The file descriptor associated with this socket.
19 enum State { READING_REQUEST, SENDING_HEADER, SENDING_DATA };
22 // The HTTP request, as sent by the client. If we are in READING_REQUEST,
23 // this might not be finished.
26 // What stream we're connecting to; parsed from <request>.
27 // Not relevant for READING_REQUEST.
28 std::string stream_id;
30 // The header we want to send. This is nominally a copy of Stream::header,
31 // but since that might change on reconnects etc., we keep a local copy here.
32 // Only relevant for SENDING_HEADER; blank otherwise.
35 // Number of bytes we've sent of the header. Only relevant for SENDING_HEADER.
36 size_t header_bytes_sent;
38 // Number of bytes we've sent of data. Only relevant for SENDING_DATA.
43 // The HTTP response header, plus the video stream header (if any).
46 // The stream data itself, stored in a circular buffer.
47 char data[BACKLOG_SIZE];
49 // How many bytes <data> contains. Can very well be larger than BACKLOG_SIZE,
50 // since the buffer wraps.
58 // Start a new thread that handles clients.
64 void add_client(int sock);
65 void add_stream(const std::string &stream_id);
66 void set_header(const std::string &stream_id, const std::string &header);
67 void add_data(const std::string &stream_id, const char *data, size_t bytes);
70 pthread_t worker_thread;
72 // All variables below this line are protected by the mutex.
73 pthread_mutex_t mutex;
75 // If the thread should stop or not.
78 // Map from stream ID to stream.
79 std::map<std::string, Stream> streams;
81 // Map from file descriptor to client.
82 std::map<int, Client> clients;
84 // Used for epoll implementation (obviously).
86 epoll_event events[EPOLL_MAX_EVENTS];
88 // Clients that are in SENDING_DATA, but that we don't listen on,
89 // because we currently don't have any data for them.
90 // See put_client_to_sleep() and wake_up_all_clients().
91 std::vector<int> sleeping_clients;
93 // Recover the this pointer, and call do_work().
94 static void *do_work_thunk(void *arg);
96 // The actual worker thread.
99 void process_client(Client *client);
101 // Close a given client socket, and clean up after it.
102 void close_client(Client *client);
104 // Parse the HTTP request, construct the header, and set the client into
105 // the SENDING_HEADER state.
106 void parse_request(Client *client);
108 // Put client to sleep, since there is no more data for it; we will on
109 // longer listen on POLLOUT until we get more data. Also, it will be put
110 // in the list of clients to wake up when we do.
111 void put_client_to_sleep(Client *client);
113 // We have more data, so mark all clients that are sleeping as ready to go.
114 void wake_up_all_clients();
117 #endif // !defined(_SERVER_H)