Add support for forced prebuffering.
[cubemap] / server.cpp
index a2f28e6..6fa4991 100644 (file)
@@ -198,6 +198,7 @@ void Server::add_client_from_serialized(const ClientProto &client)
        }
 
        if (client_ptr->state == Client::WAITING_FOR_KEYFRAME ||
+           client_ptr->state == Client::PREBUFFERING ||
            (client_ptr->state == Client::SENDING_DATA &&
             client_ptr->stream_pos == client_ptr->stream->bytes_received)) {
                client_ptr->stream->put_client_to_sleep(client_ptr);
@@ -215,11 +216,11 @@ int Server::lookup_stream_by_url(const std::string &url) const
        return url_it->second;
 }
 
-int Server::add_stream(const string &url, size_t backlog_size, Stream::Encoding encoding)
+int Server::add_stream(const string &url, size_t backlog_size, size_t prebuffering_bytes, Stream::Encoding encoding)
 {
        MutexLock lock(&mutex);
        url_map.insert(make_pair(url, streams.size()));
-       streams.push_back(new Stream(url, backlog_size, encoding));
+       streams.push_back(new Stream(url, backlog_size, prebuffering_bytes, encoding));
        return streams.size() - 1;
 }
 
@@ -399,6 +400,18 @@ sending_header_or_error_again:
                        return;
                }
                client->stream_pos = stream->last_suitable_starting_point;
+               client->state = Client::PREBUFFERING;
+               // Fall through.
+       }
+       case Client::PREBUFFERING: {
+               Stream *stream = client->stream;
+               size_t bytes_to_send = stream->bytes_received - client->stream_pos;
+               assert(bytes_to_send <= stream->backlog_size);
+               if (bytes_to_send < stream->prebuffering_bytes) {
+                       // We don't have enough bytes buffered to start this client yet.
+                       stream->put_client_to_sleep(client);
+                       return;
+               }
                client->state = Client::SENDING_DATA;
                // Fall through.
        }