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 http_header(serialized.http_header()),
57 stream_header(serialized.stream_header()),
58 encoding(Stream::STREAM_ENCODING_RAW), // Will be changed later.
60 backlog_size(serialized.backlog_size()),
61 bytes_received(serialized.bytes_received()),
62 first_fragment_index(serialized.first_fragment_index()),
63 discontinuity_counter(serialized.discontinuity_counter())
69 for (ssize_t point : serialized.suitable_starting_point()) {
71 // Can happen when upgrading from before 1.1.3,
72 // where this was an optional field with -1 signifying
76 suitable_starting_points.push_back(point);
79 for (const FragmentStartProto &fragment : serialized.fragment()) {
80 fragments.push_back(FragmentStart { size_t(fragment.byte_position()), fragment.pts(), fragment.begins_header() });
84 StreamProto Stream::serialize()
86 StreamProto serialized;
87 serialized.set_http_header(http_header);
88 serialized.set_stream_header(stream_header);
89 serialized.add_data_fds(data_fd);
90 serialized.set_backlog_size(backlog_size);
91 serialized.set_bytes_received(bytes_received);
92 for (size_t point : suitable_starting_points) {
93 serialized.add_suitable_starting_point(point);
95 for (const FragmentStart &fragment : fragments) {
96 FragmentStartProto *proto = serialized.add_fragment();
97 proto->set_byte_position(fragment.byte_position);
98 proto->set_pts(fragment.pts);
99 proto->set_begins_header(fragment.begins_header);
101 serialized.set_first_fragment_index(first_fragment_index);
102 serialized.set_discontinuity_counter(discontinuity_counter);
104 serialized.set_url(url);
109 void Stream::set_backlog_size(size_t new_size)
111 if (backlog_size == new_size) {
115 string existing_data;
116 if (!read_tempfile_and_close(data_fd, &existing_data)) {
120 // Unwrap the data so it's no longer circular.
121 if (bytes_received <= backlog_size) {
122 existing_data.resize(bytes_received);
124 size_t pos = bytes_received % backlog_size;
125 existing_data = existing_data.substr(pos, string::npos) +
126 existing_data.substr(0, pos);
129 // See if we need to discard data.
130 if (new_size < existing_data.size()) {
131 size_t to_discard = existing_data.size() - new_size;
132 existing_data = existing_data.substr(to_discard, string::npos);
135 // Create a new, empty data file.
136 data_fd = make_tempfile("");
140 backlog_size = new_size;
142 // Now cheat a bit by rewinding, and adding all the old data back.
143 bytes_received -= existing_data.size();
144 DataElement data_element;
145 data_element.data.iov_base = const_cast<char *>(existing_data.data());
146 data_element.data.iov_len = existing_data.size();
147 data_element.metacube_flags = 0; // Ignored by add_data_raw().
149 vector<DataElement> data_elements;
150 data_elements.push_back(data_element);
151 add_data_raw(data_elements);
152 remove_obsolete_starting_points();
155 void Stream::set_header(const std::string &new_http_header, const std::string &new_stream_header)
157 http_header = new_http_header;
158 if (new_stream_header == stream_header) {
162 // We cannot start at any of the older starting points anymore,
163 // since they'd get the wrong header for the stream (not to mention
164 // that a changed header probably means the stream restarted,
165 // which means any client starting on the old one would probably
166 // stop playing properly at the change point). Next block
167 // should be a suitable starting point (if not, something is
168 // pretty strange), so it will fill up again soon enough.
169 suitable_starting_points.clear();
171 // HLS, on the other hand, can deal with discontinuities and multiple
172 // headers. At least in theory (client support varies wildly).
173 if (!fragments.empty()) {
174 // Commit the old header to the backlog, so that we can serve it
175 // for all the old fragments for as long as they exist.
176 if (!stream_header.empty()) {
177 // End the current fragment and make a new one for the header.
178 fragments.push_back(Stream::FragmentStart { bytes_received, 0.0, true });
179 process_queued_data();
180 Stream::DataElement elem;
181 elem.data.iov_base = (char *)stream_header.data();
182 elem.data.iov_len = stream_header.size();
183 add_data_raw({ elem });
184 remove_obsolete_starting_points();
186 // The discontinuity counter will be increased when
187 // this header goes out of the backlog.
189 clear_hls_playlist_cache();
191 stream_header = new_stream_header;
194 void Stream::put_client_to_sleep(Client *client)
196 sleeping_clients.push_back(client);
199 // Return a new set of iovecs that contains only the first <bytes_wanted> bytes of <data>.
200 vector<iovec> collect_iovecs(const vector<Stream::DataElement> &data, size_t bytes_wanted)
203 size_t max_iovecs = min<size_t>(data.size(), IOV_MAX);
204 for (size_t i = 0; i < max_iovecs && bytes_wanted > 0; ++i) {
205 if (data[i].data.iov_len <= bytes_wanted) {
206 // Consume the entire iovec.
207 ret.push_back(data[i].data);
208 bytes_wanted -= data[i].data.iov_len;
210 // Take only parts of this iovec.
212 iov.iov_base = data[i].data.iov_base;
213 iov.iov_len = bytes_wanted;
221 // Return a new set of iovecs that contains all of <data> except the first <bytes_wanted> bytes.
222 vector<Stream::DataElement> remove_iovecs(const vector<Stream::DataElement> &data, size_t bytes_wanted)
224 vector<Stream::DataElement> ret;
226 for (i = 0; i < data.size() && bytes_wanted > 0; ++i) {
227 if (data[i].data.iov_len <= bytes_wanted) {
228 // Consume the entire iovec.
229 bytes_wanted -= data[i].data.iov_len;
231 // Take only parts of this iovec.
232 Stream::DataElement data_element;
233 data_element.data.iov_base = reinterpret_cast<char *>(data[i].data.iov_base) + bytes_wanted;
234 data_element.data.iov_len = data[i].data.iov_len - bytes_wanted;
235 data_element.metacube_flags = METACUBE_FLAGS_NOT_SUITABLE_FOR_STREAM_START;
236 data_element.pts = RationalPTS();
237 ret.push_back(data_element);
242 // Add the rest of the iovecs unchanged.
243 ret.insert(ret.end(), data.begin() + i, data.end());
247 void Stream::add_data_raw(const vector<DataElement> &orig_data)
249 vector<DataElement> data = orig_data;
250 while (!data.empty()) {
251 size_t pos = bytes_received % backlog_size;
253 // Collect as many iovecs as we can before we hit the point
254 // where the circular buffer wraps around.
255 vector<iovec> to_write = collect_iovecs(data, backlog_size - pos);
258 ret = pwritev(data_fd, to_write.data(), to_write.size(), pos);
259 } while (ret == -1 && errno == EINTR);
262 log_perror("pwritev");
263 // Dazed and confused, but trying to continue...
266 bytes_received += ret;
268 // Remove the data that was actually written from the set of iovecs.
269 data = remove_iovecs(data, ret);
273 void Stream::remove_obsolete_starting_points()
275 // We could do a binary search here (std::lower_bound), but it seems
276 // overkill for removing what's probably only a few points.
277 while (!suitable_starting_points.empty() &&
278 bytes_received - suitable_starting_points[0] > backlog_size) {
279 suitable_starting_points.pop_front();
281 assert(backlog_size >= hls_backlog_margin);
282 while (!fragments.empty() &&
283 bytes_received - fragments[0].byte_position > (backlog_size - hls_backlog_margin)) {
284 if (fragments[0].begins_header) {
285 ++discontinuity_counter;
287 ++first_fragment_index;
289 fragments.pop_front();
290 clear_hls_playlist_cache();
294 void Stream::add_data_deferred(const char *data, size_t bytes, uint16_t metacube_flags, const RationalPTS &pts)
296 // For regular output, we don't want to send the client twice
297 // (it's already sent out together with the HTTP header).
298 // However, for Metacube output, we need to send it so that
299 // the Cubemap instance in the other end has a chance to update it.
300 // It may come twice in its stream, but Cubemap doesn't care.
301 if (encoding == Stream::STREAM_ENCODING_RAW &&
302 (metacube_flags & METACUBE_FLAGS_HEADER) != 0) {
306 lock_guard<mutex> lock(queued_data_mutex);
308 DataElement data_element;
309 data_element.metacube_flags = metacube_flags;
310 data_element.pts = pts;
312 if (encoding == Stream::STREAM_ENCODING_METACUBE) {
313 // Construct a PTS metadata block. (We'll avoid sending it out
314 // if we don't have a valid PTS.)
315 metacube2_pts_packet pts_packet;
316 pts_packet.type = htobe64(METACUBE_METADATA_TYPE_NEXT_BLOCK_PTS);
317 pts_packet.pts = htobe64(pts.pts);
318 pts_packet.timebase_num = htobe64(pts.timebase_num);
319 pts_packet.timebase_den = htobe64(pts.timebase_den);
321 metacube2_block_header pts_hdr;
322 memcpy(pts_hdr.sync, METACUBE2_SYNC, sizeof(pts_hdr.sync));
323 pts_hdr.size = htonl(sizeof(pts_packet));
324 pts_hdr.flags = htons(METACUBE_FLAGS_METADATA);
325 pts_hdr.csum = htons(metacube2_compute_crc(&pts_hdr));
327 // Add a Metacube block header before the data.
328 metacube2_block_header hdr;
329 memcpy(hdr.sync, METACUBE2_SYNC, sizeof(hdr.sync));
330 hdr.size = htonl(bytes);
331 hdr.flags = htons(metacube_flags);
332 hdr.csum = htons(metacube2_compute_crc(&hdr));
334 data_element.data.iov_len = bytes + sizeof(hdr);
335 if (pts.timebase_num != 0) {
336 data_element.data.iov_len += sizeof(pts_hdr) + sizeof(pts_packet);
338 data_element.data.iov_base = new char[data_element.data.iov_len];
340 char *ptr = reinterpret_cast<char *>(data_element.data.iov_base);
341 if (pts.timebase_num != 0) {
342 memcpy(ptr, &pts_hdr, sizeof(pts_hdr));
343 ptr += sizeof(pts_hdr);
344 memcpy(ptr, &pts_packet, sizeof(pts_packet));
345 ptr += sizeof(pts_packet);
348 memcpy(ptr, &hdr, sizeof(hdr));
350 memcpy(ptr, data, bytes);
352 queued_data.push_back(data_element);
353 } else if (encoding == Stream::STREAM_ENCODING_RAW) {
354 // Just add the data itself.
355 data_element.data.iov_base = new char[bytes];
356 memcpy(data_element.data.iov_base, data, bytes);
357 data_element.data.iov_len = bytes;
359 queued_data.push_back(data_element);
365 void Stream::process_queued_data()
367 vector<DataElement> queued_data_copy;
369 // Hold the lock for as short as possible, since add_data_raw() can possibly
370 // write to disk, which might disturb the input thread.
372 lock_guard<mutex> lock(queued_data_mutex);
373 if (queued_data.empty()) {
377 swap(queued_data, queued_data_copy);
380 // Add suitable starting points for the stream, if the queued data
381 // contains such starting points. Note that we drop starting points
382 // if they're less than 10 kB apart, so that we don't get a huge
383 // amount of them for e.g. each and every MPEG-TS 188-byte cell.
384 // The 10 kB value is somewhat arbitrary, but at least it should make
385 // the RAM cost of saving the position ~0.1% (or less) of the actual
386 // data, and 10 kB is a very fine granularity in most streams.
387 static const int minimum_start_point_distance = 10240;
388 size_t byte_position = bytes_received;
389 bool need_hls_clear = false;
390 for (const DataElement &elem : queued_data_copy) {
391 if ((elem.metacube_flags & METACUBE_FLAGS_NOT_SUITABLE_FOR_STREAM_START) == 0) {
392 size_t num_points = suitable_starting_points.size();
393 if (num_points >= 2 &&
394 suitable_starting_points[num_points - 1] - suitable_starting_points[num_points - 2] < minimum_start_point_distance) {
395 // p[n-1] - p[n-2] < 10 kB, so drop p[n-1].
396 suitable_starting_points.pop_back();
398 suitable_starting_points.push_back(byte_position);
400 if (elem.pts.timebase_num != 0) {
401 need_hls_clear |= add_fragment_boundary(byte_position, elem.pts);
404 byte_position += elem.data.iov_len;
406 if (need_hls_clear) {
407 clear_hls_playlist_cache();
410 add_data_raw(queued_data_copy);
411 remove_obsolete_starting_points();
412 for (const DataElement &elem : queued_data_copy) {
413 char *data = reinterpret_cast<char *>(elem.data.iov_base);
417 // We have more data, so wake up all clients.
418 if (to_process.empty()) {
419 swap(sleeping_clients, to_process);
421 to_process.insert(to_process.end(), sleeping_clients.begin(), sleeping_clients.end());
422 sleeping_clients.clear();
426 bool Stream::add_fragment_boundary(size_t byte_position, const RationalPTS &pts)
428 double pts_double = double(pts.pts) * pts.timebase_den / pts.timebase_num;
430 if (fragments.size() <= 1 ||
431 fragments[fragments.size() - 1].begins_header ||
432 fragments[fragments.size() - 2].begins_header) {
433 // Just starting up, so try to establish the first in-progress fragment.
434 fragments.push_back(FragmentStart{ byte_position, pts_double, false });
438 // Keep extending the in-progress fragment as long as we do not
439 // exceed the target duration by more than half a second
440 // (RFC 8216 4.3.3.1) and we get closer to the target by doing so.
441 // Note that in particular, this means we'll always extend
442 // as long as we don't exceed the target duration.
443 double current_duration = pts_double - fragments[fragments.size() - 1].pts;
444 double candidate_duration = pts_double - fragments[fragments.size() - 2].pts;
445 if (lrintf(candidate_duration) <= hls_frag_duration &&
446 fabs(candidate_duration - hls_frag_duration) < fabs(current_duration - hls_frag_duration)) {
447 fragments.back() = FragmentStart{ byte_position, pts_double, false };
450 // Extending the in-progress fragment would make it too long,
451 // so finalize it and start a new in-progress fragment.
452 fragments.push_back(FragmentStart{ byte_position, pts_double, false });
457 void Stream::clear_hls_playlist_cache()
459 hls_playlist_http10.reset();
460 hls_playlist_http11_close.reset();
461 hls_playlist_http11_persistent.reset();
464 shared_ptr<const string> Stream::generate_hls_playlist(bool http_11, bool close_after_response)
467 snprintf(buf, sizeof(buf),
469 "#EXT-X-VERSION:7\r\n"
470 "#EXT-X-TARGETDURATION:%u\r\n"
471 "#EXT-X-MEDIA-SEQUENCE:%" PRIu64 "\r\n"
472 "#EXT-X-DISCONTINUITY-SEQUENCE:%" PRIu64 "\r\n",
474 first_fragment_index,
475 discontinuity_counter);
477 string playlist = buf;
479 if (fragments.size() >= 3) {
480 bool printed_header_for_this_group = false;
481 bool printed_first_header = false;
482 for (size_t i = 0; i < fragments.size() - 2; ++i) {
485 if (fragments[i].begins_header) {
486 // End of this group. (We've already printed the header
487 // as part of the previous group.)
488 printed_header_for_this_group = false;
491 if (!printed_header_for_this_group) {
492 // Look forward until we find the header for this group (if any).
493 for (size_t j = i + 1; j < fragments.size() - 1; ++j) {
494 if (fragments[j].begins_header) {
495 if (printed_first_header) {
496 playlist += "#EXT-X-DISCONTINUITY\r\n";
498 snprintf(buf, sizeof(buf),
499 "#EXT-X-MAP:URI=\"%s?frag=%" PRIu64 "-%" PRIu64 "\"\r\n",
500 url.c_str(), fragments[j].byte_position,
501 fragments[j + 1].byte_position);
503 printed_first_header = true;
504 printed_header_for_this_group = true;
509 if (!printed_header_for_this_group && !stream_header.empty()) {
510 if (printed_first_header) {
511 playlist += "#EXT-X-DISCONTINUITY\r\n";
513 snprintf(buf, sizeof(buf), "#EXT-X-MAP:URI=\"%s?frag=header\"\r\n", url.c_str());
517 // Even if we didn't find anything, we don't want to search again for each fragment.
518 printed_first_header = true;
519 printed_header_for_this_group = true;
522 if (fragments[i + 1].begins_header) {
523 // Since we only have start pts for each block and not duration,
524 // we have no idea how long this fragment is; the encoder restarted
525 // before it got to output the next pts. However, it's likely
526 // to be very short, so instead of trying to guess, we just skip it.
530 snprintf(buf, sizeof(buf), "#EXTINF:%f,\r\n%s?frag=%" PRIu64 "-%" PRIu64 "\r\n",
531 fragments[i + 1].pts - fragments[i].pts,
533 fragments[i].byte_position,
534 fragments[i + 1].byte_position);
541 response = "HTTP/1.1 200 OK\r\n";
542 if (close_after_response) {
543 response.append("Connection: close\r\n");
546 assert(close_after_response);
547 response = "HTTP/1.0 200 OK\r\n";
549 snprintf(buf, sizeof(buf), "Content-Length: %zu\r\n", playlist.size());
550 response.append(buf);
551 response.append("Content-Type: application/x-mpegURL\r\n");
552 if (!allow_origin.empty()) {
553 response.append("Access-Control-Allow-Origin: ");
554 response.append(allow_origin);
555 response.append("\r\n");
557 response.append("\r\n");
558 response.append(move(playlist));
560 return shared_ptr<const string>(new string(move(response)));