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