-// Locks a pthread mutex, RAII-style.
-class MutexLock {
-public:
- MutexLock(pthread_mutex_t *mutex);
- ~MutexLock();
-
-private:
- pthread_mutex_t *mutex;
-};
-
-MutexLock::MutexLock(pthread_mutex_t *mutex)
- : mutex(mutex)
-{
- pthread_mutex_lock(mutex);
-}
-
-MutexLock::~MutexLock()
-{
- pthread_mutex_unlock(mutex);
-}
-
-struct Client {
- enum State { READING_REQUEST, SENDING_HEADER, SENDING_DATA };
- State state;
-
- // The HTTP request, as sent by the client. If we are in READING_REQUEST,
- // this might not be finished.
- string client_request;
-
-#if 0
- // What stream we're connecting to; parsed from client_request.
- // Not relevant for READING_REQUEST.
- string stream_id;
-#endif
-
- // Number of bytes we've sent of the header. Only relevant for SENDING_HEADER.
- size_t header_bytes_sent;
-
- // Number of bytes we've sent of data. Only relevant for SENDING_DATA.
- size_t bytes_sent;
-};
-
-struct Stream {
- // The HTTP response header, plus the video stream header (if any).
- string header;
-
- // The stream data itself, stored in a circular buffer.
- char data[BACKLOG_SIZE];
-
- // How many bytes <data> contains. Can very well be larger than BACKLOG_SIZE,
- // since the buffer wraps.
- size_t data_size;
-};
-
-class Server {
-public:
- Server();
-
- // Start a new thread that handles clients.
- void run();
- void add_client(int sock);
- void add_stream(const string &stream_id);
- void set_header(const string &stream_id, const string &header);
- void add_data(const string &stream_id, const char *data, size_t bytes);
-
-private:
- pthread_mutex_t mutex;
-
- // Map from stream ID to stream.
- map<string, Stream> streams;
-
- // Map from file descriptor to client.
- map<int, Client> clients;
-
- int epoll_fd;
-
- // Recover the this pointer, and call do_work().
- static void *do_work_thunk(void *arg);
-
- // The actual worker thread.
- void do_work();
-};
-