Partially revert last patch.
[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, size_t prebuffering_bytes, Encoding encoding)
23         : url(url),
24           encoding(encoding),
25           data_fd(make_tempfile("")),
26           backlog_size(backlog_size),
27           prebuffering_bytes(prebuffering_bytes),
28           bytes_received(0),
29           last_suitable_starting_point(-1),
30           pacing_rate(~0U)
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           prebuffering_bytes(serialized.prebuffering_bytes()),
54           bytes_received(serialized.bytes_received()),
55           pacing_rate(~0U)
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_prebuffering_bytes(prebuffering_bytes);
75         serialized.set_bytes_received(bytes_received);
76         serialized.set_last_suitable_starting_point(last_suitable_starting_point);
77         serialized.set_url(url);
78         data_fd = -1;
79         return serialized;
80 }
81         
82 void Stream::set_backlog_size(size_t new_size)
83 {
84         if (backlog_size == new_size) {
85                 return;
86         }
87
88         string existing_data;
89         if (!read_tempfile_and_close(data_fd, &existing_data)) {
90                 exit(1);
91         }
92
93         // Unwrap the data so it's no longer circular.
94         if (bytes_received <= backlog_size) {
95                 existing_data.resize(bytes_received);
96         } else {
97                 size_t pos = bytes_received % backlog_size;
98                 existing_data = existing_data.substr(pos, string::npos) +
99                         existing_data.substr(0, pos);
100         }
101
102         // See if we need to discard data.
103         if (new_size < existing_data.size()) {
104                 size_t to_discard = existing_data.size() - new_size;
105                 existing_data = existing_data.substr(to_discard, string::npos);
106         }
107
108         // Create a new, empty data file.
109         data_fd = make_tempfile("");
110         if (data_fd == -1) {
111                 exit(1);
112         }
113         backlog_size = new_size;
114
115         // Now cheat a bit by rewinding, and adding all the old data back.
116         bytes_received -= existing_data.size();
117         DataElement data_element;
118         data_element.data.iov_base = const_cast<char *>(existing_data.data());
119         data_element.data.iov_len = existing_data.size();
120         data_element.suitable_for_stream_start = NOT_SUITABLE_FOR_STREAM_START;  // Ignored by add_data_raw().
121
122         vector<DataElement> data_elements;
123         data_elements.push_back(data_element);
124         add_data_raw(data_elements);
125 }
126
127 void Stream::put_client_to_sleep(Client *client)
128 {
129         sleeping_clients.push_back(client);
130 }
131
132 // Return a new set of iovecs that contains only the first <bytes_wanted> bytes of <data>.
133 vector<iovec> collect_iovecs(const vector<Stream::DataElement> &data, size_t bytes_wanted)
134 {
135         vector<iovec> ret;
136         size_t max_iovecs = std::min<size_t>(data.size(), IOV_MAX);
137         for (size_t i = 0; i < max_iovecs && bytes_wanted > 0; ++i) {
138                 if (data[i].data.iov_len <= bytes_wanted) {
139                         // Consume the entire iovec.
140                         ret.push_back(data[i].data);
141                         bytes_wanted -= data[i].data.iov_len;
142                 } else {
143                         // Take only parts of this iovec.
144                         iovec iov;
145                         iov.iov_base = data[i].data.iov_base;
146                         iov.iov_len = bytes_wanted;
147                         ret.push_back(iov);
148                         bytes_wanted = 0;
149                 }
150         }
151         return ret;
152 }
153
154 // Return a new set of iovecs that contains all of <data> except the first <bytes_wanted> bytes.
155 vector<Stream::DataElement> remove_iovecs(const vector<Stream::DataElement> &data, size_t bytes_wanted)
156 {
157         vector<Stream::DataElement> ret;
158         size_t i;
159         for (i = 0; i < data.size() && bytes_wanted > 0; ++i) {
160                 if (data[i].data.iov_len <= bytes_wanted) {
161                         // Consume the entire iovec.
162                         bytes_wanted -= data[i].data.iov_len;
163                 } else {
164                         // Take only parts of this iovec.
165                         Stream::DataElement data_element;
166                         data_element.data.iov_base = reinterpret_cast<char *>(data[i].data.iov_base) + bytes_wanted;
167                         data_element.data.iov_len = data[i].data.iov_len - bytes_wanted;
168                         data_element.suitable_for_stream_start = NOT_SUITABLE_FOR_STREAM_START;
169                         ret.push_back(data_element);
170                         bytes_wanted = 0;
171                 }
172         }
173
174         // Add the rest of the iovecs unchanged.
175         ret.insert(ret.end(), data.begin() + i, data.end());
176         return ret;
177 }
178
179 void Stream::add_data_raw(const vector<DataElement> &orig_data)
180 {
181         vector<DataElement> data = orig_data;
182         while (!data.empty()) {
183                 size_t pos = bytes_received % backlog_size;
184
185                 // Collect as many iovecs as we can before we hit the point
186                 // where the circular buffer wraps around.
187                 vector<iovec> to_write = collect_iovecs(data, backlog_size - pos);
188                 ssize_t ret;
189                 do {
190                         ret = pwritev(data_fd, to_write.data(), to_write.size(), pos);
191                 } while (ret == -1 && errno == EINTR);
192
193                 if (ret == -1) {
194                         log_perror("pwritev");
195                         // Dazed and confused, but trying to continue...
196                         return;
197                 }
198                 bytes_received += ret;
199
200                 // Remove the data that was actually written from the set of iovecs.
201                 data = remove_iovecs(data, ret);
202         }
203 }
204
205 void Stream::add_data_deferred(const char *data, size_t bytes, StreamStartSuitability suitable_for_stream_start)
206 {
207         MutexLock lock(&queued_data_mutex);
208         assert(suitable_for_stream_start == SUITABLE_FOR_STREAM_START ||
209                suitable_for_stream_start == NOT_SUITABLE_FOR_STREAM_START);
210
211         DataElement data_element;
212         data_element.suitable_for_stream_start = suitable_for_stream_start;
213
214         if (encoding == Stream::STREAM_ENCODING_METACUBE) {
215                 // Add a Metacube block header before the data.
216                 metacube2_block_header hdr;
217                 memcpy(hdr.sync, METACUBE2_SYNC, sizeof(hdr.sync));
218                 hdr.size = htonl(bytes);
219                 hdr.flags = htons(0);
220                 if (suitable_for_stream_start == NOT_SUITABLE_FOR_STREAM_START) {
221                         hdr.flags |= htons(METACUBE_FLAGS_NOT_SUITABLE_FOR_STREAM_START);
222                 }
223                 hdr.csum = htons(metacube2_compute_crc(&hdr));
224
225                 data_element.data.iov_base = new char[bytes + sizeof(hdr)];
226                 data_element.data.iov_len = bytes + sizeof(hdr);
227
228                 memcpy(data_element.data.iov_base, &hdr, sizeof(hdr));
229                 memcpy(reinterpret_cast<char *>(data_element.data.iov_base) + sizeof(hdr), data, bytes);
230
231                 queued_data.push_back(data_element);
232         } else if (encoding == Stream::STREAM_ENCODING_RAW) {
233                 // Just add the data itself.
234                 data_element.data.iov_base = new char[bytes];
235                 memcpy(data_element.data.iov_base, data, bytes);
236                 data_element.data.iov_len = bytes;
237
238                 queued_data.push_back(data_element);
239         } else {
240                 assert(false);
241         }
242 }
243
244 void Stream::process_queued_data()
245 {
246         std::vector<DataElement> queued_data_copy;
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         }
258
259         // Update the last suitable starting point for the stream,
260         // if the queued data contains such a starting point.
261         size_t byte_position = bytes_received;
262         for (size_t i = 0; i < queued_data_copy.size(); ++i) {
263                 if (queued_data_copy[i].suitable_for_stream_start == SUITABLE_FOR_STREAM_START) {
264                         last_suitable_starting_point = byte_position;
265                 }
266                 byte_position += queued_data_copy[i].data.iov_len;
267         }
268
269         add_data_raw(queued_data_copy);
270         for (size_t i = 0; i < queued_data_copy.size(); ++i) {
271                 char *data = reinterpret_cast<char *>(queued_data_copy[i].data.iov_base);
272                 delete[] data;
273         }
274
275         // We have more data, so wake up all clients.
276         if (to_process.empty()) {
277                 swap(sleeping_clients, to_process);
278         } else {
279                 to_process.insert(to_process.end(), sleeping_clients.begin(), sleeping_clients.end());
280                 sleeping_clients.clear();
281         }
282 }