5 #include <netinet/in.h>
16 #include "metacube2.h"
23 Stream::Stream(const string &url,
25 size_t prebuffering_bytes,
27 Encoding src_encoding,
28 unsigned hls_frag_duration,
29 size_t hls_backlog_margin,
30 const std::string &allow_origin)
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)
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.
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())
68 for (ssize_t point : serialized.suitable_starting_point()) {
70 // Can happen when upgrading from before 1.1.3,
71 // where this was an optional field with -1 signifying
75 suitable_starting_points.push_back(point);
78 for (const FragmentStartProto &fragment : serialized.fragment()) {
79 fragments.push_back(FragmentStart { size_t(fragment.byte_position()), fragment.pts() });
83 StreamProto Stream::serialize()
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);
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);
99 serialized.set_first_fragment_index(first_fragment_index);
100 serialized.set_discontinuity_counter(discontinuity_counter);
102 serialized.set_url(url);
107 void Stream::set_backlog_size(size_t new_size)
109 if (backlog_size == new_size) {
113 string existing_data;
114 if (!read_tempfile_and_close(data_fd, &existing_data)) {
118 // Unwrap the data so it's no longer circular.
119 if (bytes_received <= backlog_size) {
120 existing_data.resize(bytes_received);
122 size_t pos = bytes_received % backlog_size;
123 existing_data = existing_data.substr(pos, string::npos) +
124 existing_data.substr(0, pos);
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);
133 // Create a new, empty data file.
134 data_fd = make_tempfile("");
138 backlog_size = new_size;
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().
147 vector<DataElement> data_elements;
148 data_elements.push_back(data_element);
149 add_data_raw(data_elements);
150 remove_obsolete_starting_points();
153 void Stream::put_client_to_sleep(Client *client)
155 sleeping_clients.push_back(client);
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)
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;
169 // Take only parts of this iovec.
171 iov.iov_base = data[i].data.iov_base;
172 iov.iov_len = bytes_wanted;
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)
183 vector<Stream::DataElement> ret;
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;
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);
201 // Add the rest of the iovecs unchanged.
202 ret.insert(ret.end(), data.begin() + i, data.end());
206 void Stream::add_data_raw(const vector<DataElement> &orig_data)
208 vector<DataElement> data = orig_data;
209 while (!data.empty()) {
210 size_t pos = bytes_received % backlog_size;
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);
217 ret = pwritev(data_fd, to_write.data(), to_write.size(), pos);
218 } while (ret == -1 && errno == EINTR);
221 log_perror("pwritev");
222 // Dazed and confused, but trying to continue...
225 bytes_received += ret;
227 // Remove the data that was actually written from the set of iovecs.
228 data = remove_iovecs(data, ret);
232 void Stream::remove_obsolete_starting_points()
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();
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();
249 void Stream::add_data_deferred(const char *data, size_t bytes, uint16_t metacube_flags, const RationalPTS &pts)
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) {
261 lock_guard<mutex> lock(queued_data_mutex);
263 DataElement data_element;
264 data_element.metacube_flags = metacube_flags;
265 data_element.pts = pts;
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);
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));
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));
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);
293 data_element.data.iov_base = new char[data_element.data.iov_len];
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);
303 memcpy(ptr, &hdr, sizeof(hdr));
305 memcpy(ptr, data, bytes);
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;
314 queued_data.push_back(data_element);
320 void Stream::process_queued_data()
322 vector<DataElement> queued_data_copy;
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.
327 lock_guard<mutex> lock(queued_data_mutex);
328 if (queued_data.empty()) {
332 swap(queued_data, queued_data_copy);
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();
353 suitable_starting_points.push_back(byte_position);
355 if (elem.pts.timebase_num != 0) {
356 need_hls_clear |= add_fragment_boundary(byte_position, elem.pts);
359 byte_position += elem.data.iov_len;
361 if (need_hls_clear) {
362 clear_hls_playlist_cache();
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);
372 // We have more data, so wake up all clients.
373 if (to_process.empty()) {
374 swap(sleeping_clients, to_process);
376 to_process.insert(to_process.end(), sleeping_clients.begin(), sleeping_clients.end());
377 sleeping_clients.clear();
381 bool Stream::add_fragment_boundary(size_t byte_position, const RationalPTS &pts)
383 double pts_double = double(pts.pts) * pts.timebase_den / pts.timebase_num;
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 });
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 };
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 });
410 void Stream::clear_hls_playlist_cache()
412 hls_playlist_http10.reset();
413 hls_playlist_http11_close.reset();
414 hls_playlist_http11_persistent.reset();
417 shared_ptr<const string> Stream::generate_hls_playlist(bool http_11, bool close_after_response)
420 snprintf(buf, sizeof(buf),
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",
427 first_fragment_index,
428 discontinuity_counter);
430 string playlist = buf;
432 if (!stream_header.empty()) {
433 snprintf(buf, sizeof(buf), "#EXT-X-MAP:URI=\"%s?frag=header\"\r\n", url.c_str());
438 if (fragments.size() >= 3) {
439 for (size_t i = 0; i < fragments.size() - 2; ++i) {
441 snprintf(buf, sizeof(buf), "#EXTINF:%f,\r\n%s?frag=%zu-%zu\r\n",
442 fragments[i + 1].pts - fragments[i].pts,
444 fragments[i].byte_position,
445 fragments[i + 1].byte_position);
452 response = "HTTP/1.1 200 OK\r\n";
453 if (close_after_response) {
454 response.append("Connection: close\r\n");
457 assert(close_after_response);
458 response = "HTTP/1.0 200 OK\r\n";
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");
468 response.append("\r\n");
469 response.append(move(playlist));
471 return shared_ptr<const string>(new string(move(response)));