Re: [whatwg/streams] Fix makeReadableBackpressureByteSocketStream to drain all data (#504)

Those are both great ideas. So if desiredSize is low (e.g. negative) then we're accumulating too much buffered data and we can afford a higher bitrate, basically. Something like this, perhaps?

```js
  const STARTING_BIT_RATE = 131072;       // 1 Mbps
  const DEFAULT_CHUNK_SIZE = 65536;       // 64 KiB
  const PREFERRED_QUEUED_SIZE = 10485760; // 10 MiB

  function makeReadableVideoSocketStream(host, port) {
    const socket = createUDPSocket(host, port);

    return new ReadableStream({
      type: "bytes",

      start(controller) {
        socket.send(createSetBitrateMessage(STARTING_BIT_RATE));

        readRepeatedly().catch(e => controller.error(e));

        function readRepeatedly() {
          return socket.select2().then(() => {
            // Since the socket can become readable even when there’s
            // no pending BYOB requests, we need to handle both cases.
            let bytesRead;
            if (controller.byobRequest) {
              const v = controller.byobRequest.view;
              bytesRead = socket.readInto(v.buffer, v.byteOffset, v.byteLength);
              controller.byobRequest.respond(bytesRead);
            } else {
              const buffer = new ArrayBuffer(DEFAULT_WINDOW_SIZE);
              bytesRead = socket.readInto(buffer, 0, DEFAULT_WINDOW_SIZE);
              controller.enqueue(new Uint8Array(buffer, 0, bytesRead));
            }
            
            if (bytesRead === 0) {
              controller.close();
              return;
            }

            // Adjust the bitrate according to how much data we have queued
            // (If the queue is full, then we can up the bitrate for higher quality)
            const newBitrate = determineBestBitrate(controller.desiredSize);
            socket.send(createSetBitrateMessage(newBitrate));

            return readRepeatedly();
          });
        }
      }
      pull(controller) {
        // This is called when the internal queue has been drained, and the
        // stream's consumer can accept more data. Recompute the best bitrate
        // using the new desiredSize.
        const newBitrate = determineBestBitrate(controller.desiredSize);
        socket.send(createSetBitrateMessage(newBitrate));
      },

      cancel() {
        socket.close();
      }
    }, {
      highWaterMark: PREFERRED_QUEUED_SIZE
    });
  }
```

I am picturing people who actually work on adaptive video streaming cringing at this simplistic code, but it does kind of get the point across, I think...

-- 
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/whatwg/streams/pull/504#issuecomment-239562465

Received on Friday, 12 August 2016 21:20:25 UTC