Add support for serving HLS playlists.
[cubemap] / stream.cpp
1 #include <assert.h>
2 #include <errno.h>
3 #include <limits.h>
4 #include <math.h>
5 #include <netinet/in.h>
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <sys/types.h>
10 #include <algorithm>
11 #include <string>
12 #include <queue>
13 #include <vector>
14
15 #include "log.h"
16 #include "metacube2.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,
24                size_t backlog_size,
25                size_t prebuffering_bytes,
26                Encoding encoding,
27                Encoding src_encoding,
28                unsigned hls_frag_duration,
29                size_t hls_backlog_margin,
30                const std::string &allow_origin)
31         : url(url),
32           encoding(encoding),
33           src_encoding(src_encoding),
34           allow_origin(allow_origin),
35           data_fd(make_tempfile("")),
36           backlog_size(backlog_size),
37           prebuffering_bytes(prebuffering_bytes),
38           hls_frag_duration(hls_frag_duration),
39           hls_backlog_margin(hls_backlog_margin)
40 {
41         if (data_fd == -1) {
42                 exit(1);
43         }
44 }
45
46 Stream::~Stream()
47 {
48         if (data_fd != -1) {
49                 safe_close(data_fd);
50         }
51 }
52
53 Stream::Stream(const StreamProto &serialized, int data_fd)
54         : url(serialized.url()),
55           http_header(serialized.http_header()),
56           stream_header(serialized.stream_header()),
57           encoding(Stream::STREAM_ENCODING_RAW),  // Will be changed later.
58           data_fd(data_fd),
59           backlog_size(serialized.backlog_size()),
60           bytes_received(serialized.bytes_received()),
61           first_fragment_index(serialized.first_fragment_index()),
62           discontinuity_counter(serialized.discontinuity_counter())
63 {
64         if (data_fd == -1) {
65                 exit(1);
66         }
67
68         for (ssize_t point : serialized.suitable_starting_point()) {
69                 if (point == -1) {
70                         // Can happen when upgrading from before 1.1.3,
71                         // where this was an optional field with -1 signifying
72                         // "no such point".
73                         continue;
74                 }
75                 suitable_starting_points.push_back(point);
76         }
77
78         for (const FragmentStartProto &fragment : serialized.fragment()) {
79                 fragments.push_back(FragmentStart { size_t(fragment.byte_position()), fragment.pts() });
80         }
81 }
82
83 StreamProto Stream::serialize()
84 {
85         StreamProto serialized;
86         serialized.set_http_header(http_header);
87         serialized.set_stream_header(stream_header);
88         serialized.add_data_fds(data_fd);
89         serialized.set_backlog_size(backlog_size);
90         serialized.set_bytes_received(bytes_received);
91         for (size_t point : suitable_starting_points) {
92                 serialized.add_suitable_starting_point(point);
93         }
94         for (const FragmentStart &fragment : fragments) {
95                 FragmentStartProto *proto = serialized.add_fragment();
96                 proto->set_byte_position(fragment.byte_position);
97                 proto->set_pts(fragment.pts);
98         }
99         serialized.set_first_fragment_index(first_fragment_index);
100         serialized.set_discontinuity_counter(discontinuity_counter);
101
102         serialized.set_url(url);
103         data_fd = -1;
104         return serialized;
105 }
106         
107 void Stream::set_backlog_size(size_t new_size)
108 {
109         if (backlog_size == new_size) {
110                 return;
111         }
112
113         string existing_data;
114         if (!read_tempfile_and_close(data_fd, &existing_data)) {
115                 exit(1);
116         }
117
118         // Unwrap the data so it's no longer circular.
119         if (bytes_received <= backlog_size) {
120                 existing_data.resize(bytes_received);
121         } else {
122                 size_t pos = bytes_received % backlog_size;
123                 existing_data = existing_data.substr(pos, string::npos) +
124                         existing_data.substr(0, pos);
125         }
126
127         // See if we need to discard data.
128         if (new_size < existing_data.size()) {
129                 size_t to_discard = existing_data.size() - new_size;
130                 existing_data = existing_data.substr(to_discard, string::npos);
131         }
132
133         // Create a new, empty data file.
134         data_fd = make_tempfile("");
135         if (data_fd == -1) {
136                 exit(1);
137         }
138         backlog_size = new_size;
139
140         // Now cheat a bit by rewinding, and adding all the old data back.
141         bytes_received -= existing_data.size();
142         DataElement data_element;
143         data_element.data.iov_base = const_cast<char *>(existing_data.data());
144         data_element.data.iov_len = existing_data.size();
145         data_element.metacube_flags = 0;  // Ignored by add_data_raw().
146
147         vector<DataElement> data_elements;
148         data_elements.push_back(data_element);
149         add_data_raw(data_elements);
150         remove_obsolete_starting_points();
151 }
152
153 void Stream::put_client_to_sleep(Client *client)
154 {
155         sleeping_clients.push_back(client);
156 }
157
158 // Return a new set of iovecs that contains only the first <bytes_wanted> bytes of <data>.
159 vector<iovec> collect_iovecs(const vector<Stream::DataElement> &data, size_t bytes_wanted)
160 {
161         vector<iovec> ret;
162         size_t max_iovecs = min<size_t>(data.size(), IOV_MAX);
163         for (size_t i = 0; i < max_iovecs && bytes_wanted > 0; ++i) {
164                 if (data[i].data.iov_len <= bytes_wanted) {
165                         // Consume the entire iovec.
166                         ret.push_back(data[i].data);
167                         bytes_wanted -= data[i].data.iov_len;
168                 } else {
169                         // Take only parts of this iovec.
170                         iovec iov;
171                         iov.iov_base = data[i].data.iov_base;
172                         iov.iov_len = bytes_wanted;
173                         ret.push_back(iov);
174                         bytes_wanted = 0;
175                 }
176         }
177         return ret;
178 }
179
180 // Return a new set of iovecs that contains all of <data> except the first <bytes_wanted> bytes.
181 vector<Stream::DataElement> remove_iovecs(const vector<Stream::DataElement> &data, size_t bytes_wanted)
182 {
183         vector<Stream::DataElement> ret;
184         size_t i;
185         for (i = 0; i < data.size() && bytes_wanted > 0; ++i) {
186                 if (data[i].data.iov_len <= bytes_wanted) {
187                         // Consume the entire iovec.
188                         bytes_wanted -= data[i].data.iov_len;
189                 } else {
190                         // Take only parts of this iovec.
191                         Stream::DataElement data_element;
192                         data_element.data.iov_base = reinterpret_cast<char *>(data[i].data.iov_base) + bytes_wanted;
193                         data_element.data.iov_len = data[i].data.iov_len - bytes_wanted;
194                         data_element.metacube_flags = METACUBE_FLAGS_NOT_SUITABLE_FOR_STREAM_START;
195                         data_element.pts = RationalPTS();
196                         ret.push_back(data_element);
197                         bytes_wanted = 0;
198                 }
199         }
200
201         // Add the rest of the iovecs unchanged.
202         ret.insert(ret.end(), data.begin() + i, data.end());
203         return ret;
204 }
205
206 void Stream::add_data_raw(const vector<DataElement> &orig_data)
207 {
208         vector<DataElement> data = orig_data;
209         while (!data.empty()) {
210                 size_t pos = bytes_received % backlog_size;
211
212                 // Collect as many iovecs as we can before we hit the point
213                 // where the circular buffer wraps around.
214                 vector<iovec> to_write = collect_iovecs(data, backlog_size - pos);
215                 ssize_t ret;
216                 do {
217                         ret = pwritev(data_fd, to_write.data(), to_write.size(), pos);
218                 } while (ret == -1 && errno == EINTR);
219
220                 if (ret == -1) {
221                         log_perror("pwritev");
222                         // Dazed and confused, but trying to continue...
223                         return;
224                 }
225                 bytes_received += ret;
226
227                 // Remove the data that was actually written from the set of iovecs.
228                 data = remove_iovecs(data, ret);
229         }
230 }
231
232 void Stream::remove_obsolete_starting_points()
233 {
234         // We could do a binary search here (std::lower_bound), but it seems
235         // overkill for removing what's probably only a few points.
236         while (!suitable_starting_points.empty() &&
237                bytes_received - suitable_starting_points[0] > backlog_size) {
238                 suitable_starting_points.pop_front();
239         }
240         assert(backlog_size >= hls_backlog_margin);
241         while (!fragments.empty() &&
242                bytes_received - fragments[0].byte_position > (backlog_size - hls_backlog_margin)) {
243                 fragments.pop_front();
244                 ++first_fragment_index;
245                 clear_hls_playlist_cache();
246         }
247 }
248
249 void Stream::add_data_deferred(const char *data, size_t bytes, uint16_t metacube_flags, const RationalPTS &pts)
250 {
251         // For regular output, we don't want to send the client twice
252         // (it's already sent out together with the HTTP header).
253         // However, for Metacube output, we need to send it so that
254         // the Cubemap instance in the other end has a chance to update it.
255         // It may come twice in its stream, but Cubemap doesn't care.
256         if (encoding == Stream::STREAM_ENCODING_RAW &&
257             (metacube_flags & METACUBE_FLAGS_HEADER) != 0) {
258                 return;
259         }
260
261         lock_guard<mutex> lock(queued_data_mutex);
262
263         DataElement data_element;
264         data_element.metacube_flags = metacube_flags;
265         data_element.pts = pts;
266
267         if (encoding == Stream::STREAM_ENCODING_METACUBE) {
268                 // Construct a PTS metadata block. (We'll avoid sending it out
269                 // if we don't have a valid PTS.)
270                 metacube2_pts_packet pts_packet;
271                 pts_packet.type = htobe64(METACUBE_METADATA_TYPE_NEXT_BLOCK_PTS);
272                 pts_packet.pts = htobe64(pts.pts);
273                 pts_packet.timebase_num = htobe64(pts.timebase_num);
274                 pts_packet.timebase_den = htobe64(pts.timebase_den);
275
276                 metacube2_block_header pts_hdr;
277                 memcpy(pts_hdr.sync, METACUBE2_SYNC, sizeof(pts_hdr.sync));
278                 pts_hdr.size = htonl(sizeof(pts_packet));
279                 pts_hdr.flags = htons(METACUBE_FLAGS_METADATA);
280                 pts_hdr.csum = htons(metacube2_compute_crc(&pts_hdr));
281
282                 // Add a Metacube block header before the data.
283                 metacube2_block_header hdr;
284                 memcpy(hdr.sync, METACUBE2_SYNC, sizeof(hdr.sync));
285                 hdr.size = htonl(bytes);
286                 hdr.flags = htons(metacube_flags);
287                 hdr.csum = htons(metacube2_compute_crc(&hdr));
288
289                 data_element.data.iov_len = bytes + sizeof(hdr);
290                 if (pts.timebase_num != 0) {
291                         data_element.data.iov_len += sizeof(pts_hdr) + sizeof(pts_packet);
292                 }
293                 data_element.data.iov_base = new char[data_element.data.iov_len];
294
295                 char *ptr = reinterpret_cast<char *>(data_element.data.iov_base);
296                 if (pts.timebase_num != 0) {
297                         memcpy(ptr, &pts_hdr, sizeof(pts_hdr));
298                         ptr += sizeof(pts_hdr);
299                         memcpy(ptr, &pts_packet, sizeof(pts_packet));
300                         ptr += sizeof(pts_packet);
301                 }
302
303                 memcpy(ptr, &hdr, sizeof(hdr));
304                 ptr += sizeof(hdr);
305                 memcpy(ptr, data, bytes);
306
307                 queued_data.push_back(data_element);
308         } else if (encoding == Stream::STREAM_ENCODING_RAW) {
309                 // Just add the data itself.
310                 data_element.data.iov_base = new char[bytes];
311                 memcpy(data_element.data.iov_base, data, bytes);
312                 data_element.data.iov_len = bytes;
313
314                 queued_data.push_back(data_element);
315         } else {
316                 assert(false);
317         }
318 }
319
320 void Stream::process_queued_data()
321 {
322         vector<DataElement> queued_data_copy;
323
324         // Hold the lock for as short as possible, since add_data_raw() can possibly
325         // write to disk, which might disturb the input thread.
326         {
327                 lock_guard<mutex> lock(queued_data_mutex);
328                 if (queued_data.empty()) {
329                         return;
330                 }
331
332                 swap(queued_data, queued_data_copy);
333         }
334
335         // Add suitable starting points for the stream, if the queued data
336         // contains such starting points. Note that we drop starting points
337         // if they're less than 10 kB apart, so that we don't get a huge
338         // amount of them for e.g. each and every MPEG-TS 188-byte cell.
339         // The 10 kB value is somewhat arbitrary, but at least it should make
340         // the RAM cost of saving the position ~0.1% (or less) of the actual
341         // data, and 10 kB is a very fine granularity in most streams.
342         static const int minimum_start_point_distance = 10240;
343         size_t byte_position = bytes_received;
344         bool need_hls_clear = false;
345         for (const DataElement &elem : queued_data_copy) {
346                 if ((elem.metacube_flags & METACUBE_FLAGS_NOT_SUITABLE_FOR_STREAM_START) == 0) {
347                         size_t num_points = suitable_starting_points.size();
348                         if (num_points >= 2 &&
349                             suitable_starting_points[num_points - 1] - suitable_starting_points[num_points - 2] < minimum_start_point_distance) {
350                                 // p[n-1] - p[n-2] < 10 kB, so drop p[n-1].
351                                 suitable_starting_points.pop_back();
352                         }
353                         suitable_starting_points.push_back(byte_position);
354
355                         if (elem.pts.timebase_num != 0) {
356                                 need_hls_clear |= add_fragment_boundary(byte_position, elem.pts);
357                         }
358                 }
359                 byte_position += elem.data.iov_len;
360         }
361         if (need_hls_clear) {
362                 clear_hls_playlist_cache();
363         }
364
365         add_data_raw(queued_data_copy);
366         remove_obsolete_starting_points();
367         for (const DataElement &elem : queued_data_copy) {
368                 char *data = reinterpret_cast<char *>(elem.data.iov_base);
369                 delete[] data;
370         }
371
372         // We have more data, so wake up all clients.
373         if (to_process.empty()) {
374                 swap(sleeping_clients, to_process);
375         } else {
376                 to_process.insert(to_process.end(), sleeping_clients.begin(), sleeping_clients.end());
377                 sleeping_clients.clear();
378         }
379 }
380
381 bool Stream::add_fragment_boundary(size_t byte_position, const RationalPTS &pts)
382 {
383         double pts_double = double(pts.pts) * pts.timebase_den / pts.timebase_num;
384
385         if (fragments.size() <= 1) {
386                 // Just starting up, so try to establish the first in-progress fragment.
387                 fragments.push_back(FragmentStart{ byte_position, pts_double });
388                 return false;
389         }
390
391         // Keep extending the in-progress fragment as long as we do not
392         // exceed the target duration by more than half a second
393         // (RFC 8216 4.3.3.1) and we get closer to the target by doing so.
394         // Note that in particular, this means we'll always extend
395         // as long as we don't exceed the target duration.
396         double current_duration = fragments[fragments.size() - 1].pts;
397         double candidate_duration = pts_double - fragments[fragments.size() - 2].pts;
398         if (lrintf(candidate_duration) <= hls_frag_duration &&
399             fabs(candidate_duration - hls_frag_duration) < fabs(current_duration - hls_frag_duration)) {
400                 fragments.back() = FragmentStart{ byte_position, pts_double };
401                 return false;
402         } else {
403                 // Extending the in-progress fragment would make it too long,
404                 // so finalize it and start a new in-progress fragment.
405                 fragments.push_back(FragmentStart{ byte_position, pts_double });
406                 return true;
407         }
408 }
409
410 void Stream::clear_hls_playlist_cache()
411 {
412         hls_playlist_http10.reset();
413         hls_playlist_http11_close.reset();
414         hls_playlist_http11_persistent.reset();
415 }
416
417 shared_ptr<const string> Stream::generate_hls_playlist(bool http_11, bool close_after_response)
418 {
419         char buf[256];
420         snprintf(buf, sizeof(buf),
421                 "#EXTM3U\r\n"
422                 "#EXT-X-VERSION:7\r\n"
423                 "#EXT-X-TARGETDURATION:%u\r\n"
424                 "#EXT-X-MEDIA-SEQUENCE:%zu\r\n"
425                 "#EXT-X-DISCONTINUITY-SEQUENCE:%zu\r\n",
426                 hls_frag_duration,
427                 first_fragment_index,
428                 discontinuity_counter);
429
430         string playlist = buf;
431
432         if (!stream_header.empty()) {
433                 snprintf(buf, sizeof(buf), "#EXT-X-MAP:URI=\"%s?frag=header\"\r\n", url.c_str());
434                 playlist += buf;
435         }
436
437         playlist += "\r\n";
438         if (fragments.size() >= 3) {
439                 for (size_t i = 0; i < fragments.size() - 2; ++i) {
440                         char buf[256];
441                         snprintf(buf, sizeof(buf), "#EXTINF:%f,\r\n%s?frag=%zu-%zu\r\n",
442                                 fragments[i + 1].pts - fragments[i].pts,
443                                 url.c_str(),
444                                 fragments[i].byte_position,
445                                 fragments[i + 1].byte_position);
446                         playlist += buf;
447                 }
448         }
449
450         string response;
451         if (http_11) {
452                 response = "HTTP/1.1 200 OK\r\n";
453                 if (close_after_response) {
454                         response.append("Connection: close\r\n");
455                 }
456         } else {
457                 assert(close_after_response);
458                 response = "HTTP/1.0 200 OK\r\n";
459         }
460         snprintf(buf, sizeof(buf), "Content-length: %zu\r\n", playlist.size());
461         response.append(buf);
462         response.append("Content-type: application/x-mpegURL\r\n");
463         if (!allow_origin.empty()) {
464                 response.append("Access-Control-Allow-Origin: ");
465                 response.append(allow_origin);
466                 response.append("\r\n");
467         }
468         response.append("\r\n");
469         response.append(move(playlist));
470
471         return shared_ptr<const string>(new string(move(response)));
472 }