]> git.sesse.net Git - cubemap/blob - server.h
d8b9064f492f2ad12e333747b389bd1093b2564a
[cubemap] / server.h
1 #ifndef _SERVER_H
2 #define _SERVER_H 1
3
4 #include <stdint.h>
5 #include <pthread.h>
6 #include <string>
7 #include <map>
8
9 #define BACKLOG_SIZE 1048576
10
11 struct Client {
12         enum State { READING_REQUEST, SENDING_HEADER, SENDING_DATA };
13         State state;
14
15         // The HTTP request, as sent by the client. If we are in READING_REQUEST,
16         // this might not be finished.
17         std::string client_request;
18
19 #if 0
20         // What stream we're connecting to; parsed from client_request.
21         // Not relevant for READING_REQUEST.
22         string stream_id;
23 #endif
24
25         // Number of bytes we've sent of the header. Only relevant for SENDING_HEADER.
26         size_t header_bytes_sent;
27
28         // Number of bytes we've sent of data. Only relevant for SENDING_DATA.
29         size_t bytes_sent;
30 };
31
32 struct Stream {
33         // The HTTP response header, plus the video stream header (if any).
34         std::string header;
35
36         // The stream data itself, stored in a circular buffer.
37         char data[BACKLOG_SIZE];
38
39         // How many bytes <data> contains. Can very well be larger than BACKLOG_SIZE,
40         // since the buffer wraps.
41         size_t data_size;
42 };
43
44 class Server {
45 public:
46         Server();
47
48         // Start a new thread that handles clients.
49         void run();
50         void add_client(int sock);
51         void add_stream(const std::string &stream_id);
52         void set_header(const std::string &stream_id, const std::string &header);
53         void add_data(const std::string &stream_id, const char *data, size_t bytes);
54
55 private:
56         pthread_mutex_t mutex;
57
58         // Map from stream ID to stream.
59         std::map<std::string, Stream> streams;
60
61         // Map from file descriptor to client.
62         std::map<int, Client> clients;
63
64         int epoll_fd;
65
66         // Recover the this pointer, and call do_work().
67         static void *do_work_thunk(void *arg);
68
69         // The actual worker thread.
70         void do_work();
71 };
72
73 #endif  // !defined(_SERVER_H)