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