1 /* vips image class
2  *
3  * 4/2/11
4  * 	- hacked up from various places
5  * 6/6/13
6  * 	- vips_image_write() didn't ref non-partial sources
7  * 18/4/15
8  * 	- add vips_image_copy_memory()
9  * 25/11/15
10  * 	- add vips_image_new_from_memory_copy()
11  * 10/6/16
12  * 	- vips_image_write() does not ref input for non-partial images
13  * 29/10/16
14  * 	- add vips_image_hasalpha()
15  * 11/10/17
16  * 	- more severing for vips_image_write()
17  * 3/4/18
18  * 	- better rules for hasalpha
19  * 9/10/18
20  * 	- fix up vips_image_dump(), it was still using ints not enums
21  * 10/12/19
22  * 	- add vips_image_new_from_source() / vips_image_write_to_target()
23  */
24 
25 /*
26 
27     This file is part of VIPS.
28 
29     VIPS is free software; you can redistribute it and/or modify
30     it under the terms of the GNU Lesser General Public License as published by
31     the Free Software Foundation; either version 2 of the License, or
32     (at your option) any later version.
33 
34     This program is distributed in the hope that it will be useful,
35     but WITHOUT ANY WARRANTY; without even the implied warranty of
36     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
37     GNU Lesser General Public License for more details.
38 
39     You should have received a copy of the GNU Lesser General Public License
40     along with this program; if not, write to the Free Software
41     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
42     02110-1301  USA
43 
44  */
45 
46 /*
47 
48     These files are distributed with VIPS - http://www.vips.ecs.soton.ac.uk
49 
50  */
51 
52 /*
53 #define VIPS_DEBUG
54  */
55 
56 #ifdef HAVE_CONFIG_H
57 #include <config.h>
58 #endif /*HAVE_CONFIG_H*/
59 #include <vips/intl.h>
60 
61 #include <stdio.h>
62 #include <stdlib.h>
63 #include <string.h>
64 #ifdef HAVE_UNISTD_H
65 #include <unistd.h>
66 #endif /*HAVE_UNISTD_H*/
67 #include <ctype.h>
68 
69 #include <vips/vips.h>
70 #include <vips/internal.h>
71 #include <vips/debug.h>
72 
73 /**
74  * SECTION: image
75  * @short_description: the VIPS image class
76  * @stability: Stable
77  * @see_also: <link linkend="libvips-header">header</link>
78  * <link linkend="VipsRegion">VipsRegion</link>
79  * <link linkend="libvips-generate">generate</link>
80  * <link linkend="VipsOperation">VipsOperation</link>
81  * @include: vips/vips.h
82  *
83  * The image class and associated types and macros.
84  *
85  * Images can be created from formatted files on disc, from C-style arrays on
86  * disc, from formatted areas of memory, or from C-style arrays in memory. See
87  * vips_image_new_from_file() and friends.
88  * Creating an image is fast. VIPS reads just enough of
89  * the image to be able to get the various properties, such as width in
90  * pixels. It delays reading any pixels until they are really needed.
91  *
92  * Once you have an image, you can get properties from it in the usual way.
93  * You can use projection functions, like vips_image_get_width() or
94  * g_object_get(), to get %GObject properties.
95  *
96  * VIPS images are three-dimensional arrays, the dimensions being width,
97  * height and bands. Each dimension can be up to 2 ** 31 pixels (or band
98  * elements). An image has a format, meaning the machine number type used
99  * to represent each value. VIPS supports 10 formats, from 8-bit unsigned
100  * integer up to 128-bit double complex, see vips_image_get_format().
101  *
102  * In VIPS, images are uninterpreted arrays, meaning that from the point of
103  * view of most operations, they are just large collections of numbers.
104  * There's no difference between an RGBA (RGB with alpha) image and a CMYK
105  * image, for example, they are both just four-band images. It's up to the
106  * user of the library to pass the right sort of image to each operation.
107  *
108  * To take an example, VIPS has vips_Lab2XYZ(), an operation to transform
109  * an image from CIE LAB colour space to CIE XYZ space. It assumes the
110  * first three bands represent pixels in LAB colour space and returns an
111  * image where the first three bands are transformed to XYZ and any
112  * remaining bands are just copied. Pass it a RGB image by mistake and
113  * you'll just get nonsense.
114  *
115  * VIPS has a feature to help (a little) with this: it sets a
116  * #VipsInterpretation hint for each image (see
117  * vips_image_get_interpretation()); a hint which says how pixels should
118  * be interpreted. For example, vips_Lab2XYZ() will set the
119  * interpretation of the output image to #VIPS_INTERPRETATION_XYZ. A
120  * few utility operations will also use interpretation as a guide. For
121  * example, you can give vips_colourspace() an input image and a desired
122  * colourspace and it will use the input's interpretation hint to apply
123  * the best sequence of colourspace transforms to get to the desired space.
124  *
125  * Use things like vips_invert() to manipulate your images. When you are done,
126  * you can write images to disc files (with vips_image_write_to_file()),
127  * to formatted memory buffers (with vips_image_write_to_buffer()) and to
128  * C-style memory arrays (with vips_image_write_to_memory().
129  *
130  * You can also write images to other images. Create, for example, a temporary
131  * disc image with vips_image_new_temp_file(), then write your image to that
132  * with vips_image_write(). You can create several other types of image and
133  * write to them, see vips_image_new_memory(), for example.
134  *
135  * See <link linkend="VipsOperation">operation</link> for an introduction to
136  * running operations on images, see <link
137  * linkend="libvips-header">header</link> for getting and setting image
138  * metadata. See <link linkend="VipsObject">object</link> for a discussion of
139  * the lower levels.
140  */
141 
142 /**
143  * VIPS_MAGIC_INTEL:
144  *
145  * The first four bytes of a VIPS file in Intel byte ordering.
146  */
147 
148 /**
149  * VIPS_MAGIC_SPARC:
150  *
151  * The first four bytes of a VIPS file in SPARC byte ordering.
152  */
153 
154 /**
155  * VipsAccess:
156  * @VIPS_ACCESS_RANDOM: can read anywhere
157  * @VIPS_ACCESS_SEQUENTIAL: top-to-bottom reading only, but with a small buffer
158  *
159  * The type of access an operation has to supply. See vips_tilecache()
160  * and #VipsForeign.
161  *
162  * @VIPS_ACCESS_RANDOM means requests can come in any order.
163  *
164  * @VIPS_ACCESS_SEQUENTIAL means requests will be top-to-bottom, but with some
165  * amount of buffering behind the read point for small non-local accesses.
166  */
167 
168 /**
169  * VipsDemandStyle:
170  * @VIPS_DEMAND_STYLE_SMALLTILE: demand in small (typically 64x64 pixel) tiles
171  * @VIPS_DEMAND_STYLE_FATSTRIP: demand in fat (typically 10 pixel high) strips
172  * @VIPS_DEMAND_STYLE_THINSTRIP: demand in thin (typically 1 pixel high) strips
173  * @VIPS_DEMAND_STYLE_ANY: demand geometry does not matter
174  *
175  * See vips_image_pipelinev(). Operations can hint to the VIPS image IO
176  * system about the kind of demand geometry they prefer.
177  *
178  * These demand styles are given below in order of increasing
179  * restrictiveness.  When demanding output from a pipeline,
180  * vips_image_generate()
181  * will use the most restrictive of the styles requested by the operations
182  * in the pipeline.
183  *
184  * #VIPS_DEMAND_STYLE_THINSTRIP --- This operation would like to output strips
185  * the width of the image and a few pels high. This is option suitable for
186  * point-to-point operations, such as those in the arithmetic package.
187  *
188  * This option is only efficient for cases where each output pel depends
189  * upon the pel in the corresponding position in the input image.
190  *
191  * #VIPS_DEMAND_STYLE_FATSTRIP --- This operation would like to output strips
192  * the width of the image and as high as possible. This option is suitable
193  * for area operations which do not violently transform coordinates, such
194  * as vips_conv().
195  *
196  * #VIPS_DEMAND_STYLE_SMALLTILE --- This is the most general demand format.
197  * Output is demanded in small (around 100x100 pel) sections. This style works
198  * reasonably efficiently, even for bizzare operations like 45 degree rotate.
199  *
200  * #VIPS_DEMAND_STYLE_ANY --- This image is not being demand-read from a disc
201  * file (even indirectly) so any demand style is OK. It's used for things like
202  * vips_black() where the pixels are calculated.
203  *
204  * See also: vips_image_pipelinev().
205  */
206 
207 /**
208  * VipsInterpretation:
209  * @VIPS_INTERPRETATION_MULTIBAND: generic many-band image
210  * @VIPS_INTERPRETATION_B_W: some kind of single-band image
211  * @VIPS_INTERPRETATION_HISTOGRAM: a 1D image, eg. histogram or lookup table
212  * @VIPS_INTERPRETATION_FOURIER: image is in fourier space
213  * @VIPS_INTERPRETATION_XYZ: the first three bands are CIE XYZ
214  * @VIPS_INTERPRETATION_LAB: pixels are in CIE Lab space
215  * @VIPS_INTERPRETATION_CMYK: the first four bands are in CMYK space
216  * @VIPS_INTERPRETATION_LABQ: implies #VIPS_CODING_LABQ
217  * @VIPS_INTERPRETATION_RGB: generic RGB space
218  * @VIPS_INTERPRETATION_CMC: a uniform colourspace based on CMC(1:1)
219  * @VIPS_INTERPRETATION_LCH: pixels are in CIE LCh space
220  * @VIPS_INTERPRETATION_LABS: CIE LAB coded as three signed 16-bit values
221  * @VIPS_INTERPRETATION_sRGB: pixels are sRGB
222  * @VIPS_INTERPRETATION_HSV: pixels are HSV
223  * @VIPS_INTERPRETATION_scRGB: pixels are scRGB
224  * @VIPS_INTERPRETATION_YXY: pixels are CIE Yxy
225  * @VIPS_INTERPRETATION_RGB16: generic 16-bit RGB
226  * @VIPS_INTERPRETATION_GREY16: generic 16-bit mono
227  * @VIPS_INTERPRETATION_MATRIX: a matrix
228  *
229  * How the values in an image should be interpreted. For example, a
230  * three-band float image of type #VIPS_INTERPRETATION_LAB should have its
231  * pixels interpreted as coordinates in CIE Lab space.
232  *
233  * RGB and sRGB are treated in the same way. Use the colourspace functions if
234  * you want some other behaviour.
235  *
236  * The gaps in numbering are historical and must be maintained. Allocate
237  * new numbers from the end.
238  */
239 
240 /**
241  * VipsBandFormat:
242  * @VIPS_FORMAT_NOTSET: invalid setting
243  * @VIPS_FORMAT_UCHAR: unsigned char format
244  * @VIPS_FORMAT_CHAR: char format
245  * @VIPS_FORMAT_USHORT: unsigned short format
246  * @VIPS_FORMAT_SHORT: short format
247  * @VIPS_FORMAT_UINT: unsigned int format
248  * @VIPS_FORMAT_INT: int format
249  * @VIPS_FORMAT_FLOAT: float format
250  * @VIPS_FORMAT_COMPLEX: complex (two floats) format
251  * @VIPS_FORMAT_DOUBLE: double float format
252  * @VIPS_FORMAT_DPCOMPLEX: double complex (two double) format
253  *
254  * The format used for each band element.
255  *
256  * Each corresponds to a native C type for the current machine. For example,
257  * #VIPS_FORMAT_USHORT is <type>unsigned short</type>.
258  */
259 
260 /**
261  * VipsCoding:
262  * @VIPS_CODING_NONE: pixels are not coded
263  * @VIPS_CODING_LABQ: pixels encode 3 float CIELAB values as 4 uchar
264  * @VIPS_CODING_RAD: pixels encode 3 float RGB as 4 uchar (Radiance coding)
265  *
266  * How pixels are coded.
267  *
268  * Normally, pixels are uncoded and can be manipulated as you would expect.
269  * However some file formats code pixels for compression, and sometimes it's
270  * useful to be able to manipulate images in the coded format.
271  *
272  * The gaps in the numbering are historical and must be maintained. Allocate
273  * new numbers from the end.
274  */
275 
276 /**
277  * VipsProgress:
278  * @run: Time we have been running
279  * @eta: Estimated seconds of computation left
280  * @tpels: Number of pels we expect to calculate
281  * @npels: Number of pels calculated so far
282  * @percent: Percent complete
283  * @start: Start time
284  *
285  * A structure available to eval callbacks giving information on evaluation
286  * progress. See #VipsImage::eval.
287  */
288 
289 /**
290  * VipsImage:
291  *
292  * An image. These can represent an image on disc, a memory buffer, an image
293  * in the process of being written to disc or a partially evaluated image
294  * in memory.
295  */
296 
297 /**
298  * VIPS_IMAGE_SIZEOF_ELEMENT:
299  * @I: a #VipsImage
300  *
301  * Returns: sizeof() a band element.
302  */
303 
304 /**
305  * VIPS_IMAGE_SIZEOF_PEL:
306  * @I: a #VipsImage
307  *
308  * Returns: sizeof() a pixel.
309  */
310 
311 /**
312  * VIPS_IMAGE_SIZEOF_LINE:
313  * @I: a #VipsImage
314  *
315  * Returns: sizeof() a scanline of pixels.
316  */
317 
318 /**
319  * VIPS_IMAGE_N_ELEMENTS:
320  * @I: a #VipsImage
321  *
322  * Returns: The number of band elements in a scanline.
323  */
324 
325 /**
326  * VIPS_IMAGE_N_PELS:
327  * @I: a #VipsImage
328  *
329  * Returns: The number of pels in an image. A 64-bit unsigned int.
330  */
331 
332 /**
333  * VIPS_IMAGE_ADDR:
334  * @I: a #VipsImage
335  * @X: x coordinate
336  * @Y: y coordinate
337  *
338  * This macro returns a pointer to a pixel in an image, cast to a #VipsPel *.
339  * It only works for
340  * images which are fully available in memory, so memory buffers and small
341  * mapped images only.
342  *
343  * If VIPS_DEBUG is defined, you get a version that checks bounds for you.
344  *
345  * See also: vips_image_wio_input(), vips_image_inplace(), VIPS_REGION_ADDR().
346  *
347  * Returns: The address of pixel (@X,@Y) in @I.
348  */
349 
350 /**
351  * VIPS_MATRIX:
352  * @I: a #VipsImage
353  * @X: x coordinate
354  * @Y: y coordinate
355  *
356  * This macro returns a pointer to a pixel in an image, cast to a double*. The
357  * image must have a single band, be #VIPS_FORMAT_DOUBLE and be
358  * fully available in memory, so memory buffers and small
359  * mapped images only.
360  *
361  * If VIPS_DEBUG is defined, you get a version that checks bounds and image
362  * type for you.
363  *
364  * See also: vips_image_wio_input(), vips_image_inplace(), vips_check_matrix().
365  *
366  * Returns: The address of pixel (@X,@Y) in @I.
367  */
368 
369 /* Our signals.
370  */
371 enum {
372 	SIG_PREEVAL,
373 	SIG_EVAL,
374 	SIG_POSTEVAL,
375 	SIG_WRITTEN,
376 	SIG_INVALIDATE,
377 	SIG_MINIMISE,
378 	SIG_LAST
379 };
380 
381 /* Progress feedback. Only really useful for testing, tbh.
382  */
383 int vips__progress = 0;
384 
385 /* A string giving the image size (in bytes of uncompressed image) above which
386  * we decompress to disc on open.  Can be eg. "12m" for 12 megabytes.
387  */
388 char *vips__disc_threshold = NULL;
389 
390 /* Minimise needs a lock.
391  */
392 static GMutex *vips__minimise_lock = NULL;
393 
394 static guint vips_image_signals[SIG_LAST] = { 0 };
395 
396 G_DEFINE_TYPE( VipsImage, vips_image, VIPS_TYPE_OBJECT );
397 
398 /**
399  * vips_progress_set:
400  * @progress: %TRUE to enable progress messages
401  *
402  * If set, vips will print messages about the progress of computation to
403  * stdout. This can also be enabled with the --vips-progress option, or by
404  * setting the environment variable VIPS_PROGRESS.
405  */
406 void
vips_progress_set(gboolean progress)407 vips_progress_set( gboolean progress )
408 {
409 	vips__progress = progress;
410 }
411 
412 static void
vips_image_delete(VipsImage * image)413 vips_image_delete( VipsImage *image )
414 {
415 	if( image->delete_on_close ) {
416 		g_assert( image->delete_on_close_filename );
417 
418 		VIPS_DEBUG_MSG( "vips_image_delete: removing temp %s\n",
419 				image->delete_on_close_filename );
420 		g_unlink( image->delete_on_close_filename );
421 		VIPS_FREE( image->delete_on_close_filename );
422 		image->delete_on_close = FALSE;
423 	}
424 }
425 
426 static void
vips_image_finalize(GObject * gobject)427 vips_image_finalize( GObject *gobject )
428 {
429 	VipsImage *image = VIPS_IMAGE( gobject );
430 
431 	VIPS_DEBUG_MSG( "vips_image_finalize: %p\n", gobject );
432 
433 	/* Should be no regions defined on the image, since they all hold a
434 	 * ref to their host image.
435 	 */
436 	g_assert( !image->regions );
437 
438 	/* Therefore there should be no windows.
439 	 */
440 	g_assert( !image->windows );
441 
442 	/* Junk generate functions.
443 	 */
444 	image->start_fn = NULL;
445 	image->generate_fn = NULL;
446 	image->stop_fn = NULL;
447 	image->client1 = NULL;
448 	image->client2 = NULL;
449 
450 	/* No more upstream/downstream links.
451 	 */
452 	vips__link_break_all( image );
453 
454 	if( image->time ) {
455 		VIPS_FREEF( g_timer_destroy, image->time->start );
456 		VIPS_FREE( image->time );
457 	}
458 
459 	/* Free attached memory.
460 	 */
461 	if( image->data ) {
462 		if( image->dtype == VIPS_IMAGE_SETBUF ) {
463 			VIPS_DEBUG_MSG( "vips_image_finalize: "
464 				"freeing buffer\n" );
465 			vips_tracked_free( image->data );
466 			image->dtype = VIPS_IMAGE_NONE;
467 		}
468 
469 		image->data = NULL;
470 	}
471 
472 	/* Delete associated files.
473 	 */
474 	vips_image_delete( image );
475 
476 	VIPS_FREEF( vips_g_mutex_free, image->sslock );
477 
478 	VIPS_FREE( image->Hist );
479 	VIPS_FREEF( vips__gslist_gvalue_free, image->history_list );
480 	vips__meta_destroy( image );
481 
482 	G_OBJECT_CLASS( vips_image_parent_class )->finalize( gobject );
483 }
484 
485 static void
vips_image_dispose(GObject * gobject)486 vips_image_dispose( GObject *gobject )
487 {
488 	VipsImage *image = VIPS_IMAGE( gobject );
489 
490 	VIPS_DEBUG_MSG( "vips_image_dispose: %p\n", gobject );
491 
492 #ifdef DEBUG_LEAK
493 {
494 	VipsImagePixels *pixels = g_object_get_qdata( G_OBJECT( image ),
495 		vips__image_pixels_quark );
496 
497 	if( pixels &&
498 		pixels->tpels ) {
499 		int compute_percent = 100.0 * pixels->npels / pixels->tpels;
500 
501 		if( compute_percent > 100 )
502 			printf( "vips_image_dispose: %s %s computed %d%%\n",
503 				image->filename,
504 				pixels->nickname,
505 				compute_percent );
506 	}
507 }
508 #endif /*DEBUG_LEAK*/
509 
510 	vips_object_preclose( VIPS_OBJECT( gobject ) );
511 
512 	/* We have to junk the fd in dispose, since we run this for rewind and
513 	 * we must close and reopen the file when we switch from write to
514 	 * read.
515 	 */
516 
517 	/* Any file mapping?
518 	 */
519 	if( image->baseaddr ) {
520 		/* MMAP file.
521 		 */
522 		VIPS_DEBUG_MSG( "vips_image_dispose: unmapping file\n" );
523 
524 		vips__munmap( image->baseaddr, image->length );
525 		image->baseaddr = NULL;
526 		image->length = 0;
527 
528 		/* This must have been a pointer to the mmap region, rather
529 		 * than a setbuf.
530 		 */
531 		image->data = NULL;
532 	}
533 
534 	/* Is there a file descriptor?
535 	 */
536 	if( image->fd != -1 ) {
537 		VIPS_DEBUG_MSG( "vips_image_dispose: closing output file\n" );
538 
539 		if( vips_tracked_close( image->fd ) == -1 )
540 			vips_error( "VipsImage",
541 				"%s", _( "unable to close fd" ) );
542 		image->fd = -1;
543 	}
544 
545 	G_OBJECT_CLASS( vips_image_parent_class )->dispose( gobject );
546 }
547 
548 static VipsObject *
vips_image_new_from_file_object(const char * string)549 vips_image_new_from_file_object( const char *string )
550 {
551 	VipsImage *image;
552 
553 	vips_check_init();
554 
555 	/* We mustn't _build() the object here, so we can't just call
556 	 * vips_image_new_from_file().
557 	 */
558 	image = VIPS_IMAGE( g_object_new( VIPS_TYPE_IMAGE, NULL ) );
559 	g_object_set( image,
560 		"filename", string,
561 		"mode", "r",
562 		NULL );
563 
564 	return( VIPS_OBJECT( image ) );
565 }
566 
567 static void
vips_image_to_string(VipsObject * object,VipsBuf * buf)568 vips_image_to_string( VipsObject *object, VipsBuf *buf )
569 {
570 	VipsImage *image = VIPS_IMAGE( object );
571 
572 	vips_buf_appends( buf, image->filename );
573 }
574 
575 static int
vips_image_write_object(VipsObject * object,const char * string)576 vips_image_write_object( VipsObject *object, const char *string )
577 {
578 	return( vips_image_write_to_file( VIPS_IMAGE( object ), string,
579 		NULL ) );
580 }
581 
582 static void *
print_field_fn(VipsImage * image,const char * field,GValue * value,void * a)583 print_field_fn( VipsImage *image, const char *field, GValue *value, void *a )
584 {
585 	VipsBuf *buf = (VipsBuf *) a;
586 
587 	vips_buf_appendf( buf, "%s: ", field );
588 	vips_buf_appendgv( buf, value );
589 	vips_buf_appendf( buf, "\n" );
590 
591 	return( NULL );
592 }
593 
594 static void
vips_image_dump(VipsObject * object,VipsBuf * buf)595 vips_image_dump( VipsObject *object, VipsBuf *buf )
596 {
597 	VipsImage *image = VIPS_IMAGE( object );
598 
599 	vips_buf_appendf( buf,
600 		ngettext(
601 			"%dx%d %s, %d band, %s",
602 			"%dx%d %s, %d bands, %s",
603 			vips_image_get_bands( image ) ),
604 		vips_image_get_width( image ),
605 		vips_image_get_height( image ),
606 		vips_enum_nick( VIPS_TYPE_BAND_FORMAT,
607 			vips_image_get_format( image ) ),
608 		vips_image_get_bands( image ),
609 		vips_enum_nick( VIPS_TYPE_INTERPRETATION,
610 			vips_image_get_interpretation( image ) ) );
611 
612 	vips_buf_appendf( buf, ", %s",
613 		vips_enum_nick( VIPS_TYPE_IMAGE_TYPE, image->dtype ) );
614 
615 	VIPS_OBJECT_CLASS( vips_image_parent_class )->dump( object, buf );
616 
617 	vips_buf_appendf( buf, "\n" );
618 
619 	(void) vips_image_map( image, print_field_fn, (void *) buf );
620 
621 	vips_buf_appendf( buf, "Hist: %s", vips_image_get_history( image ) );
622 }
623 
624 static void
vips_image_summary(VipsObject * object,VipsBuf * buf)625 vips_image_summary( VipsObject *object, VipsBuf *buf )
626 {
627 	VipsImage *image = VIPS_IMAGE( object );
628 	const char *p;
629 
630 	vips_buf_appendf( buf, "%dx%d",
631 		vips_image_get_width( image ), vips_image_get_height( image ) );
632 	if( vips_image_get_coding( image ) == VIPS_CODING_NONE ) {
633 		vips_buf_appendf( buf,
634 			ngettext(
635 				" %s, %d band, %s",
636 				" %s, %d bands, %s",
637 				vips_image_get_bands( image ) ),
638 			vips_enum_nick( VIPS_TYPE_BAND_FORMAT,
639 				vips_image_get_format( image ) ),
640 			vips_image_get_bands( image ),
641 			vips_enum_nick( VIPS_TYPE_INTERPRETATION,
642 				vips_image_get_interpretation( image ) ) );
643 	}
644 	else {
645 		vips_buf_appendf( buf, ", %s",
646 			vips_enum_nick( VIPS_TYPE_CODING,
647 				vips_image_get_coding( image ) ) );
648 	}
649 
650 	if( vips_image_get_typeof( image, VIPS_META_LOADER ) &&
651 		!vips_image_get_string( image, VIPS_META_LOADER, &p ) )
652 		vips_buf_appendf( buf, ", %s", p );
653 
654 	VIPS_OBJECT_CLASS( vips_image_parent_class )->summary( object, buf );
655 }
656 
657 static void *
vips_image_sanity_upstream(VipsImage * up,VipsImage * down,void * b)658 vips_image_sanity_upstream( VipsImage *up, VipsImage *down, void *b )
659 {
660 	if( !g_slist_find( up->downstream, down ) ||
661 		!g_slist_find( down->upstream, up ) )
662 		return( up );
663 
664 	return( NULL );
665 }
666 
667 static void *
vips_image_sanity_downstream(VipsImage * down,VipsImage * up,void * b)668 vips_image_sanity_downstream( VipsImage *down, VipsImage *up, void *b )
669 {
670 	return( vips_image_sanity_upstream( up, down, b ) );
671 }
672 
673 static void
vips_image_sanity(VipsObject * object,VipsBuf * buf)674 vips_image_sanity( VipsObject *object, VipsBuf *buf )
675 {
676 	VipsImage *image = VIPS_IMAGE( object );
677 
678 	/* All 0 means im has been inited but never used.
679 	 */
680 	if( image->Xsize != 0 ||
681 		image->Ysize != 0 ||
682 		image->Bands != 0 ) {
683 		if( image->Xsize <= 0 ||
684 			image->Ysize <= 0 ||
685 			image->Bands <= 0 )
686 			vips_buf_appends( buf, "bad dimensions\n" );
687 		if( image->BandFmt < -1 ||
688 			image->BandFmt > VIPS_FORMAT_DPCOMPLEX ||
689 			(image->Coding != -1 &&
690 				image->Coding != VIPS_CODING_NONE &&
691 				image->Coding != VIPS_CODING_LABQ &&
692 				image->Coding != VIPS_CODING_RAD) ||
693 			image->Type >= VIPS_INTERPRETATION_LAST ||
694 			image->dtype > VIPS_IMAGE_PARTIAL ||
695 			image->dhint > VIPS_DEMAND_STYLE_ANY )
696 			vips_buf_appends( buf, "bad enum\n" );
697 		if( image->Xres < 0 ||
698 			image->Yres < 0 )
699 			vips_buf_appends( buf, "bad resolution\n" );
700 	}
701 
702 	/* Must lock around inter-image links.
703 	 */
704 	g_mutex_lock( vips__global_lock );
705 
706 	if( vips_slist_map2( image->upstream,
707 		(VipsSListMap2Fn) vips_image_sanity_upstream, image, NULL ) )
708 		vips_buf_appends( buf, "upstream broken\n" );
709 	if( vips_slist_map2( image->downstream,
710 		(VipsSListMap2Fn) vips_image_sanity_downstream, image, NULL ) )
711 		vips_buf_appends( buf, "downstream broken\n" );
712 
713 	g_mutex_unlock( vips__global_lock );
714 
715 	VIPS_OBJECT_CLASS( vips_image_parent_class )->sanity( object, buf );
716 }
717 
718 static void
vips_image_rewind(VipsObject * object)719 vips_image_rewind( VipsObject *object )
720 {
721 	VipsImage *image = VIPS_IMAGE( object );
722 	char *filename;
723 	char *mode;
724 
725 	/* This triggers a dispose. Copy filename/mode across the dispose.
726 	 */
727 	filename = g_strdup( vips_image_get_filename( image ) );
728 	mode = g_strdup( vips_image_get_mode( image ) );
729 
730 	VIPS_OBJECT_CLASS( vips_image_parent_class )->rewind( object );
731 
732 	g_assert( image->filename == NULL );
733 	g_assert( image->mode == NULL );
734 
735 	image->filename = filename;
736 	image->mode = mode;
737 }
738 
739 /* Delayed save.
740  */
741 
742 /* From "written" callback: save to image->filename using VipsForeign.
743  */
744 static void
vips_image_save_cb(VipsImage * image,int * result,void * data)745 vips_image_save_cb( VipsImage *image, int *result, void *data )
746 {
747 	if( vips_foreign_save( image, image->filename, NULL ) )
748 		*result = -1;
749 }
750 
751 /* Progress feedback.
752  */
753 
754 static void
vips_image_preeval_cb(VipsImage * image,VipsProgress * progress,int * last)755 vips_image_preeval_cb( VipsImage *image, VipsProgress *progress, int *last )
756 {
757 	int tile_width;
758 	int tile_height;
759 	int n_lines;
760 
761 	*last = -1;
762 
763 	vips_get_tile_size( image,
764 		&tile_width, &tile_height, &n_lines );
765 	printf( _( "%s %s: %d x %d pixels, %d threads, %d x %d tiles, "
766 		"%d lines in buffer" ),
767 		vips_get_prgname(), image->filename,
768 		image->Xsize, image->Ysize,
769 		vips_concurrency_get(),
770 		tile_width, tile_height, n_lines );
771 	printf( "\n" );
772 }
773 
774 static void
vips_image_eval_cb(VipsImage * image,VipsProgress * progress,int * last)775 vips_image_eval_cb( VipsImage *image, VipsProgress *progress, int *last )
776 {
777 	if( progress->percent != *last ) {
778 		printf( _( "%s %s: %d%% complete" ),
779 			vips_get_prgname(), image->filename,
780 			progress->percent );
781 		printf( "\r" );
782 		fflush( stdout );
783 
784 		*last = progress->percent;
785 
786 		/* Needs DEBUG in region.c
787 		vips_region_dump_all();
788 		 */
789 	}
790 }
791 
792 static void
vips_image_posteval_cb(VipsImage * image,VipsProgress * progress,void * data)793 vips_image_posteval_cb( VipsImage *image, VipsProgress *progress, void *data )
794 {
795 	/* Spaces at end help to erase the %complete message we overwrite.
796 	 */
797 	printf( _( "%s %s: done in %.3gs          \n" ),
798 		vips_get_prgname(), image->filename,
799 		g_timer_elapsed( progress->start, NULL ) );
800 }
801 
802 /* Attach progress feedback, if required.
803  */
804 static void
vips_image_add_progress(VipsImage * image)805 vips_image_add_progress( VipsImage *image )
806 {
807 	if( vips__progress ||
808 		g_getenv( "VIPS_PROGRESS" )
809 #if ENABLE_DEPRECATED
810 		|| g_getenv( "IM_PROGRESS" )
811 #endif
812 		) {
813 
814 		/* Keep the %complete we displayed last time here.
815 		 */
816 		int *last = VIPS_NEW( image, int );
817 
818 		g_signal_connect( image, "preeval",
819 			G_CALLBACK( vips_image_preeval_cb ), last );
820 		g_signal_connect( image, "eval",
821 			G_CALLBACK( vips_image_eval_cb ), last );
822 		g_signal_connect( image, "posteval",
823 			G_CALLBACK( vips_image_posteval_cb ), NULL );
824 
825 		vips_image_set_progress( image, TRUE );
826 	}
827 }
828 
829 /* We have to do a lot of work in _build() so we can work with the stuff in
830  * /deprecated to support the vips7 API. We could get rid of most of this
831  * stuff if we were vips8-only.
832  */
833 
834 static int
vips_image_build(VipsObject * object)835 vips_image_build( VipsObject *object )
836 {
837 	VipsImage *image = VIPS_IMAGE( object );
838 	const char *filename = image->filename;
839 	const char *mode = image->mode;
840 
841 	guint32 magic;
842 	guint64 sizeof_image;
843 
844 	VIPS_DEBUG_MSG( "vips_image_build: %p\n", image );
845 
846 	if( VIPS_OBJECT_CLASS( vips_image_parent_class )->build( object ) )
847 		return( -1 );
848 
849 	/* Parse the mode string.
850 	 */
851 	switch( mode[0] ) {
852         case 'v':
853 		/* Used by 'r' for native open of vips, see below. Also by
854 		 * vips_image_rewind_output().
855 		 */
856 		if( vips_image_open_input( image ) )
857 			return( -1 );
858 
859 		break;
860 
861         case 'r':
862 		if( (magic = vips__file_magic( filename )) ) {
863 			/* We may need to byteswap.
864 			 */
865 			if( GUINT_FROM_BE( magic ) == image->magic ) {
866 				/* Native open.
867 				 */
868 				if( vips_image_open_input( image ) )
869 					return( -1 );
870 			}
871 			else {
872 				VipsImage *t;
873 				VipsImage *t2;
874 
875 				/* Open the image in t, then byteswap to this
876 				 * image.
877 				 */
878 				if( !(t = vips_image_new_mode( filename,
879 					"v" )) )
880 					return( -1 );
881 
882 				if( vips_byteswap( t, &t2, NULL ) ) {
883 					g_object_unref( t );
884 					return( -1 );
885 				}
886 				g_object_unref( t );
887 
888 				image->dtype = VIPS_IMAGE_PARTIAL;
889 				if( vips_image_write( t2, image ) ) {
890 					g_object_unref( t2 );
891 					return( -1 );
892 				}
893 				g_object_unref( t2 );
894 			}
895 		}
896 		else {
897 			VipsImage *t;
898 
899 			if( mode[1] == 's' ) {
900 				if( vips_foreign_load( filename, &t,
901 					"access", VIPS_ACCESS_SEQUENTIAL,
902 					NULL ) )
903 					return( -1 );
904 			}
905 			else {
906 				if( vips_foreign_load( filename, &t, NULL ) )
907 					return( -1 );
908 			}
909 
910 			image->dtype = VIPS_IMAGE_PARTIAL;
911 			if( vips_image_write( t, image ) ) {
912 				g_object_unref( t );
913 				return( -1 );
914 			}
915 			g_object_unref( t );
916 		}
917 
918         	break;
919 
920 	case 'w':
921 {
922 		const char *file_op;
923 
924 		/* Make sure the vips saver is there ... strange things will
925 		 * happen if this type is renamed or removed.
926 		 */
927 		g_assert( g_type_from_name( "VipsForeignSaveVips" ) );
928 
929 		if( !(file_op = vips_foreign_find_save( filename )) )
930 			return( -1 );
931 
932 		/* If this is the vips saver, just save directly ourselves.
933 		 * Otherwise save with VipsForeign when the image has been
934 		 * written to.
935 		 */
936 		if( vips_isprefix( "VipsForeignSaveVips", file_op ) )
937 			image->dtype = VIPS_IMAGE_OPENOUT;
938 		else {
939 			image->dtype = VIPS_IMAGE_PARTIAL;
940 			g_signal_connect( image, "written",
941 				G_CALLBACK( vips_image_save_cb ),
942 				NULL );
943 		}
944 }
945         	break;
946 
947         case 't':
948 		image->dtype = VIPS_IMAGE_SETBUF;
949 		image->dhint = VIPS_DEMAND_STYLE_ANY;
950                 break;
951 
952         case 'p':
953 		image->dtype = VIPS_IMAGE_PARTIAL;
954                 break;
955 
956 	case 'a':
957 		if( (image->fd = vips__open_image_read( filename )) == -1 )
958 			return( -1 );
959 		image->dtype = VIPS_IMAGE_OPENIN;
960 		image->dhint = VIPS_DEMAND_STYLE_THINSTRIP;
961 
962 		if( image->Bands == 1 )
963 			image->Type = VIPS_INTERPRETATION_B_W;
964 		else if( image->Bands == 3 )
965 			image->Type = VIPS_INTERPRETATION_sRGB;
966 		else
967 			image->Type = VIPS_INTERPRETATION_MULTIBAND;
968 
969 		/* Read the real file length and check against what we think
970 		 * the size should be.
971 		 */
972 		if( (image->file_length = vips_file_length( image->fd )) == -1 )
973 			return( -1 );
974 
975 		/* Very common, so a special message.
976 		 */
977 		sizeof_image = VIPS_IMAGE_SIZEOF_IMAGE( image ) +
978 			image->sizeof_header;
979 		if( image->file_length < sizeof_image ) {
980 			vips_error( "VipsImage",
981 				_( "unable to open \"%s\", file too short" ),
982 				image->filename );
983 			return( -1 );
984 		}
985 
986 		/* Just weird. Only print a warning for this, since we should
987 		 * still be able to process it without coredumps.
988 		 */
989 		if( image->file_length > sizeof_image )
990 			g_warning( _( "%s is longer than expected" ),
991 				image->filename );
992 		break;
993 
994 	case 'm':
995 		if( image->Bands == 1 )
996 			image->Type = VIPS_INTERPRETATION_B_W;
997 		else if( image->Bands == 3 )
998 			image->Type = VIPS_INTERPRETATION_sRGB;
999 		else
1000 			image->Type = VIPS_INTERPRETATION_MULTIBAND;
1001 
1002 		image->dtype = VIPS_IMAGE_SETBUF_FOREIGN;
1003 		image->dhint = VIPS_DEMAND_STYLE_ANY;
1004 
1005 		break;
1006 
1007 	default:
1008 		vips_error( "VipsImage", _( "bad mode \"%s\"" ), mode );
1009 
1010 		return( -1 );
1011         }
1012 
1013 	vips_image_add_progress( image );
1014 
1015 	return( 0 );
1016 }
1017 
1018 static void *
vips_image_real_invalidate_cb(VipsRegion * reg,void * a,void * b)1019 vips_image_real_invalidate_cb( VipsRegion *reg, void *a, void *b )
1020 {
1021 	vips_region_invalidate( reg );
1022 
1023 	return( NULL );
1024 }
1025 
1026 static void
vips_image_real_invalidate(VipsImage * image,void * data)1027 vips_image_real_invalidate( VipsImage *image, void *data )
1028 {
1029 	VIPS_DEBUG_MSG( "vips_image_real_invalidate: %p\n", image );
1030 
1031 	VIPS_GATE_START( "vips_image_real_invalidate: wait" );
1032 
1033 	g_mutex_lock( image->sslock );
1034 
1035 	VIPS_GATE_STOP( "vips_image_real_invalidate: wait" );
1036 
1037 	(void) vips_slist_map2( image->regions,
1038 		(VipsSListMap2Fn) vips_image_real_invalidate_cb, NULL, NULL );
1039 
1040 	g_mutex_unlock( image->sslock );
1041 }
1042 
1043 static void
vips_image_real_minimise(VipsImage * image,void * data)1044 vips_image_real_minimise( VipsImage *image, void *data )
1045 {
1046 	VIPS_DEBUG_MSG( "vips_image_real_minimise: %p\n", image );
1047 }
1048 
1049 static void
vips_image_real_written(VipsImage * image,int * result,void * data)1050 vips_image_real_written( VipsImage *image, int *result, void *data )
1051 {
1052 	VIPS_DEBUG_MSG( "vips_image_real_written: %p\n", image );
1053 
1054 	/* For vips image write, append the xml after the data.
1055 	 */
1056 	if( image->dtype == VIPS_IMAGE_OPENOUT &&
1057 		vips__writehist( image ) )
1058 		*result = -1;
1059 }
1060 
1061 static void
vips_image_class_init(VipsImageClass * class)1062 vips_image_class_init( VipsImageClass *class )
1063 {
1064 	GObjectClass *gobject_class = G_OBJECT_CLASS( class );
1065 	VipsObjectClass *vobject_class = VIPS_OBJECT_CLASS( class );
1066 
1067 	VIPS_DEBUG_MSG( "vips_image_class_init:\n" );
1068 
1069 	/* We must have threads set up before we can process.
1070 	 */
1071 	vips_check_init();
1072 
1073 	gobject_class->finalize = vips_image_finalize;
1074 	gobject_class->dispose = vips_image_dispose;
1075 	gobject_class->set_property = vips_object_set_property;
1076 	gobject_class->get_property = vips_object_get_property;
1077 
1078 	vobject_class->new_from_string = vips_image_new_from_file_object;
1079 	vobject_class->to_string = vips_image_to_string;
1080 	vobject_class->output_needs_arg = TRUE;
1081 	vobject_class->output_to_arg = vips_image_write_object;
1082 
1083 	vobject_class->nickname = "image";
1084 	vobject_class->description = _( "image class" );
1085 
1086 	vobject_class->dump = vips_image_dump;
1087 	vobject_class->summary = vips_image_summary;
1088 	vobject_class->sanity = vips_image_sanity;
1089 	vobject_class->rewind = vips_image_rewind;
1090 	vobject_class->build = vips_image_build;
1091 
1092 	class->invalidate = vips_image_real_invalidate;
1093 	class->written = vips_image_real_written;
1094 	class->minimise = vips_image_real_minimise;
1095 
1096 	/* Create properties.
1097 	 */
1098 
1099 	/* It'd be good to have these as set once at construct time, but we
1100 	 * can't :-(
1101 	 *
1102 	 * For example, a "p" image might be made with vips_image_new() and
1103 	 * constructed, then passed to vips_copy() of whatever to be written to.
1104 	 * That operation will then need to set width/height etc.
1105 	 *
1106 	 * We can't set_once either, since vips_copy() etc. need to update
1107 	 * xoffset and friends on the way through.
1108 	 */
1109 
1110 	VIPS_ARG_INT( class, "width", 2,
1111 		_( "Width" ),
1112 		_( "Image width in pixels" ),
1113 		VIPS_ARGUMENT_SET_ALWAYS,
1114 		G_STRUCT_OFFSET( VipsImage, Xsize ),
1115 		1, VIPS_MAX_COORD, 1 );
1116 
1117 	VIPS_ARG_INT( class, "height", 3,
1118 		_( "Height" ),
1119 		_( "Image height in pixels" ),
1120 		VIPS_ARGUMENT_SET_ALWAYS,
1121 		G_STRUCT_OFFSET( VipsImage, Ysize ),
1122 		1, VIPS_MAX_COORD, 1 );
1123 
1124 	VIPS_ARG_INT( class, "bands", 4,
1125 		_( "Bands" ),
1126 		_( "Number of bands in image" ),
1127 		VIPS_ARGUMENT_SET_ALWAYS,
1128 		G_STRUCT_OFFSET( VipsImage, Bands ),
1129 		1, VIPS_MAX_COORD, 1 );
1130 
1131 	VIPS_ARG_ENUM( class, "format", 5,
1132 		_( "Format" ),
1133 		_( "Pixel format in image" ),
1134 		VIPS_ARGUMENT_SET_ALWAYS,
1135 		G_STRUCT_OFFSET( VipsImage, BandFmt ),
1136 		VIPS_TYPE_BAND_FORMAT, VIPS_FORMAT_UCHAR );
1137 
1138 	VIPS_ARG_ENUM( class, "coding", 6,
1139 		_( "Coding" ),
1140 		_( "Pixel coding" ),
1141 		VIPS_ARGUMENT_SET_ALWAYS,
1142 		G_STRUCT_OFFSET( VipsImage, Coding ),
1143 		VIPS_TYPE_CODING, VIPS_CODING_NONE );
1144 
1145 	VIPS_ARG_ENUM( class, "interpretation", 7,
1146 		_( "Interpretation" ),
1147 		_( "Pixel interpretation" ),
1148 		VIPS_ARGUMENT_SET_ALWAYS,
1149 		G_STRUCT_OFFSET( VipsImage, Type ),
1150 		VIPS_TYPE_INTERPRETATION, VIPS_INTERPRETATION_MULTIBAND );
1151 
1152 	VIPS_ARG_DOUBLE( class, "xres", 8,
1153 		_( "Xres" ),
1154 		_( "Horizontal resolution in pixels/mm" ),
1155 		VIPS_ARGUMENT_SET_ALWAYS,
1156 		G_STRUCT_OFFSET( VipsImage, Xres ),
1157 		-0.0, 1000000, 0 );
1158 
1159 	VIPS_ARG_DOUBLE( class, "yres", 9,
1160 		_( "Yres" ),
1161 		_( "Vertical resolution in pixels/mm" ),
1162 		VIPS_ARGUMENT_SET_ALWAYS,
1163 		G_STRUCT_OFFSET( VipsImage, Yres ),
1164 		-0.0, 1000000, 0 );
1165 
1166 	VIPS_ARG_INT( class, "xoffset", 10,
1167 		_( "Xoffset" ),
1168 		_( "Horizontal offset of origin" ),
1169 		VIPS_ARGUMENT_SET_ALWAYS,
1170 		G_STRUCT_OFFSET( VipsImage, Xoffset ),
1171 		-VIPS_MAX_COORD, VIPS_MAX_COORD, 0 );
1172 
1173 	VIPS_ARG_INT( class, "yoffset", 11,
1174 		_( "Yoffset" ),
1175 		_( "Vertical offset of origin" ),
1176 		VIPS_ARGUMENT_SET_ALWAYS,
1177 		G_STRUCT_OFFSET( VipsImage, Yoffset ),
1178 		-VIPS_MAX_COORD, VIPS_MAX_COORD, 0 );
1179 
1180 	VIPS_ARG_STRING( class, "filename", 12,
1181 		_( "Filename" ),
1182 		_( "Image filename" ),
1183 		VIPS_ARGUMENT_SET_ONCE | VIPS_ARGUMENT_CONSTRUCT,
1184 		G_STRUCT_OFFSET( VipsImage, filename ),
1185 		NULL );
1186 
1187 	VIPS_ARG_STRING( class, "mode", 13,
1188 		_( "Mode" ),
1189 		_( "Open mode" ),
1190 		VIPS_ARGUMENT_SET_ONCE | VIPS_ARGUMENT_CONSTRUCT,
1191 		G_STRUCT_OFFSET( VipsImage, mode ),
1192 		"p" );
1193 
1194 	VIPS_ARG_BOOL( class, "kill", 14,
1195 		_( "Kill" ),
1196 		_( "Block evaluation on this image" ),
1197 		VIPS_ARGUMENT_SET_ALWAYS,
1198 		G_STRUCT_OFFSET( VipsImage, kill ),
1199 		FALSE );
1200 
1201 	VIPS_ARG_ENUM( class, "demand", 15,
1202 		_( "Demand style" ),
1203 		_( "Preferred demand style for this image" ),
1204 		VIPS_ARGUMENT_CONSTRUCT,
1205 		G_STRUCT_OFFSET( VipsImage, dhint ),
1206 		VIPS_TYPE_DEMAND_STYLE, VIPS_DEMAND_STYLE_SMALLTILE );
1207 
1208 	VIPS_ARG_UINT64( class, "sizeof_header", 16,
1209 		_( "Size of header" ),
1210 		_( "Offset in bytes from start of file" ),
1211 		VIPS_ARGUMENT_SET_ONCE | VIPS_ARGUMENT_CONSTRUCT,
1212 		G_STRUCT_OFFSET( VipsImage, sizeof_header ),
1213 		0, 1000000000, VIPS_SIZEOF_HEADER );
1214 
1215 	VIPS_ARG_POINTER( class, "foreign_buffer", 17,
1216 		_( "Foreign buffer" ),
1217 		_( "Pointer to foreign pixels" ),
1218 		VIPS_ARGUMENT_SET_ONCE | VIPS_ARGUMENT_CONSTRUCT,
1219 		G_STRUCT_OFFSET( VipsImage, data ) );
1220 
1221 	/* Create signals.
1222 	 */
1223 
1224 	/**
1225 	 * VipsImage::preeval:
1226 	 * @image: the image to be calculated
1227 	 * @progress: #VipsProgress for this image
1228 	 *
1229 	 * The ::preeval signal is emitted once before computation of @image
1230 	 * starts. It's a good place to set up evaluation feedback.
1231 	 *
1232 	 * Use vips_image_set_progress() to turn on progress reporting for an
1233 	 * image.
1234 	 */
1235 	vips_image_signals[SIG_PREEVAL] = g_signal_new( "preeval",
1236 		G_TYPE_FROM_CLASS( class ),
1237 		G_SIGNAL_RUN_LAST,
1238 		G_STRUCT_OFFSET( VipsImageClass, preeval ),
1239 		NULL, NULL,
1240 		g_cclosure_marshal_VOID__POINTER,
1241 		G_TYPE_NONE, 1,
1242 		G_TYPE_POINTER );
1243 
1244 	/**
1245 	 * VipsImage::eval:
1246 	 * @image: the image being calculated
1247 	 * @progress: #VipsProgress for this image
1248 	 *
1249 	 * The ::eval signal is emitted once per work unit (typically a 128 x
1250 	 * 128 area of pixels) during image computation.
1251 	 *
1252 	 * You can use this signal to update user-interfaces with progress
1253 	 * feedback. Beware of updating too frequently: you will usually
1254 	 * need some throttling mechanism.
1255 	 *
1256 	 * Use vips_image_set_progress() to turn on progress reporting for an
1257 	 * image.
1258 	 */
1259 	vips_image_signals[SIG_EVAL] = g_signal_new( "eval",
1260 		G_TYPE_FROM_CLASS( class ),
1261 		G_SIGNAL_RUN_LAST,
1262 		G_STRUCT_OFFSET( VipsImageClass, eval ),
1263 		NULL, NULL,
1264 		g_cclosure_marshal_VOID__POINTER,
1265 		G_TYPE_NONE, 1,
1266 		G_TYPE_POINTER );
1267 
1268 	/**
1269 	 * VipsImage::posteval:
1270 	 * @image: the image that was calculated
1271 	 * @progress: #VipsProgress for this image
1272 	 *
1273 	 * The ::posteval signal is emitted once at the end of the computation
1274 	 * of @image. It's a good place to shut down evaluation feedback.
1275 	 *
1276 	 * Use vips_image_set_progress() to turn on progress reporting for an
1277 	 * image.
1278 	 */
1279 	vips_image_signals[SIG_POSTEVAL] = g_signal_new( "posteval",
1280 		G_TYPE_FROM_CLASS( class ),
1281 		G_SIGNAL_RUN_LAST,
1282 		G_STRUCT_OFFSET( VipsImageClass, posteval ),
1283 		NULL, NULL,
1284 		g_cclosure_marshal_VOID__POINTER,
1285 		G_TYPE_NONE, 1,
1286 		G_TYPE_POINTER );
1287 
1288 	/**
1289 	 * VipsImage::written:
1290 	 * @image: the image that was calculated
1291 	 * @result: set to non-zero to indicate error
1292 	 *
1293 	 * The ::written signal is emitted just after an image has been
1294 	 * written to. It is
1295 	 * used by vips to implement things like write to foreign file
1296 	 * formats.
1297 	 */
1298 	vips_image_signals[SIG_WRITTEN] = g_signal_new( "written",
1299 		G_TYPE_FROM_CLASS( class ),
1300 		G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
1301 		G_STRUCT_OFFSET( VipsImageClass, written ),
1302 		NULL, NULL,
1303 		g_cclosure_marshal_VOID__POINTER,
1304 		G_TYPE_NONE, 1,
1305 		G_TYPE_POINTER );
1306 
1307 	/**
1308 	 * VipsImage::invalidate:
1309 	 * @image: the image that has changed
1310 	 *
1311 	 * The ::invalidate signal is emitted when an image or one of it's
1312 	 * upstream data sources has been destructively modified. See
1313 	 * vips_image_invalidate_all().
1314 	 */
1315 	vips_image_signals[SIG_INVALIDATE] = g_signal_new( "invalidate",
1316 		G_TYPE_FROM_CLASS( class ),
1317 		G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
1318 		G_STRUCT_OFFSET( VipsImageClass, invalidate ),
1319 		NULL, NULL,
1320 		g_cclosure_marshal_VOID__VOID,
1321 		G_TYPE_NONE, 0 );
1322 
1323 	/**
1324 	 * VipsImage::minimise:
1325 	 * @image: the image that is being minimised
1326 	 *
1327 	 * The ::minimise signal is emitted when an image has been asked to
1328 	 * minimise memory usage. All non-essential caches are dropped.
1329 	 * See vips_image_minimise_all().
1330 	 */
1331 	vips_image_signals[SIG_MINIMISE] = g_signal_new( "minimise",
1332 		G_TYPE_FROM_CLASS( class ),
1333 		G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
1334 		G_STRUCT_OFFSET( VipsImageClass, minimise ),
1335 		NULL, NULL,
1336 		g_cclosure_marshal_VOID__VOID,
1337 		G_TYPE_NONE, 0 );
1338 
1339 	vips__minimise_lock = vips_g_mutex_new();
1340 }
1341 
1342 static void
vips_image_init(VipsImage * image)1343 vips_image_init( VipsImage *image )
1344 {
1345 	VIPS_DEBUG_MSG( "vips_image_init: %p\n", image );
1346 
1347 	/* Default to native order.
1348 	 */
1349 	image->magic = vips_amiMSBfirst() ? VIPS_MAGIC_SPARC : VIPS_MAGIC_INTEL;
1350 
1351 	image->Xsize = 1;
1352 	image->Ysize = 1;
1353 	image->Bands = 1;
1354 
1355 	image->Xres = 1.0;
1356 	image->Yres = 1.0;
1357 
1358 	image->fd = -1;			/* since 0 is stdout */
1359 	image->sslock = vips_g_mutex_new();
1360 
1361 	image->sizeof_header = VIPS_SIZEOF_HEADER;
1362 
1363 	image->mode = g_strdup( "p" );
1364 
1365 #ifdef DEBUG_LEAK
1366 	g_object_set_qdata_full( G_OBJECT( image ), vips__image_pixels_quark,
1367 		g_new0( VipsImagePixels, 1 ), (GDestroyNotify) g_free );
1368 #endif /*DEBUG_LEAK*/
1369 }
1370 
1371 int
vips_image_written(VipsImage * image)1372 vips_image_written( VipsImage *image )
1373 {
1374 	int result;
1375 
1376 	VIPS_DEBUG_MSG( "vips_image_written: %p\n", image );
1377 
1378 	result = 0;
1379 	g_signal_emit( image, vips_image_signals[SIG_WRITTEN], 0, &result );
1380 
1381 	return( result );
1382 }
1383 
1384 void
vips_image_invalidate(VipsImage * image)1385 vips_image_invalidate( VipsImage *image )
1386 {
1387 	VIPS_DEBUG_MSG( "vips_image_invalidate: %p\n", image );
1388 
1389 	g_signal_emit( image, vips_image_signals[SIG_INVALIDATE], 0 );
1390 }
1391 
1392 static void *
vips_image_invalidate_all_cb(VipsImage * image,void * a,void * b)1393 vips_image_invalidate_all_cb( VipsImage *image, void *a, void *b )
1394 {
1395 	vips_image_invalidate( image );
1396 
1397 	return( NULL );
1398 }
1399 
1400 /**
1401  * vips_image_invalidate_all: (method)
1402  * @image: #VipsImage to invalidate
1403  *
1404  * Invalidate all pixel caches on @image and any downstream images, that
1405  * is, images which depend on this image. Additionally, all operations which
1406  * depend upon this image are dropped from the VIPS operation cache.
1407  *
1408  * You should call this function after
1409  * destructively modifying an image with something like vips_draw_circle().
1410  *
1411  * The #VipsImage::invalidate signal is emitted for all invalidated images.
1412  *
1413  * See also: vips_region_invalidate().
1414  */
1415 void
vips_image_invalidate_all(VipsImage * image)1416 vips_image_invalidate_all( VipsImage *image )
1417 {
1418 	VIPS_DEBUG_MSG( "vips_image_invalidate_all: %p\n", image );
1419 
1420 	(void) vips__link_map( image, FALSE,
1421 		(VipsSListMap2Fn) vips_image_invalidate_all_cb, NULL, NULL );
1422 }
1423 
1424 void
vips_image_minimise(VipsImage * image)1425 vips_image_minimise( VipsImage *image )
1426 {
1427 	VIPS_DEBUG_MSG( "vips_image_minimise: %p\n", image );
1428 
1429 	g_signal_emit( image, vips_image_signals[SIG_MINIMISE], 0 );
1430 }
1431 
1432 static void *
vips_image_minimise_all_cb(VipsImage * image,void * a,void * b)1433 vips_image_minimise_all_cb( VipsImage *image, void *a, void *b )
1434 {
1435 	vips_image_minimise( image );
1436 
1437 	return( NULL );
1438 }
1439 
1440 /**
1441  * vips_image_minimise_all: (method)
1442  * @image: #VipsImage to minimise
1443  *
1444  * Minimise memory use on this image and any upstream images, that is, images
1445  * which this image depends upon. This function is called automatically at the
1446  * end of a computation, but it might be useful to call at other times.
1447  *
1448  * The #VipsImage::minimise signal is emitted for all minimised images.
1449  */
1450 void
vips_image_minimise_all(VipsImage * image)1451 vips_image_minimise_all( VipsImage *image )
1452 {
1453 	/* Minimisation will modify things like sources, so we can't run it
1454 	 * from many threads.
1455 	 */
1456 	g_mutex_lock( vips__minimise_lock );
1457 
1458 	(void) vips__link_map( image, TRUE,
1459 		(VipsSListMap2Fn) vips_image_minimise_all_cb, NULL, NULL );
1460 
1461 	g_mutex_unlock( vips__minimise_lock );
1462 }
1463 
1464 /**
1465  * vips_image_is_sequential: (method)
1466  * @image: #VipsImage to minimise
1467  *
1468  * TRUE if any of the images upstream from @image were opened in sequential
1469  * mode. Some operations change behaviour slightly in sequential mode to
1470  * optimize memory behaviour.
1471  *
1472  * Returns: %TRUE if @image is in sequential mode.
1473  */
1474 gboolean
vips_image_is_sequential(VipsImage * image)1475 vips_image_is_sequential( VipsImage *image )
1476 {
1477 	return( vips_image_get_typeof( image, VIPS_META_SEQUENTIAL ) );
1478 }
1479 
1480 /* Attach a new time struct, if necessary, and reset it.
1481  */
1482 static int
vips_progress_add(VipsImage * image)1483 vips_progress_add( VipsImage *image )
1484 {
1485 	VipsProgress *progress;
1486 
1487 	VIPS_DEBUG_MSG( "vips_progress_add: %p\n", image );
1488 
1489 	if( !(progress = image->time) ) {
1490 		if( !(image->time = VIPS_NEW( NULL, VipsProgress )) )
1491 			return( -1 );
1492 		progress = image->time;
1493 
1494 		progress->im = image;
1495 		progress->start = NULL;
1496 	}
1497 
1498 	if( !progress->start )
1499 		progress->start = g_timer_new();
1500 
1501 	g_timer_start( progress->start );
1502 	progress->run = 0;
1503 	progress->eta = 0;
1504 	progress->tpels = VIPS_IMAGE_N_PELS( image );
1505 	progress->npels = 0;
1506 	progress->percent = 0;
1507 
1508 	return( 0 );
1509 }
1510 
1511 static void
vips_progress_update(VipsProgress * progress,guint64 processed)1512 vips_progress_update( VipsProgress *progress, guint64 processed )
1513 {
1514 	float prop;
1515 
1516 	VIPS_DEBUG_MSG( "vips_progress_update: %p\n", progress );
1517 
1518 	g_assert( progress );
1519 
1520 	progress->run = g_timer_elapsed( progress->start, NULL );
1521 	progress->npels = processed;
1522 	prop = (float) progress->npels / (float) progress->tpels;
1523 	progress->percent = 100 * prop;
1524 
1525 	/* Don't estimate eta until we are 10% in.
1526 	 */
1527 	if( prop > 0.1 )
1528 		progress->eta = (1.0 / prop) * progress->run - progress->run;
1529 }
1530 
1531 void
vips_image_preeval(VipsImage * image)1532 vips_image_preeval( VipsImage *image )
1533 {
1534 	if( image->progress_signal ) {
1535 		VIPS_DEBUG_MSG( "vips_image_preeval: %p\n", image );
1536 
1537 		g_assert( vips_object_sanity(
1538 			VIPS_OBJECT( image->progress_signal ) ) );
1539 
1540 		(void) vips_progress_add( image );
1541 
1542 		/* For vips7 compat, we also have to make sure ->time on the
1543 		 * image that was originally marked with
1544 		 * vips_image_set_progress() is valid.
1545 		 */
1546 		(void) vips_progress_add( image->progress_signal );
1547 
1548 		if( !vips_image_get_typeof( image, "hide-progress" ) )
1549 			g_signal_emit( image->progress_signal,
1550 				vips_image_signals[SIG_PREEVAL], 0,
1551 				image->time );
1552 	}
1553 }
1554 
1555 /* Updated the number of pixels that have been processed.
1556  */
1557 void
vips_image_eval(VipsImage * image,guint64 processed)1558 vips_image_eval( VipsImage *image, guint64 processed )
1559 {
1560 	if( image->progress_signal &&
1561 		image->time ) {
1562 		VIPS_DEBUG_MSG( "vips_image_eval: %p\n", image );
1563 
1564 		g_assert( vips_object_sanity(
1565 			VIPS_OBJECT( image->progress_signal ) ) );
1566 
1567 		vips_progress_update( image->time, processed );
1568 
1569 		/* For vips7 compat, update the ->time on the signalling image
1570 		 * too, even though it may have a different width/height to
1571 		 * the image we are actually generating.
1572 		 */
1573 		if( image->progress_signal->time != image->time )
1574 			vips_progress_update( image->progress_signal->time,
1575 				processed );
1576 
1577 		if( !vips_image_get_typeof( image, "hide-progress" ) )
1578 			g_signal_emit( image->progress_signal,
1579 				vips_image_signals[SIG_EVAL], 0,
1580 				image->time );
1581 	}
1582 }
1583 
1584 void
vips_image_posteval(VipsImage * image)1585 vips_image_posteval( VipsImage *image )
1586 {
1587 	if( image->progress_signal &&
1588 		image->progress_signal->time ) {
1589 		VIPS_DEBUG_MSG( "vips_image_posteval: %p\n", image );
1590 
1591 		g_assert( vips_object_sanity(
1592 			VIPS_OBJECT( image->progress_signal ) ) );
1593 
1594 		if( !vips_image_get_typeof( image, "hide-progress" ) )
1595 			g_signal_emit( image->progress_signal,
1596 				vips_image_signals[SIG_POSTEVAL], 0,
1597 				image->time );
1598 	}
1599 }
1600 
1601 /**
1602  * vips_image_set_progress: (method)
1603  * @image: image to signal progress on
1604  * @progress: turn progress reporting on or off
1605  *
1606  * vips signals evaluation progress via the #VipsImage::preeval,
1607  * #VipsImage::eval and #VipsImage::posteval
1608  * signals. Progress is signalled on the most-downstream image for which
1609  * vips_image_set_progress() was called.
1610  */
1611 void
vips_image_set_progress(VipsImage * image,gboolean progress)1612 vips_image_set_progress( VipsImage *image, gboolean progress )
1613 {
1614 	if( progress &&
1615 		!image->progress_signal ) {
1616 		VIPS_DEBUG_MSG( "vips_image_set_progress: %p %s\n",
1617 			image, image->filename );
1618 		image->progress_signal = image;
1619 	}
1620 	else if( !progress )
1621 		image->progress_signal = NULL;
1622 }
1623 
1624 /**
1625  * vips_image_iskilled: (method)
1626  * @image: image to test
1627  *
1628  * If @image has been killed (see vips_image_set_kill()), set an error message,
1629  * clear the #VipsImage.kill flag and return %TRUE. Otherwise return %FALSE.
1630  *
1631  * Handy for loops which need to run sets of threads which can fail.
1632  *
1633  * See also: vips_image_set_kill().
1634  *
1635  * Returns: %TRUE if @image has been killed.
1636  */
1637 gboolean
vips_image_iskilled(VipsImage * image)1638 vips_image_iskilled( VipsImage *image )
1639 {
1640 	gboolean kill;
1641 
1642 	kill = image->kill;
1643 
1644 	/* Has kill been set for this image? If yes, abort evaluation.
1645 	 */
1646 	if( image->kill ) {
1647 		VIPS_DEBUG_MSG( "vips_image_iskilled: %s (%p) killed\n",
1648 			image->filename, image );
1649 		vips_error( "VipsImage",
1650 			_( "killed for image \"%s\"" ), image->filename );
1651 
1652 		/* We've picked up the kill message, it's now our caller's
1653 		 * responsibility to pass the message up the chain.
1654 		 */
1655 		vips_image_set_kill( image, FALSE );
1656 	}
1657 
1658 	return( kill );
1659 }
1660 
1661 /**
1662  * vips_image_set_kill: (method)
1663  * @image: image to test
1664  * @kill: the kill state
1665  *
1666  * Set the #VipsImage.kill flag on an image. Handy for stopping sets of
1667  * threads.
1668  *
1669  * See also: vips_image_iskilled().
1670  */
1671 void
vips_image_set_kill(VipsImage * image,gboolean kill)1672 vips_image_set_kill( VipsImage *image, gboolean kill )
1673 {
1674 	if( image->kill != kill )
1675 		VIPS_DEBUG_MSG( "vips_image_set_kill: %s (%p) %d\n",
1676 			image->filename, image, kill );
1677 
1678 	image->kill = kill;
1679 }
1680 
1681 /* Fills the given buffer with a temporary filename.
1682  * Assuming that "int" might be 64 Bit wide a buffer size of 26 suffices.
1683  */
1684 void
vips_image_temp_name(char * name,int size)1685 vips_image_temp_name( char *name, int size )
1686 {
1687 	static int global_serial = 0;
1688 
1689 	int serial = g_atomic_int_add( &global_serial, 1 );
1690 
1691 	vips_snprintf( name, size, "temp-%d", serial );
1692 }
1693 
1694 /**
1695  * vips_image_new: (constructor)
1696  *
1697  * vips_image_new() creates a new, empty #VipsImage.
1698  * If you write to one of these images, vips will just attach some callbacks,
1699  * no pixels will be generated.
1700  *
1701  * Write pixels to an image with vips_image_generate() or
1702  * vips_image_write_line(). Write a whole image to another image with
1703  * vips_image_write().
1704  *
1705  * Returns: (transfer full): the new #VipsImage, or %NULL on error.
1706  */
1707 VipsImage *
vips_image_new(void)1708 vips_image_new( void )
1709 {
1710 	VipsImage *image;
1711 	char filename[26];
1712 
1713 	vips_check_init();
1714 
1715 	vips_image_temp_name( filename, sizeof( filename ) );
1716 
1717 	image = VIPS_IMAGE( g_object_new( VIPS_TYPE_IMAGE, NULL ) );
1718 	g_object_set( image,
1719 		"filename", filename,
1720 		"mode", "p",
1721 		NULL );
1722 	if( vips_object_build( VIPS_OBJECT( image ) ) ) {
1723 		VIPS_UNREF( image );
1724 		return( NULL );
1725 	}
1726 
1727 	return( image );
1728 }
1729 
1730 VipsImage *
vips_image_new_mode(const char * filename,const char * mode)1731 vips_image_new_mode( const char *filename, const char *mode )
1732 {
1733 	VipsImage *image;
1734 
1735 	g_assert( filename );
1736 	g_assert( mode );
1737 
1738 	vips_check_init();
1739 
1740 	image = VIPS_IMAGE( g_object_new( VIPS_TYPE_IMAGE, NULL ) );
1741 	g_object_set( image,
1742 		"filename", filename,
1743 		"mode", mode,
1744 		NULL );
1745 	if( vips_object_build( VIPS_OBJECT( image ) ) ) {
1746 		VIPS_UNREF( image );
1747 		return( NULL );
1748 	}
1749 
1750 	return( image );
1751 }
1752 
1753 /**
1754  * vips_image_new_memory: (constructor)
1755  *
1756  * vips_image_new_memory() creates a new #VipsImage which, when written to, will
1757  * create a memory image.
1758  *
1759  * See also: vips_image_new().
1760  *
1761  * Returns: (transfer full): the new #VipsImage, or %NULL on error.
1762  */
1763 VipsImage *
vips_image_new_memory(void)1764 vips_image_new_memory( void )
1765 {
1766 	char filename[26];
1767 
1768 	vips_image_temp_name( filename, sizeof( filename ) );
1769 	return( vips_image_new_mode( filename, "t" ) );
1770 }
1771 
1772 /**
1773  * vips_image_memory: (constructor)
1774  *
1775  * A renamed vips_image_new_memory() ... Some gobject binding systems do not
1776  * like more than one _new() method.
1777  *
1778  * See also: vips_image_new_memory().
1779  *
1780  * Returns: (transfer full): the new #VipsImage, or %NULL on error.
1781  */
1782 VipsImage *
vips_image_memory(void)1783 vips_image_memory( void )
1784 {
1785 	return( vips_image_new_memory() );
1786 }
1787 
1788 /**
1789  * vips_filename_get_filename:
1790  * @vips_filename: a filename including a set of options
1791  *
1792  * Given a vips filename like "fred.jpg[Q=90]", return a new string of
1793  * just the filename part, "fred.jpg" in this case.
1794  *
1795  * Useful for language bindings.
1796  *
1797  * See also: vips_filename_get_options().
1798  *
1799  * Returns: transfer full: just the filename component.
1800  */
1801 char *
vips_filename_get_filename(const char * vips_filename)1802 vips_filename_get_filename( const char *vips_filename )
1803 {
1804 	char filename[VIPS_PATH_MAX];
1805 	char options[VIPS_PATH_MAX];
1806 
1807 	vips__filename_split8( vips_filename, filename, options );
1808 
1809 	return( g_strdup( filename ) );
1810 }
1811 
1812 /**
1813  * vips_filename_get_options:
1814  * @vips_filename: a filename including a set of options
1815  *
1816  * Given a vips filename like "fred.jpg[Q=90]", return a new string of
1817  * just the options part, "[Q=90]" in this case.
1818  *
1819  * Useful for language bindings.
1820  *
1821  * See also: vips_filename_get_filename().
1822  *
1823  * Returns: transfer full: just the options component.
1824  */
1825 char *
vips_filename_get_options(const char * vips_filename)1826 vips_filename_get_options( const char *vips_filename )
1827 {
1828 	char filename[VIPS_PATH_MAX];
1829 	char options[VIPS_PATH_MAX];
1830 
1831 	vips__filename_split8( vips_filename, filename, options );
1832 
1833 	return( g_strdup( options ) );
1834 }
1835 
1836 /**
1837  * vips_image_new_from_file: (constructor)
1838  * @name: file to open
1839  * @...: %NULL-terminated list of optional named arguments
1840  *
1841  * Optional arguments:
1842  *
1843  * * @access: hint #VipsAccess mode to loader
1844  * * @memory: force load via memory
1845  *
1846  * vips_image_new_from_file() opens @name for reading. It can load files
1847  * in many image formats, including VIPS, TIFF, PNG, JPEG, FITS, Matlab,
1848  * OpenEXR, CSV, WebP, Radiance, RAW, PPM and others.
1849  *
1850  * Load options may be appended to @filename as "[name=value,...]" or given as
1851  * a NULL-terminated list of name-value pairs at the end of the arguments.
1852  * Options given in the function call override options given in the filename.
1853  * Many loaders add extra options, see vips_jpegload(), for example.
1854  *
1855  * vips_image_new_from_file() always returns immediately with the header
1856  * fields filled in. No pixels are actually read until you first access them.
1857  *
1858  * @access lets you set a #VipsAccess hint giving the expected access pattern
1859  * for this file.
1860  * #VIPS_ACCESS_RANDOM means you can fetch pixels randomly from the image.
1861  * This is the default mode. #VIPS_ACCESS_SEQUENTIAL means you will read the
1862  * whole image exactly once, top-to-bottom. In this mode, vips can avoid
1863  * converting the whole image in one go, for a large memory saving. You are
1864  * allowed to make small non-local references, so area operations like
1865  * convolution will work.
1866  *
1867  * In #VIPS_ACCESS_RANDOM mode, small images are decompressed to memory and
1868  * then processed from there. Large images are decompressed to temporary
1869  * random-access files on disc and then processed from there.
1870  *
1871  * Set @memory to %TRUE to force loading via memory. The default is to load
1872  * large random access images via temporary disc files. See
1873  * vips_image_new_temp_file() for an
1874  * explanation of how VIPS selects a location for the temporary file.
1875  *
1876  * The disc threshold can be set with the "--vips-disc-threshold"
1877  * command-line argument, or the `VIPS_DISC_THRESHOLD` environment variable.
1878  * The value is a simple integer, but can take a unit postfix of "k",
1879  * "m" or "g" to indicate kilobytes, megabytes or gigabytes.
1880  * The default threshold is 100 MB.
1881  *
1882  * For example:
1883  *
1884  * |[
1885  * VipsImage *image = vips_image_new_from_file ("fred.tif",
1886  * 	"page", 12,
1887  * 	NULL);
1888  * ]|
1889  *
1890  * Will open "fred.tif", reading page 12.
1891  *
1892  * |[
1893  * VipsImage *image = vips_image_new_from_file ("fred.jpg[shrink=2]",
1894  * 	NULL);
1895  * ]|
1896  *
1897  * Will open "fred.jpg", downsampling by a factor of two.
1898  *
1899  * Use vips_foreign_find_load() or vips_foreign_is_a() to see what format a
1900  * file is in and therefore what options are available. If you need more
1901  * control over the loading process, you can call loaders directly, see
1902  * vips_jpegload(), for example.
1903  *
1904  * See also: vips_foreign_find_load(), vips_foreign_is_a(),
1905  * vips_image_write_to_file().
1906  *
1907  * Returns: (transfer full): the new #VipsImage, or %NULL on error.
1908  */
1909 VipsImage *
vips_image_new_from_file(const char * name,...)1910 vips_image_new_from_file( const char *name, ... )
1911 {
1912 	char filename[VIPS_PATH_MAX];
1913 	char option_string[VIPS_PATH_MAX];
1914 	const char *operation_name;
1915 	va_list ap;
1916 	int result;
1917 	VipsImage *out;
1918 
1919 	vips_check_init();
1920 
1921 	vips__filename_split8( name, filename, option_string );
1922 
1923 	if( !(operation_name = vips_foreign_find_load( filename )) )
1924 		return( NULL );
1925 
1926 	va_start( ap, name );
1927 	result = vips_call_split_option_string( operation_name,
1928 		option_string, ap, filename, &out );
1929 	va_end( ap );
1930 
1931 	if( result )
1932 		return( NULL );
1933 
1934 	return( out );
1935 }
1936 
1937 /**
1938  * vips_image_new_from_file_RW: (constructor)
1939  * @filename: filename to open
1940  *
1941  * Opens the named file for simultaneous reading and writing. This will only
1942  * work for VIPS files in a format native to your machine. It is only for
1943  * paintbox-type applications.
1944  *
1945  * See also: vips_draw_circle().
1946  *
1947  * Returns: (transfer full): the new #VipsImage, or %NULL on error.
1948  */
1949 VipsImage *
vips_image_new_from_file_RW(const char * filename)1950 vips_image_new_from_file_RW( const char *filename )
1951 {
1952 	return( vips_image_new_mode( filename, "rw" ) );
1953 }
1954 
1955 /**
1956  * vips_image_new_from_file_raw: (constructor)
1957  * @filename: filename to open
1958  * @xsize: image width
1959  * @ysize: image height
1960  * @bands: image bands (or bytes per pixel)
1961  * @offset: bytes to skip at start of file
1962  *
1963  * This function maps the named file and returns a #VipsImage you can use to
1964  * read it.
1965  *
1966  * It returns an 8-bit image with @bands bands. If the image is not 8-bit, use
1967  * vips_copy() to transform the descriptor after loading it.
1968  *
1969  * See also: vips_copy(), vips_rawload(), vips_image_new_from_file().
1970  *
1971  * Returns: (transfer full): the new #VipsImage, or %NULL on error.
1972  */
1973 VipsImage *
vips_image_new_from_file_raw(const char * filename,int xsize,int ysize,int bands,guint64 offset)1974 vips_image_new_from_file_raw( const char *filename,
1975 	int xsize, int ysize, int bands, guint64 offset )
1976 {
1977 	VipsImage *image;
1978 
1979 	vips_check_init();
1980 
1981 	image = VIPS_IMAGE( g_object_new( VIPS_TYPE_IMAGE, NULL ) );
1982 	g_object_set( image,
1983 		"filename", filename,
1984 		"mode", "a",
1985 		"width", xsize,
1986 		"height", ysize,
1987 		"bands", bands,
1988 		"sizeof_header", offset,
1989 		NULL );
1990 	if( vips_object_build( VIPS_OBJECT( image ) ) ) {
1991 		VIPS_UNREF( image );
1992 		return( NULL );
1993 	}
1994 
1995 	return( image );
1996 }
1997 
1998 /**
1999  * vips_image_new_from_memory: (constructor)
2000  * @data: (array length=size) (element-type guint8) (transfer none): start of memory area
2001  * @size: (type gsize): length of memory area
2002  * @width: image width
2003  * @height: image height
2004  * @bands: image bands (or bytes per pixel)
2005  * @format: image format
2006  *
2007  * This function wraps a #VipsImage around a memory area. The memory area
2008  * must be a simple array, for example RGBRGBRGB, left-to-right,
2009  * top-to-bottom. Use vips_image_new_from_buffer() to load an area of memory
2010  * containing an image in a format.
2011  *
2012  * VIPS does not take
2013  * responsibility for the area of memory, it's up to you to make sure it's
2014  * freed when the image is closed. See for example #VipsObject::close.
2015  *
2016  * Because VIPS is "borrowing" @data from the caller, this function is
2017  * extremely dangerous. Unless you are very careful, you will get crashes or
2018  * memory corruption. Use vips_image_new_from_memory_copy() instead if you are
2019  * at all unsure.
2020  *
2021  * Use vips_copy() to set other image properties.
2022  *
2023  * See also: vips_image_new(), vips_image_write_to_memory(),
2024  * vips_image_new_from_memory_copy().
2025  *
2026  * Returns: (transfer full): the new #VipsImage, or %NULL on error.
2027  */
2028 VipsImage *
vips_image_new_from_memory(const void * data,size_t size,int width,int height,int bands,VipsBandFormat format)2029 vips_image_new_from_memory( const void *data, size_t size,
2030 	int width, int height, int bands, VipsBandFormat format )
2031 {
2032 	VipsImage *image;
2033 	char filename[26];
2034 
2035 	vips_check_init();
2036 	vips_image_temp_name( filename, sizeof( filename ) );
2037 
2038 	image = VIPS_IMAGE( g_object_new( VIPS_TYPE_IMAGE, NULL ) );
2039 	g_object_set( image,
2040 		"filename", filename,
2041 		"mode", "m",
2042 		"foreign_buffer", data,
2043 		"width", width,
2044 		"height", height,
2045 		"bands", bands,
2046 		"format", format,
2047 		NULL );
2048 	if( vips_object_build( VIPS_OBJECT( image ) ) ) {
2049 		VIPS_UNREF( image );
2050 		return( NULL );
2051 	}
2052 
2053 	if( size < VIPS_IMAGE_SIZEOF_IMAGE( image ) ) {
2054 		vips_error( "VipsImage",
2055 			_( "memory area too small --- "
2056 				"should be %" G_GINT64_FORMAT " bytes, "
2057 				"you passed %zd" ),
2058 			VIPS_IMAGE_SIZEOF_IMAGE( image ), size );
2059 		VIPS_UNREF( image );
2060 		return( NULL );
2061 	}
2062 
2063 	return( image );
2064 }
2065 
2066 static void
vips_image_new_from_memory_copy_cb(VipsImage * image,void * data_copy)2067 vips_image_new_from_memory_copy_cb( VipsImage *image, void *data_copy )
2068 {
2069 	vips_tracked_free( data_copy );
2070 }
2071 
2072 /**
2073  * vips_image_new_from_memory_copy: (constructor)
2074  * @data: (array length=size) (element-type guint8) (transfer none): start of memory area
2075  * @size: (type gsize): length of memory area
2076  * @width: image width
2077  * @height: image height
2078  * @bands: image bands (or bytes per pixel)
2079  * @format: image format
2080  *
2081  * Like vips_image_new_from_memory(), but VIPS will make a copy of the memory
2082  * area. This means more memory use and an extra copy operation, but is much
2083  * simpler and safer.
2084  *
2085  * See also: vips_image_new_from_memory().
2086  *
2087  * Returns: (transfer full): the new #VipsImage, or %NULL on error.
2088  */
2089 VipsImage *
vips_image_new_from_memory_copy(const void * data,size_t size,int width,int height,int bands,VipsBandFormat format)2090 vips_image_new_from_memory_copy( const void *data, size_t size,
2091 	int width, int height, int bands, VipsBandFormat format )
2092 {
2093 	void *data_copy;
2094 	VipsImage *image;
2095 
2096 	vips_check_init();
2097 
2098 	if( !(data_copy = vips_tracked_malloc( size )) )
2099 		return( NULL );
2100 	memcpy( data_copy, data, size );
2101 	if( !(image = vips_image_new_from_memory( data_copy, size,
2102 		width, height, bands, format )) ) {
2103 		vips_tracked_free( data_copy );
2104 		return( NULL );
2105 	}
2106 
2107 	g_signal_connect( image, "close",
2108 		G_CALLBACK( vips_image_new_from_memory_copy_cb ), data_copy );
2109 
2110 	return( image );
2111 }
2112 
2113 /**
2114  * vips_image_new_from_buffer: (constructor)
2115  * @buf: (array length=len) (element-type guint8) (transfer none): image data
2116  * @len: (type gsize): length of memory buffer
2117  * @option_string: set of extra options as a string
2118  * @...: %NULL-terminated list of optional named arguments
2119  *
2120  * Loads an image from the formatted area of memory @buf, @len using the
2121  * loader recommended by vips_foreign_find_load_buffer().
2122  * To load an unformatted area of memory, use
2123  * vips_image_new_from_memory().
2124  *
2125  * VIPS does not take
2126  * responsibility for the area of memory, it's up to you to make sure it's
2127  * freed when the image is closed. See for example #VipsObject::close.
2128  *
2129  * Load options may be given in @option_string as "[name=value,...]" or given as
2130  * a NULL-terminated list of name-value pairs at the end of the arguments.
2131  * Options given in the function call override options given in the filename.
2132  *
2133  * See also: vips_image_write_to_buffer().
2134  *
2135  * Returns: (transfer full): the new #VipsImage, or %NULL on error.
2136  */
2137 VipsImage *
vips_image_new_from_buffer(const void * buf,size_t len,const char * option_string,...)2138 vips_image_new_from_buffer( const void *buf, size_t len,
2139 	const char *option_string, ... )
2140 {
2141 	const char *operation_name;
2142 	va_list ap;
2143 	int result;
2144 	VipsImage *out;
2145 	VipsBlob *blob;
2146 
2147 	vips_check_init();
2148 
2149 	if( !(operation_name =
2150 		vips_foreign_find_load_buffer( buf, len )) )
2151 		return( NULL );
2152 
2153 	/* We don't take a copy of the data or free it.
2154 	 */
2155 	blob = vips_blob_new( NULL, buf, len );
2156 
2157 	va_start( ap, option_string );
2158 	result = vips_call_split_option_string( operation_name,
2159 		option_string, ap, blob, &out );
2160 	va_end( ap );
2161 
2162 	vips_area_unref( VIPS_AREA( blob ) );
2163 
2164 	if( result )
2165 		return( NULL );
2166 
2167 	return( out );
2168 }
2169 
2170 /**
2171  * vips_image_new_from_source: (constructor)
2172  * @source: (transfer none): source to fetch image from
2173  * @option_string: set of extra options as a string
2174  * @...: %NULL-terminated list of optional named arguments
2175  *
2176  * Loads an image from the formatted source @input,
2177  * loader recommended by vips_foreign_find_load_source().
2178  *
2179  * Load options may be given in @option_string as "[name=value,...]" or given as
2180  * a NULL-terminated list of name-value pairs at the end of the arguments.
2181  * Options given in the function call override options given in the string.
2182  *
2183  * See also: vips_image_write_to_target().
2184  *
2185  * Returns: (transfer full): the new #VipsImage, or %NULL on error.
2186  */
2187 VipsImage *
vips_image_new_from_source(VipsSource * source,const char * option_string,...)2188 vips_image_new_from_source( VipsSource *source,
2189 	const char *option_string, ... )
2190 {
2191 	const char *filename =
2192 		vips_connection_filename( VIPS_CONNECTION( source ) );
2193 
2194 	const char *operation_name;
2195 	va_list ap;
2196 	int result;
2197 	VipsImage *out;
2198 
2199 	vips_check_init();
2200 
2201 	vips_error_freeze();
2202 	operation_name = vips_foreign_find_load_source( source );
2203 	vips_error_thaw();
2204 
2205         if( operation_name ) {
2206 		va_start( ap, option_string );
2207 		result = vips_call_split_option_string( operation_name,
2208 			option_string, ap, source, &out );
2209 		va_end( ap );
2210 	}
2211 	else if( filename ) {
2212 		/* Try with the old file-based loaders.
2213 		 */
2214 		if( !(operation_name = vips_foreign_find_load( filename )) )
2215 			return( NULL );
2216 
2217 		va_start( ap, option_string );
2218 		result = vips_call_split_option_string( operation_name,
2219 			option_string, ap, filename, &out );
2220 		va_end( ap );
2221 	}
2222 	else if( vips_source_is_mappable( source ) ) {
2223 		/* Try with the old buffer-based loaders.
2224 		 */
2225 		VipsBlob *blob;
2226 		const void *buf;
2227 		size_t len;
2228 
2229 		if( !(blob = vips_source_map_blob( source )) )
2230 			return( NULL );
2231 
2232 		buf = vips_blob_get( blob, &len );
2233 		if( !(operation_name =
2234 			vips_foreign_find_load_buffer( buf, len )) ) {
2235 			vips_area_unref( VIPS_AREA( blob ) );
2236 			return( NULL );
2237 		}
2238 
2239                 va_start( ap, option_string );
2240                 result = vips_call_split_option_string( operation_name,
2241                         option_string, ap, blob, &out );
2242                 va_end( ap );
2243 
2244 		vips_area_unref( VIPS_AREA( blob ) );
2245 	}
2246 	else {
2247 		vips_error( "VipsImage",
2248 			"%s", _( "unable to load source" ) );
2249 		result = -1;
2250 	}
2251 
2252         if( result )
2253                 return( NULL );
2254 
2255         return( out );
2256 }
2257 
2258 /**
2259  * vips_image_new_matrix: (constructor)
2260  * @width: image width
2261  * @height: image height
2262  *
2263  * This convenience function makes an image which is a matrix: a one-band
2264  * #VIPS_FORMAT_DOUBLE image held in memory.
2265  *
2266  * Use VIPS_IMAGE_ADDR(), or VIPS_MATRIX() to address pixels in the image.
2267  *
2268  * Use vips_image_set_double() to set "scale" and "offset", if required.
2269  *
2270  * See also: vips_image_new_matrixv()
2271  *
2272  * Returns: (transfer full): the new #VipsImage, or %NULL on error.
2273  */
2274 VipsImage *
vips_image_new_matrix(int width,int height)2275 vips_image_new_matrix( int width, int height )
2276 {
2277 	VipsImage *image;
2278 
2279 	vips_check_init();
2280 
2281 	image = VIPS_IMAGE( g_object_new( VIPS_TYPE_IMAGE, NULL ) );
2282 	g_object_set( image,
2283 		"filename", "vips_image_new_matrix",
2284 		"mode", "t",
2285 		"width", width,
2286 		"height", height,
2287 		"bands", 1,
2288 		"format", VIPS_FORMAT_DOUBLE,
2289 		"interpretation", VIPS_INTERPRETATION_MATRIX,
2290 		NULL );
2291 	if( vips_object_build( VIPS_OBJECT( image ) ) ) {
2292 		VIPS_UNREF( image );
2293 		return( NULL );
2294 	}
2295 
2296 	if( vips_image_write_prepare( image ) ) {
2297 		g_object_unref( image );
2298 		return( NULL );
2299 	}
2300 
2301 	return( image );
2302 }
2303 
2304 /**
2305  * vips_image_new_matrixv: (constructor)
2306  * @width: image width
2307  * @height: image height
2308  * @...: matrix coefficients
2309  *
2310  * As vips_image_new_matrix(), but initialise the matrix from the argument
2311  * list. After @height should be @width * @height double constants which are
2312  * used to set the matrix elements.
2313  *
2314  * See also: vips_image_new_matrix()
2315  *
2316  * Returns: (transfer full): the new #VipsImage, or %NULL on error.
2317  */
2318 VipsImage *
vips_image_new_matrixv(int width,int height,...)2319 vips_image_new_matrixv( int width, int height, ... )
2320 {
2321 	va_list ap;
2322 	VipsImage *matrix;
2323 	int x, y;
2324 
2325 	vips_check_init();
2326 
2327 	matrix = vips_image_new_matrix( width, height );
2328 
2329 	va_start( ap, height );
2330 	for( y = 0; y < height; y++ )
2331 		for( x = 0; x < width; x++ )
2332 			*VIPS_MATRIX( matrix, x, y ) = va_arg( ap, double );
2333 	va_end( ap );
2334 
2335 	return( matrix );
2336 }
2337 
2338 /**
2339  * vips_image_new_matrix_from_array: (constructor)
2340  * @width: image width
2341  * @height: image height
2342  * @array: (array length=size) (transfer none): array of elements
2343  * @size: (type gsize): number of elements
2344  *
2345  * A binding-friendly version of vips_image_new_matrixv().
2346  *
2347  * Returns: (transfer full): the new #VipsImage, or %NULL on error.
2348  */
2349 VipsImage *
vips_image_new_matrix_from_array(int width,int height,const double * array,int size)2350 vips_image_new_matrix_from_array( int width, int height,
2351 	const double *array, int size )
2352 {
2353 	VipsImage *matrix;
2354 	int x, y;
2355 	int i;
2356 
2357 	if( size != width * height ) {
2358 		vips_error( "VipsImage",
2359 			_( "bad array length --- should be %d, you passed %d" ),
2360 			width * height, size );
2361 		return( NULL );
2362 	}
2363 
2364 	vips_check_init();
2365 
2366 	matrix = vips_image_new_matrix( width, height );
2367 
2368 	i = 0;
2369 	for( y = 0; y < height; y++ )
2370 		for( x = 0; x < width; x++ )
2371 			*VIPS_MATRIX( matrix, x, y ) = array[i++];
2372 
2373 	return( matrix );
2374 }
2375 
2376 /**
2377  * vips_image_matrix_from_array: (constructor)
2378  * @width: image width
2379  * @height: image height
2380  * @array: (array length=size) (transfer none): array of elements
2381  * @size: (type gsize): number of elements
2382  *
2383  * A renamed vips_image_new_matrix_from_array(). Some gobject bindings do not
2384  * like more than one _new method.
2385  *
2386  * Returns: (transfer full): the new #VipsImage, or %NULL on error.
2387  */
2388 VipsImage *
vips_image_matrix_from_array(int width,int height,const double * array,int size)2389 vips_image_matrix_from_array( int width, int height,
2390 	const double *array, int size )
2391 {
2392 	return( vips_image_new_matrix_from_array( width, height,
2393 		array, size ) );
2394 }
2395 
2396 /**
2397  * vips_image_new_from_image: (constructor)
2398  * @image: image to copy
2399  * @c: (array length=n) (transfer none): array of constants
2400  * @n: number of constants
2401  *
2402  * Creates a new image with width, height, format, interpretation, resolution
2403  * and offset taken from @image, but with number of bands taken from @n and the
2404  * value of each band element set from @c.
2405  *
2406  * See also: vips_image_new_from_image1()
2407  *
2408  * Returns: (transfer full): the new #VipsImage, or %NULL on error.
2409  */
2410 VipsImage *
vips_image_new_from_image(VipsImage * image,const double * c,int n)2411 vips_image_new_from_image( VipsImage *image, const double *c, int n )
2412 {
2413 	VipsObject *scope = (VipsObject *) vips_image_new();
2414 	VipsImage **t = (VipsImage **) vips_object_local_array( scope, 5 );
2415 
2416 	double *ones;
2417 	int i;
2418 	VipsImage *result;
2419 
2420 	if( !(ones = VIPS_ARRAY( scope, n, double )) ) {
2421 		g_object_unref( scope );
2422 		return( NULL );
2423 	}
2424 	for( i = 0; i < n; i++ )
2425 		ones[i] = 1.0;
2426 
2427 	if( vips_black( &t[0], 1, 1, NULL ) ||
2428 		vips_linear( t[0], &t[1], ones, (double *) c, n, NULL ) ||
2429 		vips_cast( t[1], &t[2], image->BandFmt, NULL ) ||
2430 		vips_embed( t[2], &t[3], 0, 0, image->Xsize, image->Ysize,
2431 			"extend", VIPS_EXTEND_COPY, NULL ) ||
2432 		vips_copy( t[3], &t[4],
2433 			"interpretation", image->Type,
2434 			"xres", image->Xres,
2435 			"yres", image->Yres,
2436 			"xoffset", image->Xoffset,
2437 			"yoffset", image->Yoffset,
2438 			NULL ) ) {
2439 		g_object_unref( scope );
2440 		return( NULL );
2441 	}
2442 
2443 	result = t[4];
2444 	g_object_ref( result );
2445 
2446 	g_object_unref( scope );
2447 
2448 	return( result );
2449 }
2450 
2451 /**
2452  * vips_image_new_from_image1: (constructor)
2453  * @image: image to copy
2454  * @c: constants
2455  *
2456  * Creates a new image with width, height, format, interpretation, resolution
2457  * and offset taken from @image, but with one band and each pixel having the
2458  * value @c.
2459  *
2460  * See also: vips_image_new_from_image()
2461  *
2462  * Returns: (transfer full): the new #VipsImage, or %NULL on error.
2463  */
2464 VipsImage *
vips_image_new_from_image1(VipsImage * image,double c)2465 vips_image_new_from_image1( VipsImage *image, double c )
2466 {
2467 	return( vips_image_new_from_image( image, (const double *) &c, 1 ) );
2468 }
2469 
2470 /**
2471  * vips_image_set_delete_on_close: (method)
2472  * @image: image to set
2473  * @delete_on_close: format of file
2474  *
2475  * Sets the delete_on_close flag for the image. If this flag is set, when
2476  * @image is finalized, the filename held in @image->filename at the time of
2477  * this call is deleted.
2478  *
2479  * This function is clearly extremely dangerous, use with great caution.
2480  *
2481  * See also: vips_image_new_temp_file().
2482  */
2483 void
vips_image_set_delete_on_close(VipsImage * image,gboolean delete_on_close)2484 vips_image_set_delete_on_close( VipsImage *image, gboolean delete_on_close )
2485 {
2486 	VIPS_DEBUG_MSG( "vips_image_set_delete_on_close: %d %s\n",
2487 			delete_on_close, image->filename );
2488 
2489 	image->delete_on_close = delete_on_close;
2490 	VIPS_FREE( image->delete_on_close_filename );
2491 	if( delete_on_close )
2492 		VIPS_SETSTR( image->delete_on_close_filename, image->filename );
2493 }
2494 
2495 /**
2496  * vips_get_disc_threshold:
2497  *
2498  * Return the number of bytes at which we flip between open via memory and
2499  * open via disc. This defaults to 100mb, but can be changed with the
2500  * VIPS_DISC_THRESHOLD environment variable or the --vips-disc-threshold
2501  * command-line flag. See vips_image_new_from_file().
2502  *
2503  * Returns: disc threshold in bytes.
2504  */
2505 guint64
vips_get_disc_threshold(void)2506 vips_get_disc_threshold( void )
2507 {
2508 	static gboolean done = FALSE;
2509 	static guint64 threshold;
2510 
2511 	if( !done ) {
2512 		const char *env;
2513 
2514 		done = TRUE;
2515 
2516 		/* 100mb default.
2517 		 */
2518 		threshold = 100 * 1024 * 1024;
2519 
2520 		if( (env = g_getenv( "VIPS_DISC_THRESHOLD" ))
2521 #if ENABLE_DEPRECATED
2522 			|| (env = g_getenv( "IM_DISC_THRESHOLD" ))
2523 #endif
2524 		  )
2525 			threshold = vips__parse_size( env );
2526 
2527 		if( vips__disc_threshold )
2528 			threshold = vips__parse_size( vips__disc_threshold );
2529 
2530 #ifdef DEBUG
2531 		printf( "vips_get_disc_threshold: %zd bytes\n", threshold );
2532 #endif /*DEBUG*/
2533 	}
2534 
2535 	return( threshold );
2536 }
2537 
2538 /**
2539  * vips_image_new_temp_file: (constructor)
2540  * @format: format of file
2541  *
2542  * Make a #VipsImage which, when written to, will create a temporary file on
2543  * disc. The file will be automatically deleted when the image is destroyed.
2544  * @format is something like "&percnt;s.v" for a vips file.
2545  *
2546  * The file is created in the temporary directory. This is set with the
2547  * environment variable TMPDIR. If this is not set, then on Unix systems, vips
2548  * will default to /tmp. On Windows, vips uses GetTempPath() to find the
2549  * temporary directory.
2550  *
2551  * See also: vips_image_new().
2552  *
2553  * Returns: the new #VipsImage, or %NULL on error.
2554  */
2555 VipsImage *
vips_image_new_temp_file(const char * format)2556 vips_image_new_temp_file( const char *format )
2557 {
2558 	char *name;
2559 	VipsImage *image;
2560 
2561 	vips_check_init();
2562 
2563 	if( !(name = vips__temp_name( format )) )
2564 		return( NULL );
2565 
2566 	if( !(image = vips_image_new_mode( name, "w" )) ) {
2567 		g_free( name );
2568 		return( NULL );
2569 	}
2570 
2571 	g_free( name );
2572 
2573 	vips_image_set_delete_on_close( image, TRUE );
2574 
2575 	return( image );
2576 }
2577 
2578 static int
vips_image_write_gen(VipsRegion * or,void * seq,void * a,void * b,gboolean * stop)2579 vips_image_write_gen( VipsRegion *or,
2580 	void *seq, void *a, void *b, gboolean *stop )
2581 {
2582 	VipsRegion *ir = (VipsRegion *) seq;
2583 	VipsRect *r = &or->valid;
2584 
2585 	/*
2586 	printf( "vips_image_write_gen: %p "
2587 		"left = %d, top = %d, width = %d, height = %d\n",
2588 		or->im,
2589 		r->left, r->top, r->width, r->height );
2590 	 */
2591 
2592 	/* Copy with pointers.
2593 	 */
2594 	if( vips_region_prepare( ir, r ) ||
2595 		vips_region_region( or, ir, r, r->left, r->top ) )
2596 		return( -1 );
2597 
2598 	return( 0 );
2599 }
2600 
2601 /**
2602  * vips_image_write: (method)
2603  * @image: image to write
2604  * @out: (out): write to this image
2605  *
2606  * Write @image to @out. Use vips_image_new() and friends to create the
2607  * #VipsImage you want to write to.
2608  *
2609  * See also: vips_image_new(), vips_copy(), vips_image_write_to_file().
2610  *
2611  * Returns: 0 on success, or -1 on error.
2612  */
2613 int
vips_image_write(VipsImage * image,VipsImage * out)2614 vips_image_write( VipsImage *image, VipsImage *out )
2615 {
2616 	/* image needs to stay alive for this call. It can be unreffed during
2617 	 * the generate.
2618 	 */
2619 	g_object_ref( image );
2620 
2621 	if( vips_image_pio_input( image ) ||
2622 		vips_image_pipelinev( out,
2623 			VIPS_DEMAND_STYLE_THINSTRIP, image, NULL ) ) {
2624 		g_object_unref( image );
2625 		return( -1 );
2626 	}
2627 
2628 	if( vips_image_generate( out,
2629 		vips_start_one, vips_image_write_gen, vips_stop_one,
2630 		image, NULL ) ) {
2631 		g_object_unref( image );
2632 		return( -1 );
2633 	}
2634 
2635 	/* If @out is a partial image, we need to unref @image when out is
2636 	 * unreffed.
2637 	 *
2638 	 * If it's not partial, perhaps a file we write to or a memory image,
2639 	 * we need to break any links between @image and @out created by
2640 	 * vips_image_pipelinev().
2641 	 */
2642 	if( vips_image_ispartial( out ) ) {
2643 		vips_object_local( out, image );
2644 	}
2645 	else {
2646 		vips__reorder_clear( out );
2647 		vips__link_break_all( out );
2648 		g_object_unref( image );
2649 	}
2650 
2651 	return( 0 );
2652 }
2653 
2654 /**
2655  * vips_image_write_to_file: (method)
2656  * @image: image to write
2657  * @name: write to this file
2658  * @...: %NULL-terminated list of optional named arguments
2659  *
2660  * Writes @in to @name using the saver recommended by
2661  * vips_foreign_find_save().
2662  *
2663  * Save options may be appended to @filename as "[name=value,...]" or given as
2664  * a NULL-terminated list of name-value pairs at the end of the arguments.
2665  * Options given in the function call override options given in the filename.
2666  *
2667  * See also: vips_image_new_from_file().
2668  *
2669  * Returns: 0 on success, or -1 on error.
2670  */
2671 int
vips_image_write_to_file(VipsImage * image,const char * name,...)2672 vips_image_write_to_file( VipsImage *image, const char *name, ... )
2673 {
2674 	char filename[VIPS_PATH_MAX];
2675 	char option_string[VIPS_PATH_MAX];
2676 	const char *operation_name;
2677 	va_list ap;
2678 	int result;
2679 
2680 	/* Save with the new target API if we can. Fall back to the older
2681 	 * mechanism in case the saver we need has not been converted yet.
2682 	 *
2683 	 * We need to hide any errors from this first phase.
2684 	 */
2685 	vips__filename_split8( name, filename, option_string );
2686 
2687 	vips_error_freeze();
2688 	operation_name = vips_foreign_find_save_target( filename );
2689 	vips_error_thaw();
2690 
2691 	if( operation_name ) {
2692 		VipsTarget *target;
2693 
2694 		if( !(target = vips_target_new_to_file( filename )) )
2695 			return( -1 );
2696 
2697 		va_start( ap, name );
2698 		result = vips_call_split_option_string( operation_name,
2699 			option_string, ap, image, target );
2700 		va_end( ap );
2701 
2702 		VIPS_UNREF( target );
2703 	}
2704 	else if( (operation_name = vips_foreign_find_save( filename )) ) {
2705 		va_start( ap, name );
2706 		result = vips_call_split_option_string( operation_name,
2707 			option_string, ap, image, filename );
2708 		va_end( ap );
2709 	}
2710 	else
2711 		return( -1 );
2712 
2713 	return( result );
2714 }
2715 
2716 /**
2717  * vips_image_write_to_buffer: (method)
2718  * @in: image to write
2719  * @suffix: format to write
2720  * @buf: (array length=size) (element-type guint8) (transfer full): return buffer start here
2721  * @size: (type gsize): return buffer length here
2722  * @...: %NULL-terminated list of optional named arguments
2723  *
2724  * Writes @in to a memory buffer in a format specified by @suffix.
2725  *
2726  * Save options may be appended to @suffix as "[name=value,...]" or given as
2727  * a NULL-terminated list of name-value pairs at the end of the arguments.
2728  * Options given in the function call override options given in the filename.
2729  *
2730  * Currently only TIFF, JPEG and PNG formats are supported.
2731  *
2732  * You can call the various save operations directly if you wish, see
2733  * vips_jpegsave_buffer(), for example.
2734  *
2735  * See also: vips_image_write_to_memory(), vips_image_new_from_buffer().
2736  *
2737  * Returns: 0 on success, -1 on error
2738  */
2739 int
vips_image_write_to_buffer(VipsImage * in,const char * suffix,void ** buf,size_t * size,...)2740 vips_image_write_to_buffer( VipsImage *in,
2741 	const char *suffix, void **buf, size_t *size,
2742 	... )
2743 {
2744 	char filename[VIPS_PATH_MAX];
2745 	char option_string[VIPS_PATH_MAX];
2746 	const char *operation_name;
2747 	VipsBlob *blob;
2748 	va_list ap;
2749 	int result;
2750 
2751 	vips__filename_split8( suffix, filename, option_string );
2752 
2753 	vips_error_freeze();
2754 	operation_name = vips_foreign_find_save_target( filename );
2755 	vips_error_thaw();
2756 
2757 	if( operation_name ) {
2758 		VipsTarget *target;
2759 
2760 		if( !(target = vips_target_new_to_memory()) )
2761 			return( -1 );
2762 
2763 		va_start( ap, size );
2764 		result = vips_call_split_option_string( operation_name,
2765 			option_string, ap, in, target );
2766 		va_end( ap );
2767 
2768 		if( result ) {
2769 			VIPS_UNREF( target );
2770 			return( -1 );
2771 		}
2772 
2773 		g_object_get( target, "blob", &blob, NULL );
2774 		VIPS_UNREF( target );
2775 	}
2776 	else if( (operation_name =
2777 		vips_foreign_find_save_buffer( filename )) ) {
2778 
2779 		va_start( ap, size );
2780 		result = vips_call_split_option_string( operation_name,
2781 			option_string, ap, in, &blob );
2782 		va_end( ap );
2783 
2784 		if( result )
2785 			return( -1 );
2786 	}
2787 	else
2788 		return( -1 );
2789 
2790 	*buf = NULL;
2791 	if( size )
2792 		*size = 0;
2793 
2794 	if( blob ) {
2795 		if( buf ) {
2796 			*buf = VIPS_AREA( blob )->data;
2797 			VIPS_AREA( blob )->free_fn = NULL;
2798 		}
2799 		if( size )
2800 			*size = VIPS_AREA( blob )->length;
2801 
2802 		vips_area_unref( VIPS_AREA( blob ) );
2803 	}
2804 
2805 	return( 0 );
2806 }
2807 
2808 /**
2809  * vips_image_write_to_target: (method)
2810  * @in: image to write
2811  * @suffix: format to write
2812  * @target: target to write to
2813  * @...: %NULL-terminated list of optional named arguments
2814  *
2815  * Writes @in to @output in format @suffix.
2816  *
2817  * Save options may be appended to @suffix as "[name=value,...]" or given as
2818  * a NULL-terminated list of name-value pairs at the end of the arguments.
2819  * Options given in the function call override options given in the filename.
2820  *
2821  * You can call the various save operations directly if you wish, see
2822  * vips_jpegsave_target(), for example.
2823  *
2824  * See also: vips_image_write_to_file().
2825  *
2826  * Returns: 0 on success, -1 on error
2827  */
2828 int
vips_image_write_to_target(VipsImage * in,const char * suffix,VipsTarget * target,...)2829 vips_image_write_to_target( VipsImage *in,
2830 	const char *suffix, VipsTarget *target, ... )
2831 {
2832 	char filename[VIPS_PATH_MAX];
2833 	char option_string[VIPS_PATH_MAX];
2834 	const char *operation_name;
2835 	va_list ap;
2836 	int result;
2837 
2838 	vips__filename_split8( suffix, filename, option_string );
2839 	if( !(operation_name = vips_foreign_find_save_target( filename )) )
2840 		return( -1 );
2841 
2842 	va_start( ap, target );
2843 	result = vips_call_split_option_string( operation_name, option_string,
2844 		ap, in, target );
2845 	va_end( ap );
2846 
2847 	if( result )
2848 		return( -1 );
2849 
2850 	return( 0 );
2851 }
2852 
2853 /**
2854  * vips_image_write_to_memory: (method)
2855  * @in: image to write
2856  * @size: return buffer length here
2857  *
2858  * Writes @in to memory as a simple, unformatted C-style array.
2859  *
2860  * The caller is responsible for freeing this memory with g_free().
2861  *
2862  * See also: vips_image_write_to_buffer().
2863  *
2864  * Returns: (array length=size) (element-type guint8) (transfer full): return buffer start here
2865  */
2866 void *
vips_image_write_to_memory(VipsImage * in,size_t * size_out)2867 vips_image_write_to_memory( VipsImage *in, size_t *size_out )
2868 {
2869 	void *buf;
2870 	size_t size;
2871 	VipsImage *x;
2872 
2873 	size = VIPS_IMAGE_SIZEOF_IMAGE( in );
2874 	if( !(buf = g_try_malloc( size )) ) {
2875 		vips_error( "vips_image_write_to_memory",
2876 			_( "out of memory --- size == %dMB" ),
2877 			(int) (size / (1024.0 * 1024.0))  );
2878 		g_warning( _( "out of memory --- size == %dMB" ),
2879 			(int) (size / (1024.0 * 1024.0))  );
2880 		return( NULL );
2881 	}
2882 
2883 	x = vips_image_new_from_memory( buf, size,
2884 		in->Xsize, in->Ysize, in->Bands, in->BandFmt );
2885 	if( vips_image_write( in, x ) ) {
2886 		g_object_unref( x );
2887 		g_free( buf );
2888 		return( NULL );
2889 	}
2890 	g_object_unref( x );
2891 
2892 	if( size_out )
2893 		*size_out = size;
2894 
2895 	return( buf );
2896 }
2897 
2898 /**
2899  * vips_image_decode: (method)
2900  * @in: image to decode
2901  * @out: (out): write to this image
2902  *
2903  * A convenience function to unpack to a format that we can compute with.
2904  * @out.coding is always #VIPS_CODING_NONE.
2905  *
2906  * This unpacks LABQ to plain LAB. Use vips_LabQ2LabS() for a bit more speed
2907  * if you need it.
2908  *
2909  * See also: vips_image_encode(), vips_LabQ2Lab(), vips_rad2float().
2910  *
2911  * Returns: 0 on success, or -1 on error.
2912  */
2913 int
vips_image_decode(VipsImage * in,VipsImage ** out)2914 vips_image_decode( VipsImage *in, VipsImage **out )
2915 {
2916 	/* Keep in sync with vips__vector_to_ink().
2917 	 */
2918 	if( in->Coding == VIPS_CODING_LABQ ) {
2919 		if( vips_LabQ2Lab( in, out, NULL ) )
2920 			return( -1 );
2921 	}
2922 	else if( in->Coding == VIPS_CODING_RAD ) {
2923 		if( vips_rad2float( in, out, NULL ) )
2924 			return( -1 );
2925 	}
2926 	else {
2927 		if( vips_copy( in, out, NULL ) )
2928 			return( -1 );
2929 	}
2930 
2931 	return( 0 );
2932 }
2933 
2934 /**
2935  * vips_image_decode_predict: (method)
2936  * @in: image to decode
2937  * @bands: (out): predict bands here
2938  * @format: (out): predict format here
2939  *
2940  * We often need to know what an image will decode to without actually
2941  * decoding it, for example, in arg checking.
2942  *
2943  * See also: vips_image_decode().
2944  */
2945 int
vips_image_decode_predict(VipsImage * in,int * out_bands,VipsBandFormat * out_format)2946 vips_image_decode_predict( VipsImage *in,
2947 	int *out_bands, VipsBandFormat *out_format )
2948 {
2949 	VipsBandFormat format;
2950 	int bands;
2951 
2952 	if( in->Coding == VIPS_CODING_LABQ ) {
2953 		bands = 3;
2954 		format = VIPS_FORMAT_FLOAT;
2955 	}
2956 	else if( in->Coding == VIPS_CODING_RAD ) {
2957 		bands = 3;
2958 		format = VIPS_FORMAT_FLOAT;
2959 	}
2960 	else {
2961 		bands = in->Bands;
2962 		format = in->BandFmt;
2963 	}
2964 
2965 	if( out_bands )
2966 		*out_bands = bands;
2967 	if( out_format )
2968 		*out_format = format;
2969 
2970 	return( 0 );
2971 }
2972 
2973 /**
2974  * vips_image_encode: (method)
2975  * @in: image to encode
2976  * @out: (out): write to this image
2977  * @coding: coding to apply
2978  *
2979  * A convenience function to pack to a coding. The inverse of
2980  * vips_image_decode().
2981  *
2982  * See also: vips_image_decode().
2983  *
2984  * Returns: 0 on success, or -1 on error.
2985  */
2986 int
vips_image_encode(VipsImage * in,VipsImage ** out,VipsCoding coding)2987 vips_image_encode( VipsImage *in, VipsImage **out, VipsCoding coding )
2988 {
2989 	if( coding == VIPS_CODING_LABQ ) {
2990 		if( vips_Lab2LabQ( in, out, NULL ) )
2991 			return( -1 );
2992 	}
2993 	else if( coding == VIPS_CODING_RAD ) {
2994 		if( vips_float2rad( in, out, NULL ) )
2995 			return( -1 );
2996 	}
2997 	else {
2998 		if( vips_copy( in, out, NULL ) )
2999 			return( -1 );
3000 	}
3001 
3002 	return( 0 );
3003 }
3004 
3005 /**
3006  * vips_image_isMSBfirst: (method)
3007  * @image: image to test
3008  *
3009  * Return %TRUE if @image is in most-significant-
3010  * byte first form. This is the byte order used on the SPARC
3011  * architecture and others.
3012  */
3013 gboolean
vips_image_isMSBfirst(VipsImage * image)3014 vips_image_isMSBfirst( VipsImage *image )
3015 {
3016 	if( image->magic == VIPS_MAGIC_SPARC )
3017 		return( 1 );
3018 	else
3019 		return( 0 );
3020 }
3021 
3022 /**
3023  * vips_image_isfile: (method)
3024  * @image: image to test
3025  *
3026  * Return %TRUE if @image represents a file on disc in some way.
3027  */
3028 gboolean
vips_image_isfile(VipsImage * image)3029 vips_image_isfile( VipsImage *image )
3030 {
3031 	switch( image->dtype ) {
3032 	case VIPS_IMAGE_MMAPIN:
3033 	case VIPS_IMAGE_MMAPINRW:
3034 	case VIPS_IMAGE_OPENOUT:
3035 	case VIPS_IMAGE_OPENIN:
3036 		return( 1 );
3037 
3038 	case VIPS_IMAGE_PARTIAL:
3039 	case VIPS_IMAGE_SETBUF:
3040 	case VIPS_IMAGE_SETBUF_FOREIGN:
3041 	case VIPS_IMAGE_NONE:
3042 		return( 0 );
3043 
3044 	default:
3045 		g_assert( FALSE );
3046 		return( 0 );
3047 	}
3048 }
3049 
3050 /**
3051  * vips_image_ispartial: (method)
3052  * @image: image to test
3053  *
3054  * Return %TRUE if @im represents a partial image (a delayed calculation).
3055  */
3056 gboolean
vips_image_ispartial(VipsImage * image)3057 vips_image_ispartial( VipsImage *image )
3058 {
3059 	if( image->dtype == VIPS_IMAGE_PARTIAL )
3060 		return( 1 );
3061 	else
3062 		return( 0 );
3063 }
3064 
3065 /**
3066  * vips_image_hasalpha: (method)
3067  * @image: image to check
3068  *
3069  * Look at an image's interpretation and see if it has extra alpha bands. For
3070  * example, a 4-band #VIPS_INTERPRETATION_sRGB would, but a six-band
3071  * #VIPS_INTERPRETATION_MULTIBAND would not.
3072  *
3073  * Return %TRUE if @image has an alpha channel.
3074  */
3075 gboolean
vips_image_hasalpha(VipsImage * image)3076 vips_image_hasalpha( VipsImage *image )
3077 {
3078 	/* The result of hasalpha is used to turn on things like
3079 	 * premultiplication, so we are rather conservative about when we
3080 	 * signal this. We don't want to premultiply things that should not be
3081 	 * premultiplied.
3082 	 */
3083 	switch( image->Type ) {
3084 	case VIPS_INTERPRETATION_B_W:
3085 	case VIPS_INTERPRETATION_GREY16:
3086 		return( image->Bands > 1 );
3087 
3088 	case VIPS_INTERPRETATION_RGB:
3089 	case VIPS_INTERPRETATION_CMC:
3090 	case VIPS_INTERPRETATION_LCH:
3091 	case VIPS_INTERPRETATION_LABS:
3092 	case VIPS_INTERPRETATION_sRGB:
3093 	case VIPS_INTERPRETATION_YXY:
3094 	case VIPS_INTERPRETATION_XYZ:
3095 	case VIPS_INTERPRETATION_LAB:
3096 	case VIPS_INTERPRETATION_RGB16:
3097 	case VIPS_INTERPRETATION_scRGB:
3098 	case VIPS_INTERPRETATION_HSV:
3099 		return( image->Bands > 3 );
3100 
3101 	case VIPS_INTERPRETATION_CMYK:
3102 		return( image->Bands > 4 );
3103 
3104 	default:
3105 		/* We can't really infer anything about bands from things like
3106 		 * HISTOGRAM or FOURIER.
3107 		 */
3108 		return( FALSE );
3109 	}
3110 }
3111 
3112 /**
3113  * vips_image_write_prepare: (method)
3114  * @image: image to prepare
3115  *
3116  * Call this after setting header fields (width, height, and so on) to
3117  * allocate resources ready for writing.
3118  *
3119  * Normally this function is called for you by vips_image_generate() or
3120  * vips_image_write_line(). You will need to call it yourself if you plan to
3121  * write directly to the ->data member of a memory image.
3122  *
3123  * Returns: 0 on success, or -1 on error.
3124  */
3125 int
vips_image_write_prepare(VipsImage * image)3126 vips_image_write_prepare( VipsImage *image )
3127 {
3128 	g_assert( vips_object_sanity( VIPS_OBJECT( image ) ) );
3129 
3130 	if( image->Xsize <= 0 ||
3131 		image->Ysize <= 0 ||
3132 		image->Bands <= 0 ) {
3133 		vips_error( "VipsImage", "%s", _( "bad dimensions" ) );
3134 		return( -1 );
3135 	}
3136 
3137 	/* We don't use this, but make sure it's set in case any old programs
3138 	 * are expecting it.
3139 	 */
3140 	image->Bbits = vips_format_sizeof( image->BandFmt ) << 3;
3141 
3142 	if( image->dtype == VIPS_IMAGE_PARTIAL ) {
3143 		VIPS_DEBUG_MSG( "vips_image_write_prepare: "
3144 			"old-style output for %s\n", image->filename );
3145 
3146 		image->dtype = VIPS_IMAGE_SETBUF;
3147 	}
3148 
3149 	switch( image->dtype ) {
3150 	case VIPS_IMAGE_MMAPINRW:
3151 	case VIPS_IMAGE_SETBUF_FOREIGN:
3152 		break;
3153 
3154 	case VIPS_IMAGE_SETBUF:
3155 		if( !image->data &&
3156 			!(image->data = vips_tracked_malloc(
3157 				VIPS_IMAGE_SIZEOF_IMAGE( image ))) )
3158 			return( -1 );
3159 
3160 		break;
3161 
3162 	case VIPS_IMAGE_OPENOUT:
3163 		if( vips_image_open_output( image ) )
3164 			return( -1 );
3165 
3166 		break;
3167 
3168 	default:
3169 		vips_error( "VipsImage", "%s", _( "bad image descriptor" ) );
3170 		return( -1 );
3171 	}
3172 
3173 	return( 0 );
3174 }
3175 
3176 /**
3177  * vips_image_write_line: (method)
3178  * @image: image to write to
3179  * @ypos: vertical position of scan-line to write
3180  * @linebuffer: scanline of pixels
3181  *
3182  * Write a line of pixels to an image. This function must be called repeatedly
3183  * with @ypos increasing from 0 to #VipsImage::height .
3184  * @linebuffer must be VIPS_IMAGE_SIZEOF_LINE() bytes long.
3185  *
3186  * See also: vips_image_generate().
3187  *
3188  * Returns: 0 on success, or -1 on error.
3189  */
3190 int
vips_image_write_line(VipsImage * image,int ypos,VipsPel * linebuffer)3191 vips_image_write_line( VipsImage *image, int ypos, VipsPel *linebuffer )
3192 {
3193 	int linesize = VIPS_IMAGE_SIZEOF_LINE( image );
3194 
3195 	/* Is this the start of eval?
3196 	 */
3197 	if( ypos == 0 ) {
3198 		if( vips__image_wio_output( image ) )
3199 			return( -1 );
3200 
3201 		/* Always clear kill before we start looping. See the
3202 		 * call to vips_image_iskilled() below.
3203 		 */
3204 		vips_image_set_kill( image, FALSE );
3205 		vips_image_write_prepare( image );
3206 		vips_image_preeval( image );
3207 	}
3208 
3209 	/* Possible cases for output: FILE or SETBUF.
3210 	 */
3211 	switch( image->dtype ) {
3212 	case VIPS_IMAGE_SETBUF:
3213 	case VIPS_IMAGE_SETBUF_FOREIGN:
3214 		memcpy( VIPS_IMAGE_ADDR( image, 0, ypos ),
3215 			linebuffer, linesize );
3216 		break;
3217 
3218 	case VIPS_IMAGE_OPENOUT:
3219 		/* Don't use ypos for this.
3220 		 */
3221 		if( vips__write( image->fd, linebuffer, linesize ) )
3222 			return( -1 );
3223 		break;
3224 
3225 	default:
3226 		vips_error( "VipsImage",
3227 			_( "unable to output to a %s image" ),
3228 			vips_enum_string( VIPS_TYPE_IMAGE_TYPE,
3229 				image->dtype ) );
3230 		return( -1 );
3231 	}
3232 
3233 	/* Trigger evaluation callbacks for this image.
3234 	 */
3235 	vips_image_eval( image, ypos * image->Xsize );
3236 	if( vips_image_iskilled( image ) )
3237 		return( -1 );
3238 
3239 	/* Is this the end of eval?
3240 	 */
3241 	if( ypos == image->Ysize - 1 ) {
3242 		vips_image_posteval( image );
3243 		if( vips_image_written( image ) )
3244 			return( -1 );
3245 	}
3246 
3247 	return( 0 );
3248 }
3249 
3250 /* Rewind an output file. VIPS images only.
3251  */
3252 static int
vips_image_rewind_output(VipsImage * image)3253 vips_image_rewind_output( VipsImage *image )
3254 {
3255 	int fd;
3256 
3257 	g_assert( image->dtype == VIPS_IMAGE_OPENOUT );
3258 
3259 #ifdef DEBUG_IO
3260 	printf( "vips_image_rewind_output: %s\n", image->filename );
3261 #endif/*DEBUG_IO*/
3262 
3263 	/* We want to keep the fd across rewind.
3264 	 *
3265 	 * On Windows, we open temp files with _O_TEMPORARY. We mustn't close
3266 	 * the file since this will delete it.
3267 	 *
3268 	 * We could open the file again to keep a reference to it alive, but
3269 	 * this is also problematic on Windows.
3270 	 */
3271 	fd = image->fd;
3272 	image->fd = -1;
3273 
3274 	/* Free any resources the image holds and reset to a base
3275 	 * state.
3276 	 */
3277 	vips_object_rewind( VIPS_OBJECT( image ) );
3278 
3279 	/* And reopen ... recurse to get a mmaped image.
3280 	 *
3281 	 * We use "v" mode to get it opened as a vips image, bypassing the
3282 	 * file type checks. They will fail on Windows because you can't open
3283 	 * fds more than once.
3284 	 */
3285 	image->fd = fd;
3286 	g_object_set( image,
3287 		"mode", "v",
3288 		NULL );
3289 	if( vips_object_build( VIPS_OBJECT( image ) ) ) {
3290 		vips_error( "VipsImage",
3291 			_( "auto-rewind for %s failed" ),
3292 			image->filename );
3293 		return( -1 );
3294 	}
3295 
3296 	/* Now we've finished writing and reopened as read, we can
3297 	 * delete-on-close.
3298 	 *
3299 	 * On *nix-like systems, this will unlink the file from the
3300 	 * filesystem and when we exit, for whatever reason, the file
3301 	 * we be reclaimed.
3302 	 *
3303 	 * On Windows this will fail because the file is open and you can't
3304 	 * delete open files. However, on Windows we set _O_TEMPORARY, so the
3305 	 * file will be deleted when the fd is finally closed.
3306 	 */
3307 	vips_image_delete( image );
3308 
3309 	return( 0 );
3310 }
3311 
3312 /**
3313  * vips_image_copy_memory: (method)
3314  * @image: image to copy to a memory buffer
3315  *
3316  * Make an image which is an area of memory.
3317  *
3318  * If @image is already a memory buffer, just ref and return. If it's a file on
3319  * disc or a partial, allocate memory and copy the image to it.
3320  *
3321  * This operation is thread-safe, unlike vips_image_wio_input().
3322  *
3323  * If you are sure that @image is not shared with another thread (perhaps you
3324  * have made it yourself), use vips_image_wio_input() instead.
3325  *
3326  * See also: vips_image_wio_input().
3327  *
3328  * Returns: (transfer full): the new #VipsImage, or %NULL on error.
3329  */
3330 VipsImage *
vips_image_copy_memory(VipsImage * image)3331 vips_image_copy_memory( VipsImage *image )
3332 {
3333 	VipsImage *new;
3334 
3335 	switch( image->dtype ) {
3336 	case VIPS_IMAGE_SETBUF:
3337 	case VIPS_IMAGE_SETBUF_FOREIGN:
3338 	case VIPS_IMAGE_MMAPIN:
3339 	case VIPS_IMAGE_MMAPINRW:
3340 		/* Can read from all these, in principle anyway.
3341 		 */
3342 		new = image;
3343 		g_object_ref( new );
3344 		break;
3345 
3346 	case VIPS_IMAGE_OPENOUT:
3347 	case VIPS_IMAGE_OPENIN:
3348 	case VIPS_IMAGE_PARTIAL:
3349 		new = vips_image_new_memory();
3350 		if( vips_image_write( image, new ) ) {
3351 			g_object_unref( new );
3352 			return( NULL );
3353 		}
3354 		break;
3355 
3356 	default:
3357 		vips_error( "vips_image_copy_memory",
3358 			"%s", _( "image not readable" ) );
3359 		return( NULL );
3360 	}
3361 
3362 	return( new );
3363 }
3364 
3365 /**
3366  * vips_image_wio_input: (method)
3367  * @image: image to transform
3368  *
3369  * Check that an image is readable via the VIPS_IMAGE_ADDR() macro, that is,
3370  * that the entire image is in memory and all pixels can be read with
3371  * VIPS_IMAGE_ADDR().  If it
3372  * isn't, try to transform it so that VIPS_IMAGE_ADDR() can work.
3373  *
3374  * Since this function modifies @image, it is not thread-safe. Only call it on
3375  * images which you are sure have not been shared with another thread. If the
3376  * image might have been shared, use the less efficient
3377  * vips_image_copy_memory() instead.
3378  *
3379  * See also: vips_image_copy_memory(), vips_image_pio_input(),
3380  * vips_image_inplace(), VIPS_IMAGE_ADDR().
3381  *
3382  * Returns: 0 on succeess, or -1 on error.
3383  */
3384 int
vips_image_wio_input(VipsImage * image)3385 vips_image_wio_input( VipsImage *image )
3386 {
3387 	VipsImage *t1;
3388 
3389 	g_assert( vips_object_sanity( VIPS_OBJECT( image ) ) );
3390 
3391 #ifdef DEBUG_IO
3392 	printf( "vips_image_wio_input: wio input for %s\n",
3393 		image->filename );
3394 #endif/*DEBUG_IO*/
3395 
3396 	switch( image->dtype ) {
3397 	case VIPS_IMAGE_SETBUF:
3398 	case VIPS_IMAGE_SETBUF_FOREIGN:
3399 		/* Should have been written to.
3400 		 */
3401 		if( !image->data ) {
3402 			vips_error( "vips_image_wio_input",
3403 				"%s", _( "no image data" ) );
3404 			return( -1 );
3405 		}
3406 
3407 		break;
3408 
3409 	case VIPS_IMAGE_MMAPIN:
3410 	case VIPS_IMAGE_MMAPINRW:
3411 		/* Can read from all these, in principle anyway.
3412 		 */
3413 		break;
3414 
3415 	case VIPS_IMAGE_PARTIAL:
3416 #ifdef DEBUG_IO
3417 		printf( "vips_image_wio_input: "
3418 			"converting partial image to WIO\n" );
3419 #endif/*DEBUG_IO*/
3420 
3421 		/* Change to VIPS_IMAGE_SETBUF. First, make a memory
3422 		 * buffer and copy into that.
3423 		 */
3424 		t1 = vips_image_new_memory();
3425 		if( vips_image_write( image, t1 ) ) {
3426 			g_object_unref( t1 );
3427 			return( -1 );
3428 		}
3429 
3430 		/* Copy new stuff in. We can't unref and free stuff, as this
3431 		 * would kill of lots of regions and cause dangling pointers
3432 		 * elsewhere.
3433 		 */
3434 		image->dtype = VIPS_IMAGE_SETBUF;
3435 		image->data = t1->data;
3436 		t1->data = NULL;
3437 
3438 		/* Close temp image.
3439 		 */
3440 		g_object_unref( t1 );
3441 
3442 		/* We need to zap any start/gen/stop callbacks. If we don't,
3443 		 * calling vips_region_prepare_to() later to read from this
3444 		 * image will fail, since it will think it needs to create the
3445 		 * image, not read from it.
3446 		 */
3447 		image->start_fn = NULL;
3448 		image->generate_fn = NULL;
3449 		image->stop_fn = NULL;
3450 		image->client1 = NULL;
3451 		image->client2 = NULL;
3452 
3453 		/* ... and that may confuse any regions which are trying to
3454 		 * generate from this image.
3455 		 */
3456 		if( image->regions )
3457 			g_warning( "rewinding image with active regions" );
3458 
3459 		break;
3460 
3461 	case VIPS_IMAGE_OPENIN:
3462 #ifdef DEBUG_IO
3463 		printf( "vips_image_wio_input: "
3464 			"converting openin image for wio input\n" );
3465 #endif/*DEBUG_IO*/
3466 
3467 		/* just mmap() the whole thing.
3468 		 */
3469 		if( vips_mapfile( image ) )
3470 			return( -1 );
3471 		image->data = (VipsPel *) image->baseaddr +
3472 			image->sizeof_header;
3473 		image->dtype = VIPS_IMAGE_MMAPIN;
3474 
3475 		break;
3476 
3477 	case VIPS_IMAGE_OPENOUT:
3478 		/* Close file down and reopen as input. I guess this will only
3479 		 * work for vips files?
3480 		 */
3481 		if( vips_image_rewind_output( image ) ||
3482 			vips_image_wio_input( image ) )
3483 			return( -1 );
3484 
3485 		break;
3486 
3487 	default:
3488 		vips_error( "vips_image_wio_input",
3489 			"%s", _( "image not readable" ) );
3490 		return( -1 );
3491 	}
3492 
3493 	return( 0 );
3494 }
3495 
3496 int
vips__image_wio_output(VipsImage * image)3497 vips__image_wio_output( VipsImage *image )
3498 {
3499 #ifdef DEBUG_IO
3500 	printf( "vips__image_wio_output: WIO output for %s\n",
3501 		image->filename );
3502 #endif/*DEBUG_IO*/
3503 
3504 	switch( image->dtype ) {
3505 	case VIPS_IMAGE_PARTIAL:
3506 		/* Make sure nothing is attached.
3507 		 */
3508 		if( image->generate_fn ) {
3509 			vips_error( "vips__image_wio_output",
3510 				"%s", _( "image already written" ) );
3511 			return( -1 );
3512 		}
3513 
3514 		/* Cannot do old-style write to PARTIAL. Turn to SETBUF.
3515 		 */
3516 		image->dtype = VIPS_IMAGE_SETBUF;
3517 
3518 		break;
3519 
3520 	case VIPS_IMAGE_SETBUF:
3521 	case VIPS_IMAGE_OPENOUT:
3522 	case VIPS_IMAGE_SETBUF_FOREIGN:
3523 		/* Can write to this ok.
3524 		 *
3525 		 * We used to check that ->data was null and warn about
3526 		 * writing twice, but we no longer insist that this is called
3527 		 * before vips_image_write_prepare(), so we can't do that any
3528 		 * more.
3529 		 */
3530 		break;
3531 
3532 	default:
3533 		vips_error( "vips__image_wio_output",
3534 			"%s", _( "image not writeable" ) );
3535 		return( -1 );
3536 	}
3537 
3538 	return( 0 );
3539 }
3540 
3541 /**
3542  * vips_image_inplace: (method)
3543  * @image: image to make read-write
3544  *
3545  * Gets @image ready for an in-place operation, such as vips_draw_circle().
3546  * After calling this function you can both read and write the image with
3547  * VIPS_IMAGE_ADDR().
3548  *
3549  * This method is called for you by the base class of the draw operations,
3550  * there's no need to call it yourself.
3551  *
3552  * Since this function modifies @image, it is not thread-safe. Only call it on
3553  * images which you are sure have not been shared with another thread.
3554  * All in-place operations are inherently not thread-safe, so you need to take
3555  * great care in any case.
3556  *
3557  * See also: vips_draw_circle(), vips_image_wio_input().
3558  *
3559  * Returns: 0 on succeess, or -1 on error.
3560  */
3561 int
vips_image_inplace(VipsImage * image)3562 vips_image_inplace( VipsImage *image )
3563 {
3564 	/* Do an vips_image_wio_input(). This will rewind, generate, etc.
3565 	 */
3566 	if( vips_image_wio_input( image ) )
3567 		return( -1 );
3568 
3569 	/* Look at the type.
3570 	 */
3571 	switch( image->dtype ) {
3572 	case VIPS_IMAGE_SETBUF:
3573 	case VIPS_IMAGE_SETBUF_FOREIGN:
3574 	case VIPS_IMAGE_MMAPINRW:
3575 		/* No action necessary.
3576 		 */
3577 		break;
3578 
3579 	case VIPS_IMAGE_MMAPIN:
3580 		/* Try to remap read-write.
3581 		 */
3582 		if( vips_remapfilerw( image ) )
3583 			return( -1 );
3584 
3585 		break;
3586 
3587 	default:
3588 		vips_error( "vips_image_inplace",
3589 			"%s", _( "bad file type" ) );
3590 		return( -1 );
3591 	}
3592 
3593 	/* This image is about to be changed (probably). Make sure it's not
3594 	 * in cache.
3595 	 */
3596 	vips_image_invalidate_all( image );
3597 
3598 	return( 0 );
3599 }
3600 
3601 /**
3602  * vips_image_pio_input: (method)
3603  * @image: image to check
3604  *
3605  * Check that an image is readable with vips_region_prepare() and friends.
3606  * If it isn't, try to transform the image so that vips_region_prepare() can
3607  * work.
3608  *
3609  * See also: vips_image_pio_output(), vips_region_prepare().
3610  *
3611  * Returns: 0 on succeess, or -1 on error.
3612  */
3613 int
vips_image_pio_input(VipsImage * image)3614 vips_image_pio_input( VipsImage *image )
3615 {
3616 	g_assert( vips_object_sanity( VIPS_OBJECT( image ) ) );
3617 
3618 #ifdef DEBUG_IO
3619 	printf( "vips_image_pio_input: enabling partial input for %s\n",
3620 		image->filename );
3621 #endif /*DEBUG_IO*/
3622 
3623 	switch( image->dtype ) {
3624 	case VIPS_IMAGE_SETBUF:
3625 	case VIPS_IMAGE_SETBUF_FOREIGN:
3626 		/* Should have been written to.
3627 		 */
3628 		if( !image->data ) {
3629 			vips_error( "vips_image_pio_input",
3630 				"%s", _( "no image data" ) );
3631 			return( -1 );
3632 		}
3633 
3634 		/* Should be no generate functions now.
3635 		 */
3636 		image->start_fn = NULL;
3637 		image->generate_fn = NULL;
3638 		image->stop_fn = NULL;
3639 
3640 		break;
3641 
3642 	case VIPS_IMAGE_PARTIAL:
3643 		/* Should have had generate functions attached.
3644 		 */
3645 		if( !image->generate_fn ) {
3646 			vips_error( "vips_image_pio_input",
3647 				"%s", _( "no image data" ) );
3648 			return( -1 );
3649 		}
3650 
3651 		break;
3652 
3653 	case VIPS_IMAGE_MMAPIN:
3654 	case VIPS_IMAGE_MMAPINRW:
3655 	case VIPS_IMAGE_OPENIN:
3656 		break;
3657 
3658 	case VIPS_IMAGE_OPENOUT:
3659 
3660 		/* Free any resources the image holds and reset to a base
3661 		 * state.
3662 		 */
3663 		if( vips_image_rewind_output( image ) )
3664 			return( -1 );
3665 
3666 		break;
3667 
3668 	default:
3669 		vips_error( "vips_image_pio_input",
3670 			"%s", _( "image not readable" ) );
3671 		return( -1 );
3672 	}
3673 
3674 	return( 0 );
3675 }
3676 
3677 /**
3678  * vips_image_pio_output: (method)
3679  * @image: image to check
3680  *
3681  * Check that an image is writeable with vips_image_generate(). If it isn't,
3682  * try to transform the image so that vips_image_generate() can work.
3683  *
3684  * See also: vips_image_pio_input().
3685  *
3686  * Returns: 0 on succeess, or -1 on error.
3687  */
3688 int
vips_image_pio_output(VipsImage * image)3689 vips_image_pio_output( VipsImage *image )
3690 {
3691 #ifdef DEBUG_IO
3692 	printf( "vips_image_pio_output: enabling partial output for %s\n",
3693 		image->filename );
3694 #endif /*DEBUG_IO*/
3695 
3696 	switch( image->dtype ) {
3697 	case VIPS_IMAGE_SETBUF:
3698 		if( image->data ) {
3699 			vips_error( "vips_image_pio_output",
3700 				"%s", _( "image already written" ) );
3701 			return( -1 );
3702 		}
3703 
3704 		break;
3705 
3706 	case VIPS_IMAGE_PARTIAL:
3707 		if( image->generate_fn ) {
3708 			vips_error( "vips_image_pio_output",
3709 				"%s", _( "image already written" ) );
3710 			return( -1 );
3711 		}
3712 
3713 		break;
3714 
3715 	case VIPS_IMAGE_OPENOUT:
3716 	case VIPS_IMAGE_SETBUF_FOREIGN:
3717 		break;
3718 
3719 	default:
3720 		vips_error( "vips_image_pio_output",
3721 			"%s", _( "image not writeable" ) );
3722 		return( -1 );
3723 	}
3724 
3725 	return( 0 );
3726 }
3727 
3728 /**
3729  * vips_band_format_isint:
3730  * @format: format to test
3731  *
3732  * Return %TRUE if @format is one of the integer types.
3733  */
3734 gboolean
vips_band_format_isint(VipsBandFormat format)3735 vips_band_format_isint( VipsBandFormat format )
3736 {
3737 	switch( format ) {
3738 	case VIPS_FORMAT_UCHAR:
3739 	case VIPS_FORMAT_CHAR:
3740 	case VIPS_FORMAT_USHORT:
3741 	case VIPS_FORMAT_SHORT:
3742 	case VIPS_FORMAT_UINT:
3743 	case VIPS_FORMAT_INT:
3744 		return( TRUE );
3745 
3746 	case VIPS_FORMAT_FLOAT:
3747 	case VIPS_FORMAT_DOUBLE:
3748 	case VIPS_FORMAT_COMPLEX:
3749 	case VIPS_FORMAT_DPCOMPLEX:
3750 		return( FALSE );
3751 
3752 	default:
3753 		g_assert_not_reached();
3754 		return( FALSE );
3755 	}
3756 }
3757 
3758 /**
3759  * vips_band_format_isuint:
3760  * @format: format to test
3761  *
3762  * Return %TRUE if @format is one of the unsigned integer types.
3763  */
3764 gboolean
vips_band_format_isuint(VipsBandFormat format)3765 vips_band_format_isuint( VipsBandFormat format )
3766 {
3767 	switch( format ) {
3768 	case VIPS_FORMAT_UCHAR:
3769 	case VIPS_FORMAT_USHORT:
3770 	case VIPS_FORMAT_UINT:
3771 		return( TRUE );
3772 
3773 	case VIPS_FORMAT_INT:
3774 	case VIPS_FORMAT_SHORT:
3775 	case VIPS_FORMAT_CHAR:
3776 	case VIPS_FORMAT_FLOAT:
3777 	case VIPS_FORMAT_DOUBLE:
3778 	case VIPS_FORMAT_COMPLEX:
3779 	case VIPS_FORMAT_DPCOMPLEX:
3780 		return( FALSE );
3781 
3782 	default:
3783 		g_assert_not_reached();
3784 		return( FALSE );
3785 	}
3786 }
3787 
3788 /**
3789  * vips_band_format_is8bit:
3790  * @format: format to test
3791  *
3792  * Return %TRUE if @format is uchar or schar.
3793  */
3794 gboolean
vips_band_format_is8bit(VipsBandFormat format)3795 vips_band_format_is8bit( VipsBandFormat format )
3796 {
3797 	switch( format ) {
3798 	case VIPS_FORMAT_UCHAR:
3799 	case VIPS_FORMAT_CHAR:
3800 		return( TRUE );
3801 
3802 	case VIPS_FORMAT_USHORT:
3803 	case VIPS_FORMAT_SHORT:
3804 	case VIPS_FORMAT_UINT:
3805 	case VIPS_FORMAT_INT:
3806 	case VIPS_FORMAT_FLOAT:
3807 	case VIPS_FORMAT_DOUBLE:
3808 	case VIPS_FORMAT_COMPLEX:
3809 	case VIPS_FORMAT_DPCOMPLEX:
3810 		return( FALSE );
3811 
3812 	default:
3813 		g_assert_not_reached();
3814 		return( FALSE );
3815 	}
3816 }
3817 
3818 /**
3819  * vips_band_format_isfloat:
3820  * @format: format to test
3821  *
3822  * Return %TRUE if @format is one of the float types.
3823  */
3824 gboolean
vips_band_format_isfloat(VipsBandFormat format)3825 vips_band_format_isfloat( VipsBandFormat format )
3826 {
3827 	switch( format ) {
3828 	case VIPS_FORMAT_FLOAT:
3829 	case VIPS_FORMAT_DOUBLE:
3830 		return( TRUE );
3831 
3832 	case VIPS_FORMAT_UCHAR:
3833 	case VIPS_FORMAT_CHAR:
3834 	case VIPS_FORMAT_USHORT:
3835 	case VIPS_FORMAT_SHORT:
3836 	case VIPS_FORMAT_UINT:
3837 	case VIPS_FORMAT_INT:
3838 	case VIPS_FORMAT_COMPLEX:
3839 	case VIPS_FORMAT_DPCOMPLEX:
3840 		return( FALSE );
3841 
3842 	default:
3843 		g_assert_not_reached();
3844 		return( FALSE );
3845 	}
3846 }
3847 
3848 /**
3849  * vips_band_format_iscomplex:
3850  * @format: format to test
3851  *
3852  * Return %TRUE if @fmt is one of the complex types.
3853  */
3854 gboolean
vips_band_format_iscomplex(VipsBandFormat format)3855 vips_band_format_iscomplex( VipsBandFormat format )
3856 {
3857 	switch( format ) {
3858 	case VIPS_FORMAT_COMPLEX:
3859 	case VIPS_FORMAT_DPCOMPLEX:
3860 		return( TRUE );
3861 
3862 	case VIPS_FORMAT_UCHAR:
3863 	case VIPS_FORMAT_CHAR:
3864 	case VIPS_FORMAT_USHORT:
3865 	case VIPS_FORMAT_SHORT:
3866 	case VIPS_FORMAT_UINT:
3867 	case VIPS_FORMAT_INT:
3868 	case VIPS_FORMAT_FLOAT:
3869 	case VIPS_FORMAT_DOUBLE:
3870 		return( FALSE );
3871 
3872 	default:
3873 		g_assert_not_reached();
3874 		return( FALSE );
3875 	}
3876 }
3877 
3878 /**
3879  * vips_image_free_buffer:
3880  * @image: the image that contains the buffer
3881  * @buffer: the orignal buffer that was stolen
3882  *
3883  * Free the externally allocated buffer found in the input image. This function
3884  * is intended to be used with g_signal_connect.
3885  */
3886 void
vips_image_free_buffer(VipsImage * image,void * buffer)3887 vips_image_free_buffer( VipsImage *image, void *buffer )
3888 {
3889 	free( buffer );
3890 }
3891 
3892 /* Handy for debugging: view an image in nip2.
3893  */
3894 int
vips__view_image(VipsImage * image)3895 vips__view_image( VipsImage *image )
3896 {
3897 	VipsArrayImage *array;
3898 	int result;
3899 
3900 	array = vips_array_image_new( &image, 1 );
3901 	result = vips_system( "nip2 %s",
3902 		"in", array,
3903 		"in-format", "%s.v",
3904 		NULL );
3905 	vips_area_unref( VIPS_AREA( array ) );
3906 
3907 	return( result );
3908 }
3909