]> git.sesse.net Git - cubemap/blob - stream.cpp
Fix compilation on 32-bit systems.
[cubemap] / stream.cpp
1 #include <assert.h>
2 #include <errno.h>
3 #include <netinet/in.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <sys/types.h>
8 #include <algorithm>
9 #include <string>
10 #include <vector>
11
12 #include "log.h"
13 #include "metacube2.h"
14 #include "mutexlock.h"
15 #include "state.pb.h"
16 #include "stream.h"
17 #include "util.h"
18
19 using namespace std;
20
21 Stream::Stream(const string &url, size_t backlog_size, Encoding encoding)
22         : url(url),
23           encoding(encoding),
24           data_fd(make_tempfile("")),
25           backlog_size(backlog_size),
26           bytes_received(0),
27           last_suitable_starting_point(-1),
28           mark_pool(NULL),
29           queued_data_last_starting_point(-1)
30 {
31         if (data_fd == -1) {
32                 exit(1);
33         }
34
35         pthread_mutex_init(&queued_data_mutex, NULL);
36 }
37
38 Stream::~Stream()
39 {
40         if (data_fd != -1) {
41                 safe_close(data_fd);
42         }
43 }
44
45 Stream::Stream(const StreamProto &serialized, int data_fd)
46         : url(serialized.url()),
47           http_header(serialized.http_header()),
48           stream_header(serialized.stream_header()),
49           encoding(Stream::STREAM_ENCODING_RAW),  // Will be changed later.
50           data_fd(data_fd),
51           backlog_size(serialized.backlog_size()),
52           bytes_received(serialized.bytes_received()),
53           mark_pool(NULL),
54           queued_data_last_starting_point(-1)
55 {
56         if (data_fd == -1) {
57                 exit(1);
58         }
59
60         // Split old-style headers into HTTP and video headers.
61         if (!serialized.header().empty()) {
62                 string header = serialized.header();
63                 size_t split = header.find("\r\n\r\n");
64                 if (split == string::npos) {
65                         http_header = header;
66                         stream_header = "";
67                 } else {
68                         http_header = header.substr(0, split + 2);  // Split off the second \r\n.
69                         stream_header = header.substr(split, string::npos);
70                 }
71         }
72
73         // Older versions did not set last_suitable_starting_point.
74         if (serialized.has_last_suitable_starting_point()) {
75                 last_suitable_starting_point = serialized.last_suitable_starting_point();
76         } else {
77                 last_suitable_starting_point = bytes_received;
78         }
79
80         pthread_mutex_init(&queued_data_mutex, NULL);
81 }
82
83 StreamProto Stream::serialize()
84 {
85         StreamProto serialized;
86         serialized.set_http_header(http_header);
87         serialized.set_stream_header(stream_header);
88         serialized.add_data_fds(data_fd);
89         serialized.set_backlog_size(backlog_size);
90         serialized.set_bytes_received(bytes_received);
91         serialized.set_last_suitable_starting_point(last_suitable_starting_point);
92         serialized.set_url(url);
93         data_fd = -1;
94         return serialized;
95 }
96         
97 void Stream::set_backlog_size(size_t new_size)
98 {
99         if (backlog_size == new_size) {
100                 return;
101         }
102
103         string existing_data;
104         if (!read_tempfile_and_close(data_fd, &existing_data)) {
105                 exit(1);
106         }
107
108         // Unwrap the data so it's no longer circular.
109         if (bytes_received <= backlog_size) {
110                 existing_data.resize(bytes_received);
111         } else {
112                 size_t pos = bytes_received % backlog_size;
113                 existing_data = existing_data.substr(pos, string::npos) +
114                         existing_data.substr(0, pos);
115         }
116
117         // See if we need to discard data.
118         if (new_size < existing_data.size()) {
119                 size_t to_discard = existing_data.size() - new_size;
120                 existing_data = existing_data.substr(to_discard, string::npos);
121         }
122
123         // Create a new, empty data file.
124         data_fd = make_tempfile("");
125         if (data_fd == -1) {
126                 exit(1);
127         }
128         backlog_size = new_size;
129
130         // Now cheat a bit by rewinding, and adding all the old data back.
131         bytes_received -= existing_data.size();
132         iovec iov;
133         iov.iov_base = const_cast<char *>(existing_data.data());
134         iov.iov_len = existing_data.size();
135
136         vector<iovec> iovs;
137         iovs.push_back(iov);
138         add_data_raw(iovs);
139 }
140
141 void Stream::put_client_to_sleep(Client *client)
142 {
143         sleeping_clients.push_back(client);
144 }
145
146 // Return a new set of iovecs that contains only the first <bytes_wanted> bytes of <data>.
147 vector<iovec> collect_iovecs(const vector<iovec> &data, size_t bytes_wanted)
148 {
149         vector<iovec> ret;
150         size_t max_iovecs = std::min<size_t>(data.size(), IOV_MAX);
151         for (size_t i = 0; i < max_iovecs && bytes_wanted > 0; ++i) {
152                 if (data[i].iov_len <= bytes_wanted) {
153                         // Consume the entire iovec.
154                         ret.push_back(data[i]);
155                         bytes_wanted -= data[i].iov_len;
156                 } else {
157                         // Take only parts of this iovec.
158                         iovec iov;
159                         iov.iov_base = data[i].iov_base;
160                         iov.iov_len = bytes_wanted;     
161                         ret.push_back(iov);
162                         bytes_wanted = 0;
163                 }
164         }
165         return ret;
166 }
167
168 // Return a new set of iovecs that contains all of <data> except the first <bytes_wanted> bytes.
169 vector<iovec> remove_iovecs(const vector<iovec> &data, size_t bytes_wanted)
170 {
171         vector<iovec> ret;
172         size_t i;
173         for (i = 0; i < data.size() && bytes_wanted > 0; ++i) {
174                 if (data[i].iov_len <= bytes_wanted) {
175                         // Consume the entire iovec.
176                         bytes_wanted -= data[i].iov_len;
177                 } else {
178                         // Take only parts of this iovec.
179                         iovec iov;
180                         iov.iov_base = reinterpret_cast<char *>(data[i].iov_base) + bytes_wanted;
181                         iov.iov_len = data[i].iov_len - bytes_wanted;
182                         ret.push_back(iov);
183                         bytes_wanted = 0;
184                 }
185         }
186
187         // Add the rest of the iovecs unchanged.
188         ret.insert(ret.end(), data.begin() + i, data.end());
189         return ret;
190 }
191
192 void Stream::add_data_raw(const vector<iovec> &orig_data)
193 {
194         vector<iovec> data = orig_data;
195         while (!data.empty()) {
196                 size_t pos = bytes_received % backlog_size;
197
198                 // Collect as many iovecs as we can before we hit the point
199                 // where the circular buffer wraps around.
200                 vector<iovec> to_write = collect_iovecs(data, backlog_size - pos);
201                 ssize_t ret;
202                 do {
203                         ret = pwritev(data_fd, to_write.data(), to_write.size(), pos);
204                 } while (ret == -1 && errno == EINTR);
205
206                 if (ret == -1) {
207                         log_perror("pwritev");
208                         // Dazed and confused, but trying to continue...
209                         return;
210                 }
211                 bytes_received += ret;
212
213                 // Remove the data that was actually written from the set of iovecs.
214                 data = remove_iovecs(data, ret);
215         }
216 }
217
218 void Stream::add_data_deferred(const char *data, size_t bytes, StreamStartSuitability suitable_for_stream_start)
219 {
220         MutexLock lock(&queued_data_mutex);
221         assert(suitable_for_stream_start == SUITABLE_FOR_STREAM_START ||
222                suitable_for_stream_start == NOT_SUITABLE_FOR_STREAM_START);
223         if (suitable_for_stream_start == SUITABLE_FOR_STREAM_START) {
224                 queued_data_last_starting_point = queued_data.size();
225         }
226
227         if (encoding == Stream::STREAM_ENCODING_METACUBE) {
228                 // Add a Metacube block header before the data.
229                 metacube2_block_header hdr;
230                 memcpy(hdr.sync, METACUBE2_SYNC, sizeof(hdr.sync));
231                 hdr.size = htonl(bytes);
232                 hdr.flags = htons(0);
233                 if (suitable_for_stream_start == NOT_SUITABLE_FOR_STREAM_START) {
234                         hdr.flags |= htons(METACUBE_FLAGS_NOT_SUITABLE_FOR_STREAM_START);
235                 }
236                 hdr.csum = htons(metacube2_compute_crc(&hdr));
237
238                 iovec iov;
239                 iov.iov_base = new char[bytes + sizeof(hdr)];
240                 iov.iov_len = bytes + sizeof(hdr);
241
242                 memcpy(iov.iov_base, &hdr, sizeof(hdr));
243                 memcpy(reinterpret_cast<char *>(iov.iov_base) + sizeof(hdr), data, bytes);
244
245                 queued_data.push_back(iov);
246         } else if (encoding == Stream::STREAM_ENCODING_RAW) {
247                 // Just add the data itself.
248                 iovec iov;
249                 iov.iov_base = new char[bytes];
250                 memcpy(iov.iov_base, data, bytes);
251                 iov.iov_len = bytes;
252
253                 queued_data.push_back(iov);
254         } else {
255                 assert(false);
256         }
257 }
258
259 void Stream::process_queued_data()
260 {
261         std::vector<iovec> queued_data_copy;
262         int queued_data_last_starting_point_copy = -1;
263
264         // Hold the lock for as short as possible, since add_data_raw() can possibly
265         // write to disk, which might disturb the input thread.
266         {
267                 MutexLock lock(&queued_data_mutex);
268                 if (queued_data.empty()) {
269                         return;
270                 }
271
272                 swap(queued_data, queued_data_copy);
273                 swap(queued_data_last_starting_point, queued_data_last_starting_point_copy);
274         }
275
276         // Update the last suitable starting point for the stream,
277         // if the queued data contains such a starting point.
278         assert(queued_data_last_starting_point_copy < ssize_t(queued_data_copy.size()));
279         if (queued_data_last_starting_point_copy >= 0) {
280                 last_suitable_starting_point = bytes_received;
281                 for (int i = 0; i < queued_data_last_starting_point_copy; ++i) {
282                         last_suitable_starting_point += queued_data_copy[i].iov_len;
283                 }
284         }
285
286         add_data_raw(queued_data_copy);
287         for (size_t i = 0; i < queued_data_copy.size(); ++i) {
288                 char *data = reinterpret_cast<char *>(queued_data_copy[i].iov_base);
289                 delete[] data;
290         }
291
292         // We have more data, so wake up all clients.
293         if (to_process.empty()) {
294                 swap(sleeping_clients, to_process);
295         } else {
296                 to_process.insert(to_process.end(), sleeping_clients.begin(), sleeping_clients.end());
297                 sleeping_clients.clear();
298         }
299 }