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