]> git.sesse.net Git - cubemap/blob - cubemap.cpp
643f1a8b0b6c7a0e1bc274a47ae65ebf7e18df76
[cubemap] / cubemap.cpp
1 #include <stdio.h>
2 #include <string.h>
3 #include <stdint.h>
4 #include <assert.h>
5 #include <arpa/inet.h>
6 #include <curl/curl.h>
7 #include <sys/socket.h>
8 #include <pthread.h>
9 #include <sys/types.h>
10 #include <sys/ioctl.h>
11 #include <sys/epoll.h>
12 #include <errno.h>
13 #include <vector>
14 #include <string>
15 #include <map>
16 #include "metacube.h"
17
18 #define NUM_SERVERS 4
19 #define STREAM_ID "stream"
20 #define STREAM_URL "http://gruessi.zrh.sesse.net:4013/"
21 #define BACKLOG_SIZE 1048576
22 #define PORT 9094
23
24 using namespace std;
25
26 // Locks a pthread mutex, RAII-style.
27 class MutexLock {
28 public:
29         MutexLock(pthread_mutex_t *mutex);
30         ~MutexLock();
31
32 private:
33         pthread_mutex_t *mutex;
34 };
35         
36 MutexLock::MutexLock(pthread_mutex_t *mutex)
37         : mutex(mutex)
38 {
39         pthread_mutex_lock(mutex);
40 }
41
42 MutexLock::~MutexLock()
43 {
44         pthread_mutex_unlock(mutex);
45 }
46
47 struct Client {
48         enum State { READING_REQUEST, SENDING_HEADER, SENDING_DATA };
49         State state;
50
51         // The HTTP request, as sent by the client. If we are in READING_REQUEST,
52         // this might not be finished.
53         string client_request;
54
55 #if 0
56         // What stream we're connecting to; parsed from client_request.
57         // Not relevant for READING_REQUEST.
58         string stream_id;
59 #endif
60
61         // Number of bytes we've sent of the header. Only relevant for SENDING_HEADER.
62         size_t header_bytes_sent;
63
64         // Number of bytes we've sent of data. Only relevant for SENDING_DATA.
65         size_t bytes_sent;
66 };
67
68 struct Stream {
69         // The HTTP response header, plus the video stream header (if any).
70         string header;
71
72         // The stream data itself, stored in a circular buffer.
73         char data[BACKLOG_SIZE];
74
75         // How many bytes <data> contains. Can very well be larger than BACKLOG_SIZE,
76         // since the buffer wraps.
77         size_t data_size;
78 };
79
80 class Server {
81 public:
82         Server();
83
84         // Start a new thread that handles clients.
85         void run();
86         void add_client(int sock);
87         void add_stream(const string &stream_id);
88         void set_header(const string &stream_id, const string &header);
89         void add_data(const string &stream_id, const char *data, size_t bytes);
90
91 private:
92         pthread_mutex_t mutex;
93
94         // Map from stream ID to stream.
95         map<string, Stream> streams;
96
97         // Map from file descriptor to client.
98         map<int, Client> clients;
99
100         int epoll_fd;
101
102         // Recover the this pointer, and call do_work().
103         static void *do_work_thunk(void *arg);
104
105         // The actual worker thread.
106         void do_work();
107 };
108
109 Server *servers = NULL;
110
111 Server::Server()
112 {
113         pthread_mutex_init(&mutex, NULL);
114
115         epoll_fd = epoll_create(1024);  // Size argument is ignored.
116         if (epoll_fd == -1) {
117                 perror("epoll_fd");
118                 exit(1);
119         }
120 }
121
122 void Server::run()
123 {
124         pthread_t thread;
125         pthread_create(&thread, NULL, Server::do_work_thunk, this);
126 }
127
128 void *Server::do_work_thunk(void *arg)
129 {
130         Server *server = static_cast<Server *>(arg);
131         server->do_work();
132         return NULL;
133 }
134
135 void Server::do_work()
136 {
137         for ( ;; ) {
138                 MutexLock lock(&mutex);
139                 printf("server thread running\n");
140                 sleep(1);
141         }
142 }
143         
144 void Server::add_client(int sock)
145 {
146         MutexLock lock(&mutex);
147         Client new_client;
148         new_client.state = Client::READING_REQUEST;
149         new_client.header_bytes_sent = 0;
150         new_client.bytes_sent = 0;
151
152         clients.insert(make_pair(sock, new_client));
153
154         // Start listening on data from this socket.
155         epoll_event ev;
156         ev.events = EPOLLIN;
157         ev.data.fd = sock;
158         if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock, &ev) == -1) {
159                 perror("epoll_ctl(EPOLL_CTL_ADD)");
160                 exit(1);
161         }
162 }
163         
164 void Server::add_stream(const string &stream_id)
165 {
166         // TODO
167 }
168         
169 void Server::set_header(const string &stream_id, const string &header)
170 {
171         // TODO
172         printf("got header! %lu bytes\n", header.size());
173 }
174         
175 void Server::add_data(const string &stream_id, const char *data, size_t bytes)
176 {
177         // TODO
178 }
179
180 class Input {
181 public:
182         Input(const string &stream_id);
183
184         // Connect to the given URL and start streaming.
185         // WARNING: Currently this blocks; it does not run in a separate thread!
186         void run(const string &url);
187
188 private:
189         // Recovers the this pointer and calls curl_callback().
190         static size_t curl_callback_thunk(char *ptr, size_t size, size_t nmemb, void *userdata);
191
192         // Stores the given data, looks for Metacube blocks (skipping data if needed),
193         // and calls process_block() for each one.
194         void curl_callback(char *ptr, size_t bytes);
195         void process_block(const char *data, uint32_t size, uint32_t flags);
196
197         // Drops <num_bytes> bytes from the head of <pending_data>,
198         // and outputs a warning.
199         void drop_pending_data(size_t num_bytes);
200
201         string stream_id;
202
203         // Data we have received but not fully processed yet.
204         vector<char> pending_data;
205
206         // If <pending_data> starts with a Metacube header,
207         // this is true.
208         bool has_metacube_header;
209 };
210
211 Input::Input(const string &stream_id)
212         : stream_id(stream_id),
213           has_metacube_header(false)
214 {
215 }
216
217 void Input::run(const string &url)
218 {
219         CURL *curl = curl_easy_init();
220         curl_easy_setopt(curl, CURLOPT_URL, STREAM_URL);
221         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &Input::curl_callback_thunk);
222         curl_easy_setopt(curl, CURLOPT_WRITEDATA, this);
223         curl_easy_perform(curl);
224 }
225
226 size_t Input::curl_callback_thunk(char *ptr, size_t size, size_t nmemb, void *userdata)
227 {
228         Input *input = static_cast<Input *>(userdata);
229         size_t bytes = size * nmemb;
230         input->curl_callback(ptr, bytes);       
231         return bytes;
232 }
233         
234 void Input::curl_callback(char *ptr, size_t bytes)
235 {
236         pending_data.insert(pending_data.end(), ptr, ptr + bytes);
237
238         for ( ;; ) {
239                 // If we don't have enough data (yet) for even the Metacube header, just return.
240                 if (pending_data.size() < sizeof(metacube_block_header)) {
241                         return;
242                 }
243
244                 // Make sure we have the Metacube sync header at the start.
245                 // We may need to skip over junk data (it _should_ not happen, though).
246                 if (!has_metacube_header) {
247                         char *ptr = static_cast<char *>(
248                                 memmem(pending_data.data(), pending_data.size(),
249                                        METACUBE_SYNC, strlen(METACUBE_SYNC)));
250                         if (ptr == NULL) {
251                                 // OK, so we didn't find the sync marker. We know then that
252                                 // we do not have the _full_ marker in the buffer, but we
253                                 // could have N-1 bytes. Drop everything before that,
254                                 // and then give up.
255                                 drop_pending_data(pending_data.size() - (strlen(METACUBE_SYNC) - 1));
256                                 return;
257                         } else {
258                                 // Yay, we found the header. Drop everything (if anything) before it.
259                                 drop_pending_data(ptr - pending_data.data());
260                                 has_metacube_header = true;
261
262                                 // Re-check that we have the entire header; we could have dropped data.
263                                 if (pending_data.size() < sizeof(metacube_block_header)) {
264                                         return;
265                                 }
266                         }
267                 }
268
269                 // Now it's safe to read the header.
270                 metacube_block_header *hdr = reinterpret_cast<metacube_block_header *>(pending_data.data());    
271                 assert(memcmp(hdr->sync, METACUBE_SYNC, sizeof(hdr->sync)) == 0);
272                 uint32_t size = ntohl(hdr->size);
273                 uint32_t flags = ntohl(hdr->flags);
274
275                 // See if we have the entire block. If not, wait for more data.
276                 if (pending_data.size() < sizeof(metacube_block_header) + size) {
277                         return;
278                 }
279
280                 process_block(pending_data.data(), size, flags);
281
282                 // Consume this block. This isn't the most efficient way of dealing with things
283                 // should we have many blocks, but these routines don't need to be too efficient
284                 // anyway.
285                 pending_data.erase(pending_data.begin(), pending_data.begin() + sizeof(metacube_block_header) + size);
286         }
287 }
288                 
289 void Input::process_block(const char *data, uint32_t size, uint32_t flags)
290 {       
291         if (flags & METACUBE_FLAGS_HEADER) {
292                 string header(data, data + size);
293                 for (int i = 0; i < NUM_SERVERS; ++i) {
294                         servers[i].set_header(stream_id, header);
295                 }
296         } else { 
297                 for (int i = 0; i < NUM_SERVERS; ++i) {
298                         servers[i].add_data(stream_id, data, size);
299                 }
300         }
301 }
302
303 void Input::drop_pending_data(size_t num_bytes)
304 {
305         if (num_bytes == 0) {
306                 return;
307         }
308         fprintf(stderr, "Warning: Dropping %lld junk bytes from stream, maybe it is not a Metacube stream?\n",
309                 (long long)num_bytes);
310         pending_data.erase(pending_data.begin(), pending_data.begin() + num_bytes);
311 }
312
313 int create_server_socket(int port)
314 {
315         int server_sock = socket(PF_INET6, SOCK_STREAM, IPPROTO_TCP);
316         if (server_sock == -1) {
317                 perror("socket");
318                 exit(1);
319         }
320
321         // We want dual-stack sockets. (Sorry, OpenBSD and Windows XP...)
322         int zero = 0;
323         if (setsockopt(server_sock, IPPROTO_IPV6, IPV6_V6ONLY, &zero, sizeof(zero)) == -1) {
324                 perror("setsockopt(IPV6_V6ONLY)");
325                 exit(1);
326         }
327
328         sockaddr_in6 addr;
329         memset(&addr, 0, sizeof(addr));
330         addr.sin6_family = AF_INET6;
331         addr.sin6_port = htons(port);
332
333         if (bind(server_sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == -1) {
334                 perror("bind");
335                 exit(1);
336         }
337
338         if (listen(server_sock, 128) == -1) {
339                 perror("listen");
340                 exit(1);
341         }
342
343         return server_sock;
344 }
345
346 void *acceptor_thread_run(void *arg)
347 {
348         int server_sock = int(intptr_t(arg));
349         int num_accepted = 0;
350         for ( ;; ) {
351                 sockaddr_in6 addr;
352                 socklen_t addrlen = sizeof(addr);
353
354                 // Get a new socket.
355                 int sock = accept(server_sock, reinterpret_cast<sockaddr *>(&addr), &addrlen);
356                 if (sock == -1 && errno == EINTR) {
357                         continue;
358                 }
359                 if (sock == -1) {
360                         perror("accept");
361                         exit(1);
362                 }
363
364                 // Set the socket as nonblocking.
365                 int one = 1;
366                 if (ioctl(sock, FIONBIO, &one) == -1) {
367                         perror("FIONBIO");
368                         exit(1);
369                 }
370
371                 // Pick a server, round-robin, and hand over the socket to it.
372                 servers[num_accepted % NUM_SERVERS].add_client(sock);
373                 ++num_accepted; 
374         }
375 }
376
377 int main(int argc, char **argv)
378 {
379         servers = new Server[NUM_SERVERS];
380         for (int i = 0; i < NUM_SERVERS; ++i) {
381                 servers[i].add_stream(STREAM_ID);
382                 servers[i].run();
383         }
384
385         int server_sock = create_server_socket(PORT);
386
387         pthread_t acceptor_thread;
388         pthread_create(&acceptor_thread, NULL, acceptor_thread_run, reinterpret_cast<void *>(server_sock));
389
390         Input input(STREAM_ID);
391         input.run(STREAM_URL);
392 }