jhiesey / videostream

Play html5 video when from a file-like object
MIT License
243 stars 74 forks source link

How to wait for data #8

Open tghosgor opened 9 years ago

tghosgor commented 9 years ago

Let's say that I am manually generating the data. I can't really see the way to do it here:

var exampleFile = {
    length: 100000, // Total size of the file
    createReadStream: function (opts) {
        var start = opts.start;
        var end = opts.end;
        // Return a readable stream that provides the bytes
        // between offsets "start" and "end" inclusive
    }
}

Let's say that start=100 end=200 is requested and I do not have and cannot yet generate the data when this request has happened. I will however will be able to provide the data in 5 seconds. Is it possible to do this?

Also, is there a documentation that defines the interface of the object to be returned in createReadStream?

Thanks.

P.S. The environment is the latest Chromium browser.

jhiesey commented 9 years ago

The object to be returned by createReadStream should be a node-style readable stream. What you need to do on your end is documented here: https://nodejs.org/api/stream.html#stream_class_stream_readable_1

Essentially it boils down to implementing a ._read() method, which doesn't need to return the data immediately, but notifies your code that data is needed. You then call .push() with the data asynchronously when the data is available. With this mechanism it's simple to provide the stream object immediately and call .push() once read has been called and the data is available.

If you use Browserify, you can just require('stream').Readable to get a something you can subclass. You can see an example of this in the WebTorrent project here: https://github.com/feross/webtorrent/blob/master/lib/file-stream.js You just need to return something like the FileStream object there on each call to createReadStream

tghosgor commented 9 years ago

Thank you very much for the information. I am mainly a C++ developer and not really familiar with nodejs libraries. I didn't know how much of nodejs is compliant with the browser exactly. You should add this information to readme if you feel to do so but then again web community probably have this knowledge :).

jhiesey commented 9 years ago

Thanks for the suggestion! I'll add it soon.