You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
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
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.
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.
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.
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.
/** * 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. */intvips_jpegload_fd( intdescriptor, VipsImage**out, ... )
We should try hooking this up to sharp somehow and see how it behaves.
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:
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?
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.
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
@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.
@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.
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
module creates an stream
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
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)
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.
I think any further stream integration is good, but these would be my observations
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").
accepting writable streams into webp methods etc is okay I suppose, but it still misses the point of streams a bit
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?
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.
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?
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.
Activity
lovell commentedon May 22, 2014
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.
jonathanong commentedon May 22, 2014
btw you'd want to change the
.write()command to something else for future stream support. maybetoFile()orwriteTo()jcupitt commentedon May 23, 2014
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, ... )andvips_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.
jcupitt commentedon May 23, 2014
If you're curious, the load-jpeg-from-buffer class is defined here:
https://github.com/jcupitt/libvips/blob/master/libvips/foreign/jpegload.c#L249
And it calls this set of functions to do the work:
https://github.com/jcupitt/libvips/blob/master/libvips/foreign/jpeg2vips.c#L1042
So you'd probably need to add under 500 lines of C.
Replace write() with toFile() to allow streams in the future #30
sebpiq commentedon Jun 8, 2014
👍 for streams!
davidmarkclements commentedon Jun 9, 2014
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.
jcupitt commentedon Jun 9, 2014
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.
jcupitt commentedon Jun 9, 2014
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.vCall from C like this:
We should try hooking this up to sharp somehow and see how it behaves.
jcupitt commentedon Jun 9, 2014
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?
lovell commentedon Jun 9, 2014
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_fdAPI and work out the most elegant way for sharp to expose it.davidmarkclements commentedon Jun 9, 2014
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
davidmarkclements commentedon Jun 9, 2014
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
lovell commentedon Jun 10, 2014
@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?
26 remaining items
davidmarkclements commentedon Jun 28, 2014
@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.
I also think the example could be made clearer by defining the outputStream
Stream to file:
Stream across http:
Not meaning to bikeshed here, it just occurs to me that the canonical example
of most modules I've worked with tend to be
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
Certainly not as nice but could be an okay half way point.
OR
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)
lovell commentedon Jul 30, 2014
(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
sharpconstructor can accept a Readable Stream from which it will stream the input data. A newpipemethod will accept a Writable Stream, where the output format will match input format. The existingjpeg,pngandwebpmethods 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
pipemethod, 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.davidmarkclements commentedon Jul 31, 2014
Hey @lovell
I think any further stream integration is good, but these would be my observations
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").
accepting writable streams into webp methods etc is okay I suppose, but it still misses the point of streams a bit
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?
davidmarkclements commentedon Jul 31, 2014
OR if keeping to th fluent api is too painful, create a parallel api thats for streams, e.g.
sharp.stream'lovell commentedon Jul 31, 2014
I think I've worked out how to correctly inherit from stream.Duplex with some minor API breakage.
The
jpeg,pngandwebpmethods need to become simple property setters and therefore can no longer trigger the processing pipeline without an explicit call totoFile,toBufferorpipe.Currently writing lots of tests.
davidmarkclements commentedon Jul 31, 2014
Hey @lovell sounds awesome, just to confirm, in case there's anything else that needs hooking up, the
.on('data', fn)and/orstream.Duplex.prototype.readwould also trigger the processing pipeline right?lovell commentedon Jul 31, 2014
Yes, the pipeline will be triggered lazily only when
_readis called internally to notify us that the consumer is ready. Sorry for any confusion.lovell commentedon Jul 31, 2014
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!
lovell commentedon Aug 7, 2014
I've updated the
streams2branch to not (yet) break the backwards compatibility of accepting a callback with thepng,jpegandwebpmethods. 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?
lovell commentedon Aug 18, 2014
The
streams2branch is now merged tomasterand will be included in the forthcoming v0.6.0 release.Thanks to everyone involved for all the help getting this far.
davidmarkclements commentedon Aug 18, 2014
hey many that's awesome - sorry for lack of final thoughts
lovell commentedon Aug 21, 2014
Closing this feature request - thank you everyone for all the suggestions and feedback - I look forward to hearing all about your use of Streams.
jcupitt commentedon Oct 12, 2019
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.