Skip to content

streams #30

Closed
Closed

Description

@davidmarkclements

Does the whole buffer have to load into run time memory or is it possible with the underlying C library to implementing a true streaming api, so that a file can be streamed from disk, through sharp stream to network socket or file read stream or whatever else.

ref: http://nodejs.org/api/stream.html

Neither graphicks magik, nor image magik wrappers are capable of streams - theres one module (gm I think) that has a stream api, but its faked somewhat, the module still has to load the full image into memory regardless. So a true streaming interface for sharp would be a massive usp

Activity

  1. lovell commented on May 22, 2014

    @lovell
    Owner

    Hi David, when the input image is on the filesystem, libvips only reads data as it is needed further down the processing pipeline. It's not "streaming" in the Node.js sense of the word but it does minimise memory usage.

    True streaming of compressed input data from a network socket would probably require modification to libvips. Summoning the vastly superior knowledge of @jcupitt, who may be able to offer help here.

  2. jonathanong commented on May 22, 2014

    @jonathanong
    Contributor

    btw you'd want to change the .write() command to something else for future stream support. maybe toFile() or writeTo()

  3. jcupitt commented on May 23, 2014

    @jcupitt
    Contributor

    Hi @davidmarkclements, as @lovell says, this is currently sort-of supported. When you process a large jpeg image (for example) libvips never decompresses the whole thing all at once, it just decompresses and then recompresses the area being processed as it works down the image.

    If you want to work over unix pipes or network sockets, you'd need to add a new pair of load and save operations, something like vips_foreign_load_jpeg_fd( int fd, VipsImage **out, ... ) and vips_foreign_save_jpeg_fd( VipsImage *in, int fd, ... ). The saver would be trivial, you can just reuse the file saver, but the loader would be a bit more work, you'd need to make a new libjpeg input method.

    You'd then need to expose that in sharp somehow, @lovell would be the expert there.

  4. jcupitt commented on May 23, 2014

    @jcupitt
    Contributor
  5. sebpiq commented on Jun 8, 2014

    @sebpiq

    👍 for streams!

  6. davidmarkclements commented on Jun 9, 2014

    @davidmarkclements
    Author

    sorry for delay on this guys, look I can happily get involved in the JS side of things, in terms of creating the stream interfaces and hooking them up to the bindings (although I'd have to research that, haven't worked with bindings before). But as for actually editing the C code, it's not my area and I wouldn't want to screw it up - if someone else who's strong in C wants to team up let me know and we'll get this done - I think it would be a huge win to have true stream image processing available in JS. I really don't know of anything else right now that offers that.

  7. jcupitt commented on Jun 9, 2014

    @jcupitt
    Contributor

    OK, I'll try doing jpeg as an experiment. I've not done much with sockets, I guess I just read() and don't seek().

    Would you always be reading from streams with a known type? Sniffing jpeg/png/etc. from a stream would be fiddly. I guess you'd read a mine header (something like that?) first to get the file type, or perhaps you'd be streaming from a source you controlled.

  8. jcupitt commented on Jun 9, 2014

    @jcupitt
    Contributor

    I've made an experimental branch with a quick hack to support load-jpeg-from-stream:

    https://github.com/jcupitt/libvips/tree/load-from-stream

    For example, you can do this:

    $ cat k2.jpg | vips jpegload_fd 0 x.v

    Call from C like this:

    /**
     * vips_jpegload_fd:
     * @fd: descriptor to load from
     * @out: image to write
     * @...: %NULL-terminated list of optional named arguments
     *
     * Optional arguments:
     *
     * @shrink: shrink by this much on load
     * @fail: fail on warnings
     *
     * Read a JPEG-formatted stream from @fd into a VIPS image. Exactly as
     * vips_jpegload(), but read from a descriptor. This operation does not seek()
     * and therefore can read from a network socket. 
     *
     * See also: vips_jpegload().
     *
     * Returns: 0 on success, -1 on error.
     */
    int
    vips_jpegload_fd( int descriptor, VipsImage **out, ... )

    We should try hooking this up to sharp somehow and see how it behaves.

  9. jcupitt commented on Jun 9, 2014

    @jcupitt
    Contributor

    I thought of a problem with this: it can only load a single image from a socket. If you want to send a series of images, you'll have to close and reopen the connection. I suppose this might be OK in some situations, but probably not over a slow network connection.

    The reason is buffering. As you can see, it reads as many bytes as it can each time, up to the buffer capacity:

    https://github.com/jcupitt/libvips/blob/load-from-stream/libvips/foreign/jpeg2vips.c#L1349

    So it can read the end of one image and the first part of the next. When image1 is complete, we will have unused bytes buffered which we would have to be saved somehow to be used for the next image.

    It's unclear how this could be done neatly. vips does not support image streams (reading many images from one source) and adding it would be hard, so that's probably out. We'd probably need to add some sort of intermediate buffer object which supported "unread", ie. allowed unused bytes to be pushed back into it.

    How does node tackle this sort of issue? Do they have a socket object that supports pushback?

  10. lovell commented on Jun 9, 2014

    @lovell
    Owner

    Thanks @jcupitt, Node.js' net.Socket object is our friend here.

    I'll try to make some time over the next few days to experiment with the new vips_jpegload_fd API and work out the most elegant way for sharp to expose it.

  11. davidmarkclements commented on Jun 9, 2014

    @davidmarkclements
    Author

    Using a socket would make the streams API super easier, essentially you just expose the socket directly or add methods that act as proxies to the sockets methods. But is that really the right thing to do? The normative way as I understanding is to use C bindings http://nodejs.org/api/addons.html

    And then wrap a stream interface around the exposed parts of the underlying C lib. Using a socket will add unnecessary overhead IMO

  12. davidmarkclements commented on Jun 9, 2014

    @davidmarkclements
    Author

    Sorry on mobile didn't see @jcupitts comment what I said May or may not be relevant. Btw pushback can be done when creating streams using the Stream module but don't know if that fits what we're talking about

  13. lovell commented on Jun 10, 2014

    @lovell
    Owner

    @jcupitt If libvips provided an API that accepted partial chunks of image data then that would fit with @davidmarkclements suggestion about managing the Streams in JavaScript.

    As soon as the chunk(s) that comprise the image header data have arrived then processing can begin, but a thread(s) may have to block waiting for further chunks of image data.

    This is essentially the approach taken by the Node.js wrapper around LAME, which takes advantage of the underlying library's chunk-aware methods such as lame_encode_buffer.

    Sockets and Streams both involve buffering data somewhere; something will block on a lack of data :)

    Shall we trial the Sockets method first as that currently feels like the quickest way to a proof-of-concept?

  14. 26 remaining items

  15. davidmarkclements commented on Jun 28, 2014

    @davidmarkclements
    Author

    @lovell So I'm just taking a cursory look over readme example at the moment,
    is there anything stopping you from making the return value a stream (as well as a promise)
    e.g.

    sharp('input.png').rotate(180).resize(300).sharpen().quality(90).webp().pipe(outputStream)
    

    I also think the example could be made clearer by defining the outputStream

    Stream to file:

    var toFile = require('fs').createReadStream('output.webp');
    sharp('input.png').rotate(180).resize(300).sharpen().quality(90).webp().pipe(toFile)
    

    Stream across http:

    var http = require('http');
    var path = require('path');
    http.createServer(function (req, res) {
       sharp('input.png').rotate(180).resize(300).sharpen().quality(90).webp().pipe(res);
    }).listen(8080);
    

    Not meaning to bikeshed here, it just occurs to me that the canonical example
    of most modules I've worked with tend to be

    1. module creates an stream
    2. it pipes to something else

    There's nothing wrong with the transform approach I'm just thinking for those
    getting their head around streams etc. in relation to sharp it adds extra
    conceptual complexity.

    So I realise that creating the fs readStream on behalf of the user when they do
    sharp('input.png') may complicate things internally - another option might be

    sharp({streamFrom: 'input.png'}).resize(200, 300).pipe(outputStream);
    

    Certainly not as nice but could be an okay half way point.

    OR

    sharp().stream('input.png').resize(200, 300).pipe(outputStream);
    

    But perhaps "stream" is too unclear.
    Anyway, that's just API stuff, I'll check the approach when I have bit more time (going through airports at the mo so probably not focused enough for internals anyway)

  16. lovell commented on Jul 30, 2014

    @lovell
    Owner

    (Back on this feature after a short break.)

    Thanks @davidmarkclements for the feedback. Anything that makes this module easier for people to use is a good thing. How does the following sound:

    The sharp constructor can accept a Readable Stream from which it will stream the input data. A new pipe method will accept a Writable Stream, where the output format will match input format. The existing jpeg, png and webp methods will be modified to also accept a Writable Stream.

    This means it will be possible to mix and match files, Buffer objects and Stream objects for the input and output, e.g. Stream in, file out; Buffer in, Stream out; etc.

    Unlike with the stream.Transform version, at no point will a Stream subclass be returned. The API will be Stream-like with the provision of a pipe method, but the need to support files, Buffers, Promises and Streams with a fluent API is too much for my tiny brain to also work out support for pure OO constructs right now.

  17. davidmarkclements commented on Jul 31, 2014

    @davidmarkclements
    Author

    Hey @lovell

    I think any further stream integration is good, but these would be my observations

    1. A "stream-like" route is trouble, if its stream-like people will try to use it as streams... and become confused when certaint hings don't work. If I saw docs saying stream-like but not streams it would make me think twice ("I dont know whether this is going to work for my case" vs "ah its a stream, great that'll work").

    2. accepting writable streams into webp methods etc is okay I suppose, but it still misses the point of streams a bit

    3. The main point would be, is it compatible with others streams via pipes (as thats the main emphasis on streams, much like *nix platforms)

    If I get a chance I'll take a look and see if theres an easy way to make the API return streams at the same point it returns promises?

  18. davidmarkclements commented on Jul 31, 2014

    @davidmarkclements
    Author

    OR if keeping to th fluent api is too painful, create a parallel api thats for streams, e.g. sharp.stream'

  19. lovell commented on Jul 31, 2014

    @lovell
    Owner

    I think I've worked out how to correctly inherit from stream.Duplex with some minor API breakage.

    The jpeg, png and webp methods need to become simple property setters and therefore can no longer trigger the processing pipeline without an explicit call to toFile, toBuffer or pipe.

    Currently writing lots of tests.

  20. davidmarkclements commented on Jul 31, 2014

    @davidmarkclements
    Author

    Hey @lovell sounds awesome, just to confirm, in case there's anything else that needs hooking up, the .on('data', fn) and/or stream.Duplex.prototype.read would also trigger the processing pipeline right?

  21. lovell commented on Jul 31, 2014

    @lovell
    Owner

    Yes, the pipeline will be triggered lazily only when _read is called internally to notify us that the consumer is ready. Sorry for any confusion.

  22. lovell commented on Jul 31, 2014

    @lovell
    Owner

    Commit 6c9f3de in the streams2 branch implements the native stream.Duplex object.

    The tests from line 272 onwards provide good examples of the various methods of input and output.

    Comments welcome!

  23. lovell commented on Aug 7, 2014

    @lovell
    Owner

    I've updated the streams2 branch to not (yet) break the backwards compatibility of accepting a callback with the png, jpeg and webp methods. They will still, for now, trigger the pipeline but also log a deprecation warning that this feature will be removed in the next major version.

    Any final thoughts from @sebpiq, @jonathanong and @davidmarkclements before this hits master?

  24. lovell commented on Aug 18, 2014

    @lovell
    Owner

    The streams2 branch is now merged to master and will be included in the forthcoming v0.6.0 release.

    Thanks to everyone involved for all the help getting this far.

  25. davidmarkclements commented on Aug 18, 2014

    @davidmarkclements
    Author

    hey many that's awesome - sorry for lack of final thoughts

  26. lovell commented on Aug 21, 2014

    @lovell
    Owner

    Closing this feature request - thank you everyone for all the suggestions and feedback - I look forward to hearing all about your use of Streams.

  27. jcupitt commented on Oct 12, 2019

    @jcupitt
    Contributor

    Hello, I've spent a few days implementing experimental support for true streaming:

    libvips/libvips#1443

    It seems to work. Any testing or feedback very welcome.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions