734110c9f47e79ee18586dff5afaabb0f1b311c3
[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 <queue>
12 #include <vector>
13
14 #include "log.h"
15 #include "metacube2.h"
16 #include "mutexlock.h"
17 #include "state.pb.h"
18 #include "stream.h"
19 #include "util.h"
20
21 using namespace std;
22
23 Stream::Stream(const string &url, size_t backlog_size, size_t prebuffering_bytes, Encoding encoding, Encoding src_encoding)
24         : url(url),
25           encoding(encoding),
26           src_encoding(src_encoding),
27           data_fd(make_tempfile("")),
28           backlog_size(backlog_size),
29           prebuffering_bytes(prebuffering_bytes),
30           bytes_received(0),
31           pacing_rate(~0U)
32 {
33         if (data_fd == -1) {
34                 exit(1);
35         }
36
37         pthread_mutex_init(&queued_data_mutex, NULL);
38 }
39
40 Stream::~Stream()
41 {
42         if (data_fd != -1) {
43                 safe_close(data_fd);
44         }
45 }
46
47 Stream::Stream(const StreamProto &serialized, int data_fd)
48         : url(serialized.url()),
49           http_header(serialized.http_header()),
50           stream_header(serialized.stream_header()),
51           encoding(Stream::STREAM_ENCODING_RAW),  // Will be changed later.
52           data_fd(data_fd),
53           backlog_size(serialized.backlog_size()),
54           prebuffering_bytes(serialized.prebuffering_bytes()),
55           bytes_received(serialized.bytes_received()),
56           pacing_rate(~0U)
57 {
58         if (data_fd == -1) {
59                 exit(1);
60         }
61
62         for (ssize_t point : serialized.suitable_starting_point()) {
63                 if (point == -1) {
64                         // Can happen when upgrading from before 1.1.3,
65                         // where this was an optional field with -1 signifying
66                         // "no such point".
67                         continue;
68                 }
69                 suitable_starting_points.push_back(point);
70         }
71
72         pthread_mutex_init(&queued_data_mutex, NULL);
73 }
74
75 StreamProto Stream::serialize()
76 {
77         StreamProto serialized;
78         serialized.set_http_header(http_header);
79         serialized.set_stream_header(stream_header);
80         serialized.add_data_fds(data_fd);
81         serialized.set_backlog_size(backlog_size);
82         serialized.set_prebuffering_bytes(prebuffering_bytes);
83         serialized.set_bytes_received(bytes_received);
84         for (size_t point : suitable_starting_points) {
85                 serialized.add_suitable_starting_point(point);
86         }
87         serialized.set_url(url);
88         data_fd = -1;
89         return serialized;
90 }
91         
92 void Stream::set_backlog_size(size_t new_size)
93 {
94         if (backlog_size == new_size) {
95                 return;
96         }
97
98         string existing_data;
99         if (!read_tempfile_and_close(data_fd, &existing_data)) {
100                 exit(1);
101         }
102
103         // Unwrap the data so it's no longer circular.
104         if (bytes_received <= backlog_size) {
105                 existing_data.resize(bytes_received);
106         } else {
107                 size_t pos = bytes_received % backlog_size;
108                 existing_data = existing_data.substr(pos, string::npos) +
109                         existing_data.substr(0, pos);
110         }
111
112         // See if we need to discard data.
113         if (new_size < existing_data.size()) {
114                 size_t to_discard = existing_data.size() - new_size;
115                 existing_data = existing_data.substr(to_discard, string::npos);
116         }
117
118         // Create a new, empty data file.
119         data_fd = make_tempfile("");
120         if (data_fd == -1) {
121                 exit(1);
122         }
123         backlog_size = new_size;
124
125         // Now cheat a bit by rewinding, and adding all the old data back.
126         bytes_received -= existing_data.size();
127         DataElement data_element;
128         data_element.data.iov_base = const_cast<char *>(existing_data.data());
129         data_element.data.iov_len = existing_data.size();
130         data_element.metacube_flags = 0;  // Ignored by add_data_raw().
131
132         vector<DataElement> data_elements;
133         data_elements.push_back(data_element);
134         add_data_raw(data_elements);
135         remove_obsolete_starting_points();
136 }
137
138 void Stream::put_client_to_sleep(Client *client)
139 {
140         sleeping_clients.push_back(client);
141 }
142
143 // Return a new set of iovecs that contains only the first <bytes_wanted> bytes of <data>.
144 vector<iovec> collect_iovecs(const vector<Stream::DataElement> &data, size_t bytes_wanted)
145 {
146         vector<iovec> ret;
147         size_t max_iovecs = min<size_t>(data.size(), IOV_MAX);
148         for (size_t i = 0; i < max_iovecs && bytes_wanted > 0; ++i) {
149                 if (data[i].data.iov_len <= bytes_wanted) {
150                         // Consume the entire iovec.
151                         ret.push_back(data[i].data);
152                         bytes_wanted -= data[i].data.iov_len;
153                 } else {
154                         // Take only parts of this iovec.
155                         iovec iov;
156                         iov.iov_base = data[i].data.iov_base;
157                         iov.iov_len = bytes_wanted;
158                         ret.push_back(iov);
159                         bytes_wanted = 0;
160                 }
161         }
162         return ret;
163 }
164
165 // Return a new set of iovecs that contains all of <data> except the first <bytes_wanted> bytes.
166 vector<Stream::DataElement> remove_iovecs(const vector<Stream::DataElement> &data, size_t bytes_wanted)
167 {
168         vector<Stream::DataElement> ret;
169         size_t i;
170         for (i = 0; i < data.size() && bytes_wanted > 0; ++i) {
171                 if (data[i].data.iov_len <= bytes_wanted) {
172                         // Consume the entire iovec.
173                         bytes_wanted -= data[i].data.iov_len;
174                 } else {
175                         // Take only parts of this iovec.
176                         Stream::DataElement data_element;
177                         data_element.data.iov_base = reinterpret_cast<char *>(data[i].data.iov_base) + bytes_wanted;
178                         data_element.data.iov_len = data[i].data.iov_len - bytes_wanted;
179                         data_element.metacube_flags = METACUBE_FLAGS_NOT_SUITABLE_FOR_STREAM_START;
180                         ret.push_back(data_element);
181                         bytes_wanted = 0;
182                 }
183         }
184
185         // Add the rest of the iovecs unchanged.
186         ret.insert(ret.end(), data.begin() + i, data.end());
187         return ret;
188 }
189
190 void Stream::add_data_raw(const vector<DataElement> &orig_data)
191 {
192         vector<DataElement> data = orig_data;
193         while (!data.empty()) {
194                 size_t pos = bytes_received % backlog_size;
195
196                 // Collect as many iovecs as we can before we hit the point
197                 // where the circular buffer wraps around.
198                 vector<iovec> to_write = collect_iovecs(data, backlog_size - pos);
199                 ssize_t ret;
200                 do {
201                         ret = pwritev(data_fd, to_write.data(), to_write.size(), pos);
202                 } while (ret == -1 && errno == EINTR);
203
204                 if (ret == -1) {
205                         log_perror("pwritev");
206                         // Dazed and confused, but trying to continue...
207                         return;
208                 }
209                 bytes_received += ret;
210
211                 // Remove the data that was actually written from the set of iovecs.
212                 data = remove_iovecs(data, ret);
213         }
214 }
215
216 void Stream::remove_obsolete_starting_points()
217 {
218         // We could do a binary search here (std::lower_bound), but it seems
219         // overkill for removing what's probably only a few points.
220         while (!suitable_starting_points.empty() &&
221                bytes_received - suitable_starting_points[0] > backlog_size) {
222                 suitable_starting_points.pop_front();
223         }
224 }
225
226 void Stream::add_data_deferred(const char *data, size_t bytes, uint16_t metacube_flags)
227 {
228         // For regular output, we don't want to send the client twice
229         // (it's already sent out together with the HTTP header).
230         // However, for Metacube output, we need to send it so that
231         // the Cubemap instance in the other end has a chance to update it.
232         // It may come twice in its stream, but Cubemap doesn't care.
233         if (encoding == Stream::STREAM_ENCODING_RAW &&
234             (metacube_flags & METACUBE_FLAGS_HEADER) != 0) {
235                 return;
236         }
237
238         MutexLock lock(&queued_data_mutex);
239
240         DataElement data_element;
241         data_element.metacube_flags = metacube_flags;
242
243         if (encoding == Stream::STREAM_ENCODING_METACUBE) {
244                 // Add a Metacube block header before the data.
245                 metacube2_block_header hdr;
246                 memcpy(hdr.sync, METACUBE2_SYNC, sizeof(hdr.sync));
247                 hdr.size = htonl(bytes);
248                 hdr.flags = htons(metacube_flags);
249                 hdr.csum = htons(metacube2_compute_crc(&hdr));
250
251                 data_element.data.iov_base = new char[bytes + sizeof(hdr)];
252                 data_element.data.iov_len = bytes + sizeof(hdr);
253
254                 memcpy(data_element.data.iov_base, &hdr, sizeof(hdr));
255                 memcpy(reinterpret_cast<char *>(data_element.data.iov_base) + sizeof(hdr), data, bytes);
256
257                 queued_data.push_back(data_element);
258         } else if (encoding == Stream::STREAM_ENCODING_RAW) {
259                 // Just add the data itself.
260                 data_element.data.iov_base = new char[bytes];
261                 memcpy(data_element.data.iov_base, data, bytes);
262                 data_element.data.iov_len = bytes;
263
264                 queued_data.push_back(data_element);
265         } else {
266                 assert(false);
267         }
268 }
269
270 void Stream::process_queued_data()
271 {
272         vector<DataElement> queued_data_copy;
273
274         // Hold the lock for as short as possible, since add_data_raw() can possibly
275         // write to disk, which might disturb the input thread.
276         {
277                 MutexLock lock(&queued_data_mutex);
278                 if (queued_data.empty()) {
279                         return;
280                 }
281
282                 swap(queued_data, queued_data_copy);
283         }
284
285         // Add suitable starting points for the stream, if the queued data
286         // contains such starting points. Note that we drop starting points
287         // if they're less than 10 kB apart, so that we don't get a huge
288         // amount of them for e.g. each and every MPEG-TS 188-byte cell.
289         // The 10 kB value is somewhat arbitrary, but at least it should make
290         // the RAM cost of saving the position ~0.1% (or less) of the actual
291         // data, and 10 kB is a very fine granularity in most streams.
292         static const int minimum_start_point_distance = 10240;
293         size_t byte_position = bytes_received;
294         for (const DataElement &elem : queued_data_copy) {
295                 if ((elem.metacube_flags & METACUBE_FLAGS_NOT_SUITABLE_FOR_STREAM_START) == 0) {
296                         size_t num_points = suitable_starting_points.size();
297                         if (num_points >= 2 &&
298                             suitable_starting_points[num_points - 1] - suitable_starting_points[num_points - 2] < minimum_start_point_distance) {
299                                 // p[n-1] - p[n-2] < 10 kB, so drop p[n-1].
300                                 suitable_starting_points.pop_back();
301                         }
302                         suitable_starting_points.push_back(byte_position);
303                 }
304                 byte_position += elem.data.iov_len;
305         }
306
307         add_data_raw(queued_data_copy);
308         remove_obsolete_starting_points();
309         for (const DataElement &elem : queued_data_copy) {
310                 char *data = reinterpret_cast<char *>(elem.data.iov_base);
311                 delete[] data;
312         }
313
314         // We have more data, so wake up all clients.
315         if (to_process.empty()) {
316                 swap(sleeping_clients, to_process);
317         } else {
318                 to_process.insert(to_process.end(), sleeping_clients.begin(), sleeping_clients.end());
319                 sleeping_clients.clear();
320         }
321 }