6 #include <netinet/in.h>
10 #include <sys/types.h>
17 #include "metacube2.h"
24 Stream::Stream(const string &url,
26 uint64_t prebuffering_bytes,
28 Encoding src_encoding,
29 unsigned hls_frag_duration,
30 size_t hls_backlog_margin,
31 const std::string &allow_origin)
34 src_encoding(src_encoding),
35 allow_origin(allow_origin),
36 data_fd(make_tempfile("")),
37 backlog_size(backlog_size),
38 prebuffering_bytes(prebuffering_bytes),
39 hls_frag_duration(hls_frag_duration),
40 hls_backlog_margin(hls_backlog_margin)
54 Stream::Stream(const StreamProto &serialized, int data_fd)
55 : url(serialized.url()),
56 unavailable(serialized.unavailable()),
57 http_header(serialized.http_header()),
58 stream_header(serialized.stream_header()),
59 encoding(Stream::STREAM_ENCODING_RAW), // Will be changed later.
61 backlog_size(serialized.backlog_size()),
62 bytes_received(serialized.bytes_received()),
63 first_fragment_index(serialized.first_fragment_index()),
64 discontinuity_counter(serialized.discontinuity_counter())
70 for (ssize_t point : serialized.suitable_starting_point()) {
72 // Can happen when upgrading from before 1.1.3,
73 // where this was an optional field with -1 signifying
77 suitable_starting_points.push_back(point);
80 for (const FragmentStartProto &fragment : serialized.fragment()) {
81 fragments.push_back(FragmentStart { size_t(fragment.byte_position()), fragment.pts(), fragment.begins_header() });
85 StreamProto Stream::serialize()
87 StreamProto serialized;
88 serialized.set_unavailable(unavailable);
89 serialized.set_http_header(http_header);
90 serialized.set_stream_header(stream_header);
91 serialized.add_data_fds(data_fd);
92 serialized.set_backlog_size(backlog_size);
93 serialized.set_bytes_received(bytes_received);
94 for (size_t point : suitable_starting_points) {
95 serialized.add_suitable_starting_point(point);
97 for (const FragmentStart &fragment : fragments) {
98 FragmentStartProto *proto = serialized.add_fragment();
99 proto->set_byte_position(fragment.byte_position);
100 proto->set_pts(fragment.pts);
101 proto->set_begins_header(fragment.begins_header);
103 serialized.set_first_fragment_index(first_fragment_index);
104 serialized.set_discontinuity_counter(discontinuity_counter);
106 serialized.set_url(url);
111 void Stream::set_backlog_size(size_t new_size)
113 if (backlog_size == new_size) {
117 string existing_data;
118 if (!read_tempfile_and_close(data_fd, &existing_data)) {
122 // Unwrap the data so it's no longer circular.
123 if (bytes_received <= backlog_size) {
124 existing_data.resize(bytes_received);
126 size_t pos = bytes_received % backlog_size;
127 existing_data = existing_data.substr(pos, string::npos) +
128 existing_data.substr(0, pos);
131 // See if we need to discard data.
132 if (new_size < existing_data.size()) {
133 size_t to_discard = existing_data.size() - new_size;
134 existing_data = existing_data.substr(to_discard, string::npos);
137 // Create a new, empty data file.
138 data_fd = make_tempfile("");
142 backlog_size = new_size;
144 // Now cheat a bit by rewinding, and adding all the old data back.
145 bytes_received -= existing_data.size();
146 DataElement data_element;
147 data_element.data.iov_base = const_cast<char *>(existing_data.data());
148 data_element.data.iov_len = existing_data.size();
149 data_element.metacube_flags = 0; // Ignored by add_data_raw().
151 vector<DataElement> data_elements;
152 data_elements.push_back(data_element);
153 add_data_raw(data_elements);
154 remove_obsolete_starting_points();
157 void Stream::set_header(const std::string &new_http_header, const std::string &new_stream_header)
160 http_header = new_http_header;
161 if (new_stream_header == stream_header) {
165 // We cannot start at any of the older starting points anymore,
166 // since they'd get the wrong header for the stream (not to mention
167 // that a changed header probably means the stream restarted,
168 // which means any client starting on the old one would probably
169 // stop playing properly at the change point). Next block
170 // should be a suitable starting point (if not, something is
171 // pretty strange), so it will fill up again soon enough.
172 suitable_starting_points.clear();
174 // HLS, on the other hand, can deal with discontinuities and multiple
175 // headers. At least in theory (client support varies wildly).
176 if (!fragments.empty()) {
177 // Commit the old header to the backlog, so that we can serve it
178 // for all the old fragments for as long as they exist.
179 if (!stream_header.empty()) {
180 // End the current fragment and make a new one for the header.
181 fragments.push_back(Stream::FragmentStart { bytes_received, 0.0, true });
182 process_queued_data();
183 Stream::DataElement elem;
184 elem.data.iov_base = (char *)stream_header.data();
185 elem.data.iov_len = stream_header.size();
186 add_data_raw({ elem });
187 remove_obsolete_starting_points();
189 // The discontinuity counter will be increased when
190 // this header goes out of the backlog.
192 clear_hls_playlist_cache();
194 stream_header = new_stream_header;
197 void Stream::put_client_to_sleep(Client *client)
199 sleeping_clients.push_back(client);
202 // Return a new set of iovecs that contains only the first <bytes_wanted> bytes of <data>.
203 vector<iovec> collect_iovecs(const vector<Stream::DataElement> &data, size_t bytes_wanted)
206 size_t max_iovecs = min<size_t>(data.size(), IOV_MAX);
207 for (size_t i = 0; i < max_iovecs && bytes_wanted > 0; ++i) {
208 if (data[i].data.iov_len <= bytes_wanted) {
209 // Consume the entire iovec.
210 ret.push_back(data[i].data);
211 bytes_wanted -= data[i].data.iov_len;
213 // Take only parts of this iovec.
215 iov.iov_base = data[i].data.iov_base;
216 iov.iov_len = bytes_wanted;
224 // Return a new set of iovecs that contains all of <data> except the first <bytes_wanted> bytes.
225 vector<Stream::DataElement> remove_iovecs(const vector<Stream::DataElement> &data, size_t bytes_wanted)
227 vector<Stream::DataElement> ret;
229 for (i = 0; i < data.size() && bytes_wanted > 0; ++i) {
230 if (data[i].data.iov_len <= bytes_wanted) {
231 // Consume the entire iovec.
232 bytes_wanted -= data[i].data.iov_len;
234 // Take only parts of this iovec.
235 Stream::DataElement data_element;
236 data_element.data.iov_base = reinterpret_cast<char *>(data[i].data.iov_base) + bytes_wanted;
237 data_element.data.iov_len = data[i].data.iov_len - bytes_wanted;
238 data_element.metacube_flags = METACUBE_FLAGS_NOT_SUITABLE_FOR_STREAM_START;
239 data_element.pts = RationalPTS();
240 ret.push_back(data_element);
245 // Add the rest of the iovecs unchanged.
246 ret.insert(ret.end(), data.begin() + i, data.end());
250 void Stream::add_data_raw(const vector<DataElement> &orig_data)
252 vector<DataElement> data = orig_data;
253 while (!data.empty()) {
254 size_t pos = bytes_received % backlog_size;
256 // Collect as many iovecs as we can before we hit the point
257 // where the circular buffer wraps around.
258 vector<iovec> to_write = collect_iovecs(data, backlog_size - pos);
261 ret = pwritev(data_fd, to_write.data(), to_write.size(), pos);
262 } while (ret == -1 && errno == EINTR);
265 log_perror("pwritev");
266 // Dazed and confused, but trying to continue...
269 bytes_received += ret;
271 // Remove the data that was actually written from the set of iovecs.
272 data = remove_iovecs(data, ret);
276 void Stream::remove_obsolete_starting_points()
278 // We could do a binary search here (std::lower_bound), but it seems
279 // overkill for removing what's probably only a few points.
280 while (!suitable_starting_points.empty() &&
281 bytes_received - suitable_starting_points[0] > backlog_size) {
282 suitable_starting_points.pop_front();
284 assert(backlog_size >= hls_backlog_margin);
285 while (!fragments.empty() &&
286 bytes_received - fragments[0].byte_position > (backlog_size - hls_backlog_margin)) {
287 if (fragments[0].begins_header) {
288 ++discontinuity_counter;
290 ++first_fragment_index;
292 fragments.pop_front();
293 clear_hls_playlist_cache();
297 void Stream::add_data_deferred(const char *data, size_t bytes, uint16_t metacube_flags, const RationalPTS &pts)
299 // For regular output, we don't want to send the client twice
300 // (it's already sent out together with the HTTP header).
301 // However, for Metacube output, we need to send it so that
302 // the Cubemap instance in the other end has a chance to update it.
303 // It may come twice in its stream, but Cubemap doesn't care.
304 if (encoding == Stream::STREAM_ENCODING_RAW &&
305 (metacube_flags & METACUBE_FLAGS_HEADER) != 0) {
309 lock_guard<mutex> lock(queued_data_mutex);
311 DataElement data_element;
312 data_element.metacube_flags = metacube_flags;
313 data_element.pts = pts;
315 if (encoding == Stream::STREAM_ENCODING_METACUBE) {
316 // Construct a PTS metadata block. (We'll avoid sending it out
317 // if we don't have a valid PTS.)
318 metacube2_pts_packet pts_packet;
319 pts_packet.type = htobe64(METACUBE_METADATA_TYPE_NEXT_BLOCK_PTS);
320 pts_packet.pts = htobe64(pts.pts);
321 pts_packet.timebase_num = htobe64(pts.timebase_num);
322 pts_packet.timebase_den = htobe64(pts.timebase_den);
324 metacube2_block_header pts_hdr;
325 memcpy(pts_hdr.sync, METACUBE2_SYNC, sizeof(pts_hdr.sync));
326 pts_hdr.size = htonl(sizeof(pts_packet));
327 pts_hdr.flags = htons(METACUBE_FLAGS_METADATA);
328 pts_hdr.csum = htons(metacube2_compute_crc(&pts_hdr));
330 // Add a Metacube block header before the data.
331 metacube2_block_header hdr;
332 memcpy(hdr.sync, METACUBE2_SYNC, sizeof(hdr.sync));
333 hdr.size = htonl(bytes);
334 hdr.flags = htons(metacube_flags);
335 hdr.csum = htons(metacube2_compute_crc(&hdr));
337 data_element.data.iov_len = bytes + sizeof(hdr);
338 if (pts.timebase_num != 0) {
339 data_element.data.iov_len += sizeof(pts_hdr) + sizeof(pts_packet);
341 data_element.data.iov_base = new char[data_element.data.iov_len];
343 char *ptr = reinterpret_cast<char *>(data_element.data.iov_base);
344 if (pts.timebase_num != 0) {
345 memcpy(ptr, &pts_hdr, sizeof(pts_hdr));
346 ptr += sizeof(pts_hdr);
347 memcpy(ptr, &pts_packet, sizeof(pts_packet));
348 ptr += sizeof(pts_packet);
351 memcpy(ptr, &hdr, sizeof(hdr));
353 memcpy(ptr, data, bytes);
355 queued_data.push_back(data_element);
356 } else if (encoding == Stream::STREAM_ENCODING_RAW) {
357 // Just add the data itself.
358 data_element.data.iov_base = new char[bytes];
359 memcpy(data_element.data.iov_base, data, bytes);
360 data_element.data.iov_len = bytes;
362 queued_data.push_back(data_element);
368 void Stream::process_queued_data()
370 vector<DataElement> queued_data_copy;
372 // Hold the lock for as short as possible, since add_data_raw() can possibly
373 // write to disk, which might disturb the input thread.
375 lock_guard<mutex> lock(queued_data_mutex);
376 if (queued_data.empty()) {
380 swap(queued_data, queued_data_copy);
383 // Add suitable starting points for the stream, if the queued data
384 // contains such starting points. Note that we drop starting points
385 // if they're less than 10 kB apart, so that we don't get a huge
386 // amount of them for e.g. each and every MPEG-TS 188-byte cell.
387 // The 10 kB value is somewhat arbitrary, but at least it should make
388 // the RAM cost of saving the position ~0.1% (or less) of the actual
389 // data, and 10 kB is a very fine granularity in most streams.
390 static const int minimum_start_point_distance = 10240;
391 size_t byte_position = bytes_received;
392 bool need_hls_clear = false;
393 for (const DataElement &elem : queued_data_copy) {
394 if ((elem.metacube_flags & METACUBE_FLAGS_NOT_SUITABLE_FOR_STREAM_START) == 0) {
395 size_t num_points = suitable_starting_points.size();
396 if (num_points >= 2 &&
397 suitable_starting_points[num_points - 1] - suitable_starting_points[num_points - 2] < minimum_start_point_distance) {
398 // p[n-1] - p[n-2] < 10 kB, so drop p[n-1].
399 suitable_starting_points.pop_back();
401 suitable_starting_points.push_back(byte_position);
403 if (elem.pts.timebase_num != 0) {
404 need_hls_clear |= add_fragment_boundary(byte_position, elem.pts);
407 byte_position += elem.data.iov_len;
409 if (need_hls_clear) {
410 clear_hls_playlist_cache();
413 add_data_raw(queued_data_copy);
414 remove_obsolete_starting_points();
415 for (const DataElement &elem : queued_data_copy) {
416 char *data = reinterpret_cast<char *>(elem.data.iov_base);
420 // We have more data, so wake up all clients.
421 if (to_process.empty()) {
422 swap(sleeping_clients, to_process);
424 to_process.insert(to_process.end(), sleeping_clients.begin(), sleeping_clients.end());
425 sleeping_clients.clear();
429 bool Stream::add_fragment_boundary(size_t byte_position, const RationalPTS &pts)
431 double pts_double = double(pts.pts) * pts.timebase_den / pts.timebase_num;
433 if (fragments.size() <= 1 ||
434 fragments[fragments.size() - 1].begins_header ||
435 fragments[fragments.size() - 2].begins_header) {
436 // Just starting up, so try to establish the first in-progress fragment.
437 fragments.push_back(FragmentStart{ byte_position, pts_double, false });
441 // Keep extending the in-progress fragment as long as we do not
442 // exceed the target duration by more than half a second
443 // (RFC 8216 4.3.3.1) and we get closer to the target by doing so.
444 // Note that in particular, this means we'll always extend
445 // as long as we don't exceed the target duration.
446 double current_duration = pts_double - fragments[fragments.size() - 1].pts;
447 double candidate_duration = pts_double - fragments[fragments.size() - 2].pts;
448 if (lrintf(candidate_duration) <= hls_frag_duration &&
449 fabs(candidate_duration - hls_frag_duration) < fabs(current_duration - hls_frag_duration)) {
450 fragments.back() = FragmentStart{ byte_position, pts_double, false };
453 // Extending the in-progress fragment would make it too long,
454 // so finalize it and start a new in-progress fragment.
455 fragments.push_back(FragmentStart{ byte_position, pts_double, false });
460 void Stream::clear_hls_playlist_cache()
462 hls_playlist_http10.reset();
463 hls_playlist_http11_close.reset();
464 hls_playlist_http11_persistent.reset();
467 shared_ptr<const string> Stream::generate_hls_playlist(bool http_11, bool close_after_response)
470 snprintf(buf, sizeof(buf),
472 "#EXT-X-VERSION:7\r\n"
473 "#EXT-X-TARGETDURATION:%u\r\n"
474 "#EXT-X-MEDIA-SEQUENCE:%" PRIu64 "\r\n"
475 "#EXT-X-DISCONTINUITY-SEQUENCE:%" PRIu64 "\r\n",
477 first_fragment_index,
478 discontinuity_counter);
480 string playlist = buf;
482 if (fragments.size() >= 3) {
483 bool printed_header_for_this_group = false;
484 bool printed_first_header = false;
485 for (size_t i = 0; i < fragments.size() - 2; ++i) {
488 if (fragments[i].begins_header) {
489 // End of this group. (We've already printed the header
490 // as part of the previous group.)
491 printed_header_for_this_group = false;
494 if (!printed_header_for_this_group) {
495 // Look forward until we find the header for this group (if any).
496 for (size_t j = i + 1; j < fragments.size() - 1; ++j) {
497 if (fragments[j].begins_header) {
498 if (printed_first_header) {
499 playlist += "#EXT-X-DISCONTINUITY\r\n";
501 snprintf(buf, sizeof(buf),
502 "#EXT-X-MAP:URI=\"%s?frag=%" PRIu64 "-%" PRIu64 "\"\r\n",
503 url.c_str(), fragments[j].byte_position,
504 fragments[j + 1].byte_position);
506 printed_first_header = true;
507 printed_header_for_this_group = true;
512 if (!printed_header_for_this_group && !stream_header.empty()) {
513 if (printed_first_header) {
514 playlist += "#EXT-X-DISCONTINUITY\r\n";
516 snprintf(buf, sizeof(buf), "#EXT-X-MAP:URI=\"%s?frag=header\"\r\n", url.c_str());
520 // Even if we didn't find anything, we don't want to search again for each fragment.
521 printed_first_header = true;
522 printed_header_for_this_group = true;
525 if (fragments[i + 1].begins_header) {
526 // Since we only have start pts for each block and not duration,
527 // we have no idea how long this fragment is; the encoder restarted
528 // before it got to output the next pts. However, it's likely
529 // to be very short, so instead of trying to guess, we just skip it.
533 snprintf(buf, sizeof(buf), "#EXTINF:%f,\r\n%s?frag=%" PRIu64 "-%" PRIu64 "\r\n",
534 fragments[i + 1].pts - fragments[i].pts,
536 fragments[i].byte_position,
537 fragments[i + 1].byte_position);
544 response = "HTTP/1.1 200 OK\r\n";
545 if (close_after_response) {
546 response.append("Connection: close\r\n");
549 assert(close_after_response);
550 response = "HTTP/1.0 200 OK\r\n";
552 snprintf(buf, sizeof(buf), "Content-Length: %zu\r\n", playlist.size());
553 response.append(buf);
554 response.append("Content-Type: application/x-mpegURL\r\n");
555 if (!allow_origin.empty()) {
556 response.append("Access-Control-Allow-Origin: ");
557 response.append(allow_origin);
558 response.append("\r\n");
560 response.append("\r\n");
561 response.append(move(playlist));
563 return shared_ptr<const string>(new string(move(response)));