• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Raster file routines for CUPS.
3  *
4  * Copyright 2007-2018 by Apple Inc.
5  * Copyright 1997-2006 by Easy Software Products.
6  *
7  * This file is part of the CUPS Imaging library.
8  *
9  * These coded instructions, statements, and computer programs are the
10  * property of Apple Inc. and are protected by Federal copyright
11  * law.  Distribution and use rights are outlined in the file "LICENSE.txt"
12  * which should have been included with this file.  If this file is
13  * missing or damaged, see the license at "http://www.cups.org/".
14  *
15  * This file is subject to the Apple OS-Developed Software exception.
16  */
17 
18 /*
19  * Include necessary headers...
20  */
21 
22 #include <cups/raster-private.h>
23 #ifdef HAVE_STDINT_H
24 #  include <stdint.h>
25 #endif /* HAVE_STDINT_H */
26 
27 
28 /*
29  * Private structures...
30  */
31 
32 struct _cups_raster_s			/**** Raster stream data ****/
33 {
34   unsigned		sync;		/* Sync word from start of stream */
35   void			*ctx;		/* File descriptor */
36   cups_raster_iocb_t	iocb;		/* IO callback */
37   cups_mode_t		mode;		/* Read/write mode */
38   cups_page_header2_t	header;		/* Raster header for current page */
39   unsigned		rowheight,	/* Row height in lines */
40 			count,		/* Current row run-length count */
41 			remaining,	/* Remaining rows in page image */
42 			bpp;		/* Bytes per pixel/color */
43   unsigned char		*pixels,	/* Pixels for current row */
44 			*pend,		/* End of pixel buffer */
45 			*pcurrent;	/* Current byte in pixel buffer */
46   int			compressed,	/* Non-zero if data is compressed */
47 			swapped;	/* Non-zero if data is byte-swapped */
48   unsigned char		*buffer,	/* Read/write buffer */
49 			*bufptr,	/* Current (read) position in buffer */
50 			*bufend;	/* End of current (read) buffer */
51   size_t		bufsize;	/* Buffer size */
52 #ifdef DEBUG
53   size_t		iostart,	/* Start of read/write buffer */
54 			iocount;	/* Number of bytes read/written */
55 #endif /* DEBUG */
56   unsigned		apple_page_count;/* Apple raster page count */
57 };
58 
59 typedef void (*_cups_copyfunc_t)(void *dst, const void *src, size_t bytes);
60 
61 
62 /*
63  * Local globals...
64  */
65 
66 #ifdef DEBUG
67   static const char * const cups_color_spaces[] =
68   {					/* Color spaces */
69     "CUPS_CSPACE_W",
70     "CUPS_CSPACE_RGB",
71     "CUPS_CSPACE_RGBA",
72     "CUPS_CSPACE_K",
73     "CUPS_CSPACE_CMY",
74     "CUPS_CSPACE_YMC",
75     "CUPS_CSPACE_CMYK",
76     "CUPS_CSPACE_YMCK",
77     "CUPS_CSPACE_KCMY",
78     "CUPS_CSPACE_KCMYcm",
79     "CUPS_CSPACE_GMCK",
80     "CUPS_CSPACE_GMCS",
81     "CUPS_CSPACE_WHITE",
82     "CUPS_CSPACE_GOLD",
83     "CUPS_CSPACE_SILVER",
84     "CUPS_CSPACE_CIEXYZ",
85     "CUPS_CSPACE_CIELab",
86     "CUPS_CSPACE_RGBW",
87     "CUPS_CSPACE_SW",
88     "CUPS_CSPACE_SRGB",
89     "CUPS_CSPACE_ADOBERGB",
90     "21",
91     "22",
92     "23",
93     "24",
94     "25",
95     "26",
96     "27",
97     "28",
98     "29",
99     "30",
100     "31",
101     "CUPS_CSPACE_ICC1",
102     "CUPS_CSPACE_ICC2",
103     "CUPS_CSPACE_ICC3",
104     "CUPS_CSPACE_ICC4",
105     "CUPS_CSPACE_ICC5",
106     "CUPS_CSPACE_ICC6",
107     "CUPS_CSPACE_ICC7",
108     "CUPS_CSPACE_ICC8",
109     "CUPS_CSPACE_ICC9",
110     "CUPS_CSPACE_ICCA",
111     "CUPS_CSPACE_ICCB",
112     "CUPS_CSPACE_ICCC",
113     "CUPS_CSPACE_ICCD",
114     "CUPS_CSPACE_ICCE",
115     "CUPS_CSPACE_ICCF",
116     "47",
117     "CUPS_CSPACE_DEVICE1",
118     "CUPS_CSPACE_DEVICE2",
119     "CUPS_CSPACE_DEVICE3",
120     "CUPS_CSPACE_DEVICE4",
121     "CUPS_CSPACE_DEVICE5",
122     "CUPS_CSPACE_DEVICE6",
123     "CUPS_CSPACE_DEVICE7",
124     "CUPS_CSPACE_DEVICE8",
125     "CUPS_CSPACE_DEVICE9",
126     "CUPS_CSPACE_DEVICEA",
127     "CUPS_CSPACE_DEVICEB",
128     "CUPS_CSPACE_DEVICEC",
129     "CUPS_CSPACE_DEVICED",
130     "CUPS_CSPACE_DEVICEE",
131     "CUPS_CSPACE_DEVICEF"
132   };
133   static const char * const cups_modes[] =
134   {					/* Open modes */
135     "CUPS_RASTER_READ",
136     "CUPS_RASTER_WRITE",
137     "CUPS_RASTER_WRITE_COMPRESSED",
138     "CUPS_RASTER_WRITE_PWG",
139     "CUPS_RASTER_WRITE_APPLE"
140   };
141 #endif /* DEBUG */
142 
143 
144 /*
145  * Local functions...
146  */
147 
148 static ssize_t	cups_raster_io(cups_raster_t *r, unsigned char *buf, size_t bytes);
149 static unsigned	cups_raster_read_header(cups_raster_t *r);
150 static ssize_t	cups_raster_read(cups_raster_t *r, unsigned char *buf, size_t bytes);
151 static int	cups_raster_update(cups_raster_t *r);
152 static ssize_t	cups_raster_write(cups_raster_t *r, const unsigned char *pixels);
153 static ssize_t	cups_read_fd(void *ctx, unsigned char *buf, size_t bytes);
154 static void	cups_swap(unsigned char *buf, size_t bytes);
155 static void	cups_swap_copy(unsigned char *dst, const unsigned char *src, size_t bytes);
156 static ssize_t	cups_write_fd(void *ctx, unsigned char *buf, size_t bytes);
157 
158 
159 /*
160  * 'cupsRasterClose()' - Close a raster stream.
161  *
162  * The file descriptor associated with the raster stream must be closed
163  * separately as needed.
164  */
165 
166 void
cupsRasterClose(cups_raster_t * r)167 cupsRasterClose(cups_raster_t *r)	/* I - Stream to close */
168 {
169   if (r != NULL)
170   {
171     if (r->buffer)
172       free(r->buffer);
173 
174     if (r->pixels)
175       free(r->pixels);
176 
177     free(r);
178   }
179 }
180 
181 
182 /*
183  * 'cupsRasterInitPWGHeader()' - Initialize a page header for PWG Raster output.
184  *
185  * The "media" argument specifies the media to use.
186  *
187  * The "type" argument specifies a "pwg-raster-document-type-supported" value
188  * that controls the color space and bit depth of the raster data.
189  *
190  * The "xres" and "yres" arguments specify the raster resolution in dots per
191  * inch.
192  *
193  * The "sheet_back" argument specifies a "pwg-raster-document-sheet-back" value
194  * to apply for the back side of a page.  Pass @code NULL@ for the front side.
195  *
196  * @since CUPS 2.2/macOS 10.12@
197  */
198 
199 int					/* O - 1 on success, 0 on failure */
cupsRasterInitPWGHeader(cups_page_header2_t * h,pwg_media_t * media,const char * type,int xdpi,int ydpi,const char * sides,const char * sheet_back)200 cupsRasterInitPWGHeader(
201     cups_page_header2_t *h,		/* I - Page header */
202     pwg_media_t         *media,		/* I - PWG media information */
203     const char          *type,		/* I - PWG raster type string */
204     int                 xdpi,		/* I - Cross-feed direction (horizontal) resolution */
205     int                 ydpi,		/* I - Feed direction (vertical) resolution */
206     const char          *sides,		/* I - IPP "sides" option value */
207     const char          *sheet_back)	/* I - Transform for back side or @code NULL@ for none */
208 {
209   if (!h || !media || !type || xdpi <= 0 || ydpi <= 0)
210   {
211     _cupsRasterAddError("%s", strerror(EINVAL));
212     return (0);
213   }
214 
215  /*
216   * Initialize the page header...
217   */
218 
219   memset(h, 0, sizeof(cups_page_header2_t));
220 
221   strlcpy(h->cupsPageSizeName, media->pwg, sizeof(h->cupsPageSizeName));
222 
223   h->PageSize[0] = (unsigned)(72 * media->width / 2540);
224   h->PageSize[1] = (unsigned)(72 * media->length / 2540);
225 
226   /* This never gets written but is needed for some applications */
227   h->cupsPageSize[0] = 72.0f * media->width / 2540.0f;
228   h->cupsPageSize[1] = 72.0f * media->length / 2540.0f;
229 
230   h->ImagingBoundingBox[2] = h->PageSize[0];
231   h->ImagingBoundingBox[3] = h->PageSize[1];
232 
233   h->HWResolution[0] = (unsigned)xdpi;
234   h->HWResolution[1] = (unsigned)ydpi;
235 
236   h->cupsWidth  = (unsigned)(media->width * xdpi / 2540);
237   h->cupsHeight = (unsigned)(media->length * ydpi / 2540);
238 
239   if (h->cupsWidth > 0x00ffffff || h->cupsHeight > 0x00ffffff)
240   {
241     _cupsRasterAddError("Raster dimensions too large.");
242     return (0);
243   }
244 
245   h->cupsInteger[CUPS_RASTER_PWG_ImageBoxRight]  = h->cupsWidth;
246   h->cupsInteger[CUPS_RASTER_PWG_ImageBoxBottom] = h->cupsHeight;
247 
248  /*
249   * Colorspace and bytes per line...
250   */
251 
252   if (!strcmp(type, "adobe-rgb_8"))
253   {
254     h->cupsBitsPerColor = 8;
255     h->cupsBitsPerPixel = 24;
256     h->cupsColorSpace   = CUPS_CSPACE_ADOBERGB;
257   }
258   else if (!strcmp(type, "adobe-rgb_16"))
259   {
260     h->cupsBitsPerColor = 16;
261     h->cupsBitsPerPixel = 48;
262     h->cupsColorSpace   = CUPS_CSPACE_ADOBERGB;
263   }
264   else if (!strcmp(type, "black_1"))
265   {
266     h->cupsBitsPerColor = 1;
267     h->cupsBitsPerPixel = 1;
268     h->cupsColorSpace   = CUPS_CSPACE_K;
269   }
270   else if (!strcmp(type, "black_8"))
271   {
272     h->cupsBitsPerColor = 8;
273     h->cupsBitsPerPixel = 8;
274     h->cupsColorSpace   = CUPS_CSPACE_K;
275   }
276   else if (!strcmp(type, "black_16"))
277   {
278     h->cupsBitsPerColor = 16;
279     h->cupsBitsPerPixel = 16;
280     h->cupsColorSpace   = CUPS_CSPACE_K;
281   }
282   else if (!strcmp(type, "cmyk_8"))
283   {
284     h->cupsBitsPerColor = 8;
285     h->cupsBitsPerPixel = 32;
286     h->cupsColorSpace   = CUPS_CSPACE_CMYK;
287   }
288   else if (!strcmp(type, "cmyk_16"))
289   {
290     h->cupsBitsPerColor = 16;
291     h->cupsBitsPerPixel = 64;
292     h->cupsColorSpace   = CUPS_CSPACE_CMYK;
293   }
294   else if (!strncmp(type, "device", 6) && type[6] >= '1' && type[6] <= '9')
295   {
296     int ncolors, bits;			/* Number of colors and bits */
297 
298 
299     if (sscanf(type, "device%d_%d", &ncolors, &bits) != 2 || ncolors > 15 || (bits != 8 && bits != 16))
300     {
301       _cupsRasterAddError("Unsupported raster type \'%s\'.", type);
302       return (0);
303     }
304 
305     h->cupsBitsPerColor = (unsigned)bits;
306     h->cupsBitsPerPixel = (unsigned)(ncolors * bits);
307     h->cupsColorSpace   = (cups_cspace_t)(CUPS_CSPACE_DEVICE1 + ncolors - 1);
308   }
309   else if (!strcmp(type, "rgb_8"))
310   {
311     h->cupsBitsPerColor = 8;
312     h->cupsBitsPerPixel = 24;
313     h->cupsColorSpace   = CUPS_CSPACE_RGB;
314   }
315   else if (!strcmp(type, "rgb_16"))
316   {
317     h->cupsBitsPerColor = 16;
318     h->cupsBitsPerPixel = 48;
319     h->cupsColorSpace   = CUPS_CSPACE_RGB;
320   }
321   else if (!strcmp(type, "sgray_1"))
322   {
323     h->cupsBitsPerColor = 1;
324     h->cupsBitsPerPixel = 1;
325     h->cupsColorSpace   = CUPS_CSPACE_SW;
326   }
327   else if (!strcmp(type, "sgray_8"))
328   {
329     h->cupsBitsPerColor = 8;
330     h->cupsBitsPerPixel = 8;
331     h->cupsColorSpace   = CUPS_CSPACE_SW;
332   }
333   else if (!strcmp(type, "sgray_16"))
334   {
335     h->cupsBitsPerColor = 16;
336     h->cupsBitsPerPixel = 16;
337     h->cupsColorSpace   = CUPS_CSPACE_SW;
338   }
339   else if (!strcmp(type, "srgb_8"))
340   {
341     h->cupsBitsPerColor = 8;
342     h->cupsBitsPerPixel = 24;
343     h->cupsColorSpace   = CUPS_CSPACE_SRGB;
344   }
345   else if (!strcmp(type, "srgb_16"))
346   {
347     h->cupsBitsPerColor = 16;
348     h->cupsBitsPerPixel = 48;
349     h->cupsColorSpace   = CUPS_CSPACE_SRGB;
350   }
351   else
352   {
353     _cupsRasterAddError("Unsupported raster type \'%s\'.", type);
354     return (0);
355   }
356 
357   h->cupsColorOrder   = CUPS_ORDER_CHUNKED;
358   h->cupsNumColors    = h->cupsBitsPerPixel / h->cupsBitsPerColor;
359   h->cupsBytesPerLine = (h->cupsWidth * h->cupsBitsPerPixel + 7) / 8;
360 
361  /*
362   * Duplex support...
363   */
364 
365   h->cupsInteger[CUPS_RASTER_PWG_CrossFeedTransform] = 1;
366   h->cupsInteger[CUPS_RASTER_PWG_FeedTransform]      = 1;
367 
368   if (sides)
369   {
370     if (!strcmp(sides, "two-sided-long-edge"))
371     {
372       h->Duplex = 1;
373     }
374     else if (!strcmp(sides, "two-sided-short-edge"))
375     {
376       h->Duplex = 1;
377       h->Tumble = 1;
378     }
379     else if (strcmp(sides, "one-sided"))
380     {
381       _cupsRasterAddError("Unsupported sides value \'%s\'.", sides);
382       return (0);
383     }
384 
385     if (sheet_back)
386     {
387       if (!strcmp(sheet_back, "flipped"))
388       {
389         if (h->Tumble)
390           h->cupsInteger[CUPS_RASTER_PWG_CrossFeedTransform] = 0xffffffffU;
391         else
392           h->cupsInteger[CUPS_RASTER_PWG_FeedTransform] = 0xffffffffU;
393       }
394       else if (!strcmp(sheet_back, "manual-tumble"))
395       {
396         if (h->Tumble)
397         {
398           h->cupsInteger[CUPS_RASTER_PWG_CrossFeedTransform] = 0xffffffffU;
399           h->cupsInteger[CUPS_RASTER_PWG_FeedTransform]      = 0xffffffffU;
400         }
401       }
402       else if (!strcmp(sheet_back, "rotated"))
403       {
404         if (!h->Tumble)
405         {
406           h->cupsInteger[CUPS_RASTER_PWG_CrossFeedTransform] = 0xffffffffU;
407           h->cupsInteger[CUPS_RASTER_PWG_FeedTransform]      = 0xffffffffU;
408         }
409       }
410       else if (strcmp(sheet_back, "normal"))
411       {
412 	_cupsRasterAddError("Unsupported sheet_back value \'%s\'.", sheet_back);
413 	return (0);
414       }
415     }
416   }
417 
418   return (1);
419 }
420 
421 
422 /*
423  * 'cupsRasterOpen()' - Open a raster stream using a file descriptor.
424  *
425  * This function associates a raster stream with the given file descriptor.
426  * For most printer driver filters, "fd" will be 0 (stdin).  For most raster
427  * image processor (RIP) filters that generate raster data, "fd" will be 1
428  * (stdout).
429  *
430  * When writing raster data, the @code CUPS_RASTER_WRITE@,
431  * @code CUPS_RASTER_WRITE_COMPRESS@, or @code CUPS_RASTER_WRITE_PWG@ mode can
432  * be used - compressed and PWG output is generally 25-50% smaller but adds a
433  * 100-300% execution time overhead.
434  */
435 
436 cups_raster_t *				/* O - New stream */
cupsRasterOpen(int fd,cups_mode_t mode)437 cupsRasterOpen(int         fd,		/* I - File descriptor */
438                cups_mode_t mode)	/* I - Mode - @code CUPS_RASTER_READ@,
439 	                                       @code CUPS_RASTER_WRITE@,
440 					       @code CUPS_RASTER_WRITE_COMPRESSED@,
441 					       or @code CUPS_RASTER_WRITE_PWG@ */
442 {
443   DEBUG_printf(("cupsRasterOpen(fd=%d, mode=%s)", fd, cups_modes[mode]));
444 
445   if (mode == CUPS_RASTER_READ)
446     return (cupsRasterOpenIO(cups_read_fd, (void *)((intptr_t)fd), mode));
447   else
448     return (cupsRasterOpenIO(cups_write_fd, (void *)((intptr_t)fd), mode));
449 }
450 
451 
452 /*
453  * 'cupsRasterOpenIO()' - Open a raster stream using a callback function.
454  *
455  * This function associates a raster stream with the given callback function and
456  * context pointer.
457  *
458  * When writing raster data, the @code CUPS_RASTER_WRITE@,
459  * @code CUPS_RASTER_WRITE_COMPRESS@, or @code CUPS_RASTER_WRITE_PWG@ mode can
460  * be used - compressed and PWG output is generally 25-50% smaller but adds a
461  * 100-300% execution time overhead.
462  */
463 
464 cups_raster_t *				/* O - New stream */
cupsRasterOpenIO(cups_raster_iocb_t iocb,void * ctx,cups_mode_t mode)465 cupsRasterOpenIO(
466     cups_raster_iocb_t iocb,		/* I - Read/write callback */
467     void               *ctx,		/* I - Context pointer for callback */
468     cups_mode_t        mode)		/* I - Mode - @code CUPS_RASTER_READ@,
469 	                                       @code CUPS_RASTER_WRITE@,
470 					       @code CUPS_RASTER_WRITE_COMPRESSED@,
471 					       or @code CUPS_RASTER_WRITE_PWG@ */
472 {
473   cups_raster_t	*r;			/* New stream */
474 
475 
476   DEBUG_printf(("cupsRasterOpenIO(iocb=%p, ctx=%p, mode=%s)", (void *)iocb, ctx, cups_modes[mode]));
477 
478   _cupsRasterClearError();
479 
480   if ((r = calloc(sizeof(cups_raster_t), 1)) == NULL)
481   {
482     _cupsRasterAddError("Unable to allocate memory for raster stream: %s\n",
483                         strerror(errno));
484     DEBUG_puts("1cupsRasterOpenIO: Returning NULL.");
485     return (NULL);
486   }
487 
488   r->ctx  = ctx;
489   r->iocb = iocb;
490   r->mode = mode;
491 
492   if (mode == CUPS_RASTER_READ)
493   {
494    /*
495     * Open for read - get sync word...
496     */
497 
498     if (cups_raster_io(r, (unsigned char *)&(r->sync), sizeof(r->sync)) !=
499             sizeof(r->sync))
500     {
501       _cupsRasterAddError("Unable to read header from raster stream: %s\n",
502                           strerror(errno));
503       free(r);
504       DEBUG_puts("1cupsRasterOpenIO: Unable to read header, returning NULL.");
505       return (NULL);
506     }
507 
508     if (r->sync != CUPS_RASTER_SYNC &&
509         r->sync != CUPS_RASTER_REVSYNC &&
510         r->sync != CUPS_RASTER_SYNCv1 &&
511         r->sync != CUPS_RASTER_REVSYNCv1 &&
512         r->sync != CUPS_RASTER_SYNCv2 &&
513         r->sync != CUPS_RASTER_REVSYNCv2 &&
514         r->sync != CUPS_RASTER_SYNCapple &&
515         r->sync != CUPS_RASTER_REVSYNCapple)
516     {
517       _cupsRasterAddError("Unknown raster format %08x!\n", r->sync);
518       free(r);
519       DEBUG_puts("1cupsRasterOpenIO: Unknown format, returning NULL.");
520       return (NULL);
521     }
522 
523     if (r->sync == CUPS_RASTER_SYNCv2 ||
524         r->sync == CUPS_RASTER_REVSYNCv2 ||
525         r->sync == CUPS_RASTER_SYNCapple ||
526         r->sync == CUPS_RASTER_REVSYNCapple)
527       r->compressed = 1;
528 
529     DEBUG_printf(("1cupsRasterOpenIO: sync=%08x", r->sync));
530 
531     if (r->sync == CUPS_RASTER_REVSYNC ||
532         r->sync == CUPS_RASTER_REVSYNCv1 ||
533         r->sync == CUPS_RASTER_REVSYNCv2 ||
534         r->sync == CUPS_RASTER_REVSYNCapple)
535       r->swapped = 1;
536 
537     if (r->sync == CUPS_RASTER_SYNCapple ||
538         r->sync == CUPS_RASTER_REVSYNCapple)
539     {
540       unsigned char	header[8];	/* File header */
541 
542       if (cups_raster_io(r, (unsigned char *)header, sizeof(header)) !=
543 	      sizeof(header))
544       {
545 	_cupsRasterAddError("Unable to read header from raster stream: %s\n",
546 			    strerror(errno));
547 	free(r);
548 	DEBUG_puts("1cupsRasterOpenIO: Unable to read header, returning NULL.");
549 	return (NULL);
550       }
551     }
552 
553 #ifdef DEBUG
554     r->iostart = r->iocount;
555 #endif /* DEBUG */
556   }
557   else
558   {
559    /*
560     * Open for write - put sync word...
561     */
562 
563     switch (mode)
564     {
565       default :
566       case CUPS_RASTER_WRITE :
567           r->sync = CUPS_RASTER_SYNC;
568 	  break;
569 
570       case CUPS_RASTER_WRITE_COMPRESSED :
571           r->compressed = 1;
572           r->sync       = CUPS_RASTER_SYNCv2;
573 	  break;
574 
575       case CUPS_RASTER_WRITE_PWG :
576           r->compressed = 1;
577           r->sync       = htonl(CUPS_RASTER_SYNC_PWG);
578           r->swapped    = r->sync != CUPS_RASTER_SYNC_PWG;
579 	  break;
580 
581       case CUPS_RASTER_WRITE_APPLE :
582           r->compressed     = 1;
583           r->sync           = htonl(CUPS_RASTER_SYNCapple);
584           r->swapped        = r->sync != CUPS_RASTER_SYNCapple;
585           r->apple_page_count = 0xffffffffU;
586 	  break;
587     }
588 
589     if (cups_raster_io(r, (unsigned char *)&(r->sync), sizeof(r->sync)) < (ssize_t)sizeof(r->sync))
590     {
591       _cupsRasterAddError("Unable to write raster stream header: %s\n",
592                           strerror(errno));
593       free(r);
594       DEBUG_puts("1cupsRasterOpenIO: Unable to write header, returning NULL.");
595       return (NULL);
596     }
597   }
598 
599   DEBUG_printf(("1cupsRasterOpenIO: compressed=%d, swapped=%d, returning %p", r->compressed, r->swapped, (void *)r));
600 
601   return (r);
602 }
603 
604 
605 /*
606  * 'cupsRasterReadHeader()' - Read a raster page header and store it in a
607  *                            version 1 page header structure.
608  *
609  * This function is deprecated. Use @link cupsRasterReadHeader2@ instead.
610  *
611  * Version 1 page headers were used in CUPS 1.0 and 1.1 and contain a subset
612  * of the version 2 page header data. This function handles reading version 2
613  * page headers and copying only the version 1 data into the provided buffer.
614  *
615  * @deprecated@
616  */
617 
618 unsigned				/* O - 1 on success, 0 on failure/end-of-file */
cupsRasterReadHeader(cups_raster_t * r,cups_page_header_t * h)619 cupsRasterReadHeader(
620     cups_raster_t      *r,		/* I - Raster stream */
621     cups_page_header_t *h)		/* I - Pointer to header data */
622 {
623   DEBUG_printf(("cupsRasterReadHeader(r=%p, h=%p)", (void *)r, (void *)h));
624 
625  /*
626   * Get the raster header...
627   */
628 
629   if (!cups_raster_read_header(r))
630   {
631     memset(h, 0, sizeof(cups_page_header_t));
632     DEBUG_puts("1cupsRasterReadHeader: Unable to read page header, returning 0.");
633     return (0);
634   }
635 
636  /*
637   * Copy the header to the user-supplied buffer...
638   */
639 
640   memcpy(h, &(r->header), sizeof(cups_page_header_t));
641 
642   DEBUG_printf(("1cupsRasterReadHeader: cupsColorSpace=%s", cups_color_spaces[h->cupsColorSpace]));
643   DEBUG_printf(("1cupsRasterReadHeader: cupsBitsPerColor=%u", h->cupsBitsPerColor));
644   DEBUG_printf(("1cupsRasterReadHeader: cupsBitsPerPixel=%u", h->cupsBitsPerPixel));
645   DEBUG_printf(("1cupsRasterReadHeader: cupsBytesPerLine=%u", h->cupsBytesPerLine));
646   DEBUG_printf(("1cupsRasterReadHeader: cupsWidth=%u", h->cupsWidth));
647   DEBUG_printf(("1cupsRasterReadHeader: cupsHeight=%u", h->cupsHeight));
648 
649   DEBUG_puts("1cupsRasterReadHeader: Returning 1.");
650   return (1);
651 }
652 
653 
654 /*
655  * 'cupsRasterReadHeader2()' - Read a raster page header and store it in a
656  *                             version 2 page header structure.
657  *
658  * @since CUPS 1.2/macOS 10.5@
659  */
660 
661 unsigned				/* O - 1 on success, 0 on failure/end-of-file */
cupsRasterReadHeader2(cups_raster_t * r,cups_page_header2_t * h)662 cupsRasterReadHeader2(
663     cups_raster_t       *r,		/* I - Raster stream */
664     cups_page_header2_t *h)		/* I - Pointer to header data */
665 {
666  /*
667   * Get the raster header...
668   */
669 
670   DEBUG_printf(("cupsRasterReadHeader2(r=%p, h=%p)", (void *)r, (void *)h));
671 
672   if (!cups_raster_read_header(r))
673   {
674     memset(h, 0, sizeof(cups_page_header2_t));
675     DEBUG_puts("1cupsRasterReadHeader2: Unable to read header, returning 0.");
676     return (0);
677   }
678 
679  /*
680   * Copy the header to the user-supplied buffer...
681   */
682 
683   memcpy(h, &(r->header), sizeof(cups_page_header2_t));
684 
685   DEBUG_printf(("1cupsRasterReadHeader2: cupsColorSpace=%s", cups_color_spaces[h->cupsColorSpace]));
686   DEBUG_printf(("1cupsRasterReadHeader2: cupsBitsPerColor=%u", h->cupsBitsPerColor));
687   DEBUG_printf(("1cupsRasterReadHeader2: cupsBitsPerPixel=%u", h->cupsBitsPerPixel));
688   DEBUG_printf(("1cupsRasterReadHeader2: cupsBytesPerLine=%u", h->cupsBytesPerLine));
689   DEBUG_printf(("1cupsRasterReadHeader2: cupsWidth=%u", h->cupsWidth));
690   DEBUG_printf(("1cupsRasterReadHeader2: cupsHeight=%u", h->cupsHeight));
691 
692   DEBUG_puts("1cupsRasterReadHeader2: Returning 1.");
693   return (1);
694 }
695 
696 
697 /*
698  * 'cupsRasterReadPixels()' - Read raster pixels.
699  *
700  * For best performance, filters should read one or more whole lines.
701  * The "cupsBytesPerLine" value from the page header can be used to allocate
702  * the line buffer and as the number of bytes to read.
703  */
704 
705 unsigned				/* O - Number of bytes read */
cupsRasterReadPixels(cups_raster_t * r,unsigned char * p,unsigned len)706 cupsRasterReadPixels(cups_raster_t *r,	/* I - Raster stream */
707                      unsigned char *p,	/* I - Pointer to pixel buffer */
708 		     unsigned      len)	/* I - Number of bytes to read */
709 {
710   ssize_t	bytes;			/* Bytes read */
711   unsigned	cupsBytesPerLine;	/* cupsBytesPerLine value */
712   unsigned	remaining;		/* Bytes remaining */
713   unsigned char	*ptr,			/* Pointer to read buffer */
714 		byte,			/* Byte from file */
715 		*temp;			/* Pointer into buffer */
716   unsigned	count;			/* Repetition count */
717 
718 
719   DEBUG_printf(("cupsRasterReadPixels(r=%p, p=%p, len=%u)", (void *)r, (void *)p, len));
720 
721   if (r == NULL || r->mode != CUPS_RASTER_READ || r->remaining == 0 ||
722       r->header.cupsBytesPerLine == 0)
723   {
724     DEBUG_puts("1cupsRasterReadPixels: Returning 0.");
725     return (0);
726   }
727 
728   DEBUG_printf(("1cupsRasterReadPixels: compressed=%d, remaining=%u", r->compressed, r->remaining));
729 
730   if (!r->compressed)
731   {
732    /*
733     * Read without compression...
734     */
735 
736     r->remaining -= len / r->header.cupsBytesPerLine;
737 
738     if (cups_raster_io(r, p, len) < (ssize_t)len)
739     {
740       DEBUG_puts("1cupsRasterReadPixels: Read error, returning 0.");
741       return (0);
742     }
743 
744    /*
745     * Swap bytes as needed...
746     */
747 
748     if (r->swapped &&
749         (r->header.cupsBitsPerColor == 16 ||
750          r->header.cupsBitsPerPixel == 12 ||
751          r->header.cupsBitsPerPixel == 16))
752       cups_swap(p, len);
753 
754    /*
755     * Return...
756     */
757 
758     DEBUG_printf(("1cupsRasterReadPixels: Returning %u", len));
759 
760     return (len);
761   }
762 
763  /*
764   * Read compressed data...
765   */
766 
767   remaining        = len;
768   cupsBytesPerLine = r->header.cupsBytesPerLine;
769 
770   while (remaining > 0 && r->remaining > 0)
771   {
772     if (r->count == 0)
773     {
774      /*
775       * Need to read a new row...
776       */
777 
778       if (remaining == cupsBytesPerLine)
779 	ptr = p;
780       else
781 	ptr = r->pixels;
782 
783      /*
784       * Read using a modified PackBits compression...
785       */
786 
787       if (!cups_raster_read(r, &byte, 1))
788       {
789 	DEBUG_puts("1cupsRasterReadPixels: Read error, returning 0.");
790 	return (0);
791       }
792 
793       r->count = (unsigned)byte + 1;
794 
795       if (r->count > 1)
796 	ptr = r->pixels;
797 
798       temp  = ptr;
799       bytes = (ssize_t)cupsBytesPerLine;
800 
801       while (bytes > 0)
802       {
803        /*
804 	* Get a new repeat count...
805 	*/
806 
807         if (!cups_raster_read(r, &byte, 1))
808 	{
809 	  DEBUG_puts("1cupsRasterReadPixels: Read error, returning 0.");
810 	  return (0);
811 	}
812 
813         if (byte == 128)
814         {
815          /*
816           * Clear to end of line...
817           */
818 
819           switch (r->header.cupsColorSpace)
820           {
821             case CUPS_CSPACE_W :
822             case CUPS_CSPACE_RGB :
823             case CUPS_CSPACE_SW :
824             case CUPS_CSPACE_SRGB :
825             case CUPS_CSPACE_RGBW :
826             case CUPS_CSPACE_ADOBERGB :
827                 memset(temp, 0xff, (size_t)bytes);
828                 break;
829             default :
830                 memset(temp, 0x00, (size_t)bytes);
831                 break;
832           }
833 
834           temp += bytes;
835           bytes = 0;
836         }
837 	else if (byte & 128)
838 	{
839 	 /*
840 	  * Copy N literal pixels...
841 	  */
842 
843 	  count = (unsigned)(257 - byte) * r->bpp;
844 
845           if (count > (unsigned)bytes)
846 	    count = (unsigned)bytes;
847 
848           if (!cups_raster_read(r, temp, count))
849 	  {
850 	    DEBUG_puts("1cupsRasterReadPixels: Read error, returning 0.");
851 	    return (0);
852 	  }
853 
854 	  temp  += count;
855 	  bytes -= (ssize_t)count;
856 	}
857 	else
858 	{
859 	 /*
860 	  * Repeat the next N bytes...
861 	  */
862 
863           count = ((unsigned)byte + 1) * r->bpp;
864           if (count > (unsigned)bytes)
865 	    count = (unsigned)bytes;
866 
867           if (count < r->bpp)
868 	    break;
869 
870 	  bytes -= (ssize_t)count;
871 
872           if (!cups_raster_read(r, temp, r->bpp))
873 	  {
874 	    DEBUG_puts("1cupsRasterReadPixels: Read error, returning 0.");
875 	    return (0);
876 	  }
877 
878 	  temp  += r->bpp;
879 	  count -= r->bpp;
880 
881 	  while (count > 0)
882 	  {
883 	    memcpy(temp, temp - r->bpp, r->bpp);
884 	    temp  += r->bpp;
885 	    count -= r->bpp;
886           }
887 	}
888       }
889 
890      /*
891       * Swap bytes as needed...
892       */
893 
894       if ((r->header.cupsBitsPerColor == 16 ||
895            r->header.cupsBitsPerPixel == 12 ||
896            r->header.cupsBitsPerPixel == 16) &&
897           r->swapped)
898       {
899         DEBUG_puts("1cupsRasterReadPixels: Swapping bytes.");
900         cups_swap(ptr, (size_t)cupsBytesPerLine);
901       }
902 
903      /*
904       * Update pointers...
905       */
906 
907       if (remaining >= cupsBytesPerLine)
908       {
909 	bytes       = (ssize_t)cupsBytesPerLine;
910         r->pcurrent = r->pixels;
911 	r->count --;
912 	r->remaining --;
913       }
914       else
915       {
916 	bytes       = (ssize_t)remaining;
917         r->pcurrent = r->pixels + bytes;
918       }
919 
920      /*
921       * Copy data as needed...
922       */
923 
924       if (ptr != p)
925         memcpy(p, ptr, (size_t)bytes);
926     }
927     else
928     {
929      /*
930       * Copy fragment from buffer...
931       */
932 
933       if ((unsigned)(bytes = (int)(r->pend - r->pcurrent)) > remaining)
934         bytes = (ssize_t)remaining;
935 
936       memcpy(p, r->pcurrent, (size_t)bytes);
937       r->pcurrent += bytes;
938 
939       if (r->pcurrent >= r->pend)
940       {
941         r->pcurrent = r->pixels;
942 	r->count --;
943 	r->remaining --;
944       }
945     }
946 
947     remaining -= (unsigned)bytes;
948     p         += bytes;
949   }
950 
951   DEBUG_printf(("1cupsRasterReadPixels: Returning %u", len));
952 
953   return (len);
954 }
955 
956 
957 /*
958  * 'cupsRasterWriteHeader()' - Write a raster page header from a version 1 page
959  *                             header structure.
960  *
961  * This function is deprecated. Use @link cupsRasterWriteHeader2@ instead.
962  *
963  * @deprecated@
964  */
965 
966 unsigned				/* O - 1 on success, 0 on failure */
cupsRasterWriteHeader(cups_raster_t * r,cups_page_header_t * h)967 cupsRasterWriteHeader(
968     cups_raster_t      *r,		/* I - Raster stream */
969     cups_page_header_t *h)		/* I - Raster page header */
970 {
971   DEBUG_printf(("cupsRasterWriteHeader(r=%p, h=%p)", (void *)r, (void *)h));
972 
973   if (r == NULL || r->mode == CUPS_RASTER_READ)
974   {
975     DEBUG_puts("1cupsRasterWriteHeader: Returning 0.");
976     return (0);
977   }
978 
979   DEBUG_printf(("1cupsRasterWriteHeader: cupsColorSpace=%s", cups_color_spaces[h->cupsColorSpace]));
980   DEBUG_printf(("1cupsRasterWriteHeader: cupsBitsPerColor=%u", h->cupsBitsPerColor));
981   DEBUG_printf(("1cupsRasterWriteHeader: cupsBitsPerPixel=%u", h->cupsBitsPerPixel));
982   DEBUG_printf(("1cupsRasterWriteHeader: cupsBytesPerLine=%u", h->cupsBytesPerLine));
983   DEBUG_printf(("1cupsRasterWriteHeader: cupsWidth=%u", h->cupsWidth));
984   DEBUG_printf(("1cupsRasterWriteHeader: cupsHeight=%u", h->cupsHeight));
985 
986  /*
987   * Make a copy of the header, and compute the number of raster
988   * lines in the page image...
989   */
990 
991   memset(&(r->header), 0, sizeof(r->header));
992   memcpy(&(r->header), h, sizeof(cups_page_header_t));
993 
994   if (!cups_raster_update(r))
995   {
996     DEBUG_puts("1cupsRasterWriteHeader: Unable to update parameters, returning 0.");
997     return (0);
998   }
999 
1000   if (r->mode == CUPS_RASTER_WRITE_APPLE)
1001   {
1002     r->rowheight = h->HWResolution[0] / h->HWResolution[1];
1003 
1004     if (h->HWResolution[0] != (r->rowheight * h->HWResolution[1]))
1005       return (0);
1006   }
1007   else
1008     r->rowheight = 1;
1009 
1010  /*
1011   * Write the raster header...
1012   */
1013 
1014   if (r->mode == CUPS_RASTER_WRITE_PWG)
1015   {
1016    /*
1017     * PWG raster data is always network byte order with much of the page header
1018     * zeroed.
1019     */
1020 
1021     cups_page_header2_t	fh;		/* File page header */
1022 
1023     memset(&fh, 0, sizeof(fh));
1024 
1025     strlcpy(fh.MediaClass, "PwgRaster", sizeof(fh.MediaClass));
1026 					/* PwgRaster */
1027     strlcpy(fh.MediaColor, r->header.MediaColor, sizeof(fh.MediaColor));
1028     strlcpy(fh.MediaType, r->header.MediaType, sizeof(fh.MediaType));
1029     strlcpy(fh.OutputType, r->header.OutputType, sizeof(fh.OutputType));
1030 					/* PrintContentType */
1031 
1032     fh.CutMedia              = htonl(r->header.CutMedia);
1033     fh.Duplex                = htonl(r->header.Duplex);
1034     fh.HWResolution[0]       = htonl(r->header.HWResolution[0]);
1035     fh.HWResolution[1]       = htonl(r->header.HWResolution[1]);
1036     fh.ImagingBoundingBox[0] = htonl(r->header.ImagingBoundingBox[0]);
1037     fh.ImagingBoundingBox[1] = htonl(r->header.ImagingBoundingBox[1]);
1038     fh.ImagingBoundingBox[2] = htonl(r->header.ImagingBoundingBox[2]);
1039     fh.ImagingBoundingBox[3] = htonl(r->header.ImagingBoundingBox[3]);
1040     fh.InsertSheet           = htonl(r->header.InsertSheet);
1041     fh.Jog                   = htonl(r->header.Jog);
1042     fh.LeadingEdge           = htonl(r->header.LeadingEdge);
1043     fh.ManualFeed            = htonl(r->header.ManualFeed);
1044     fh.MediaPosition         = htonl(r->header.MediaPosition);
1045     fh.MediaWeight           = htonl(r->header.MediaWeight);
1046     fh.NumCopies             = htonl(r->header.NumCopies);
1047     fh.Orientation           = htonl(r->header.Orientation);
1048     fh.PageSize[0]           = htonl(r->header.PageSize[0]);
1049     fh.PageSize[1]           = htonl(r->header.PageSize[1]);
1050     fh.Tumble                = htonl(r->header.Tumble);
1051     fh.cupsWidth             = htonl(r->header.cupsWidth);
1052     fh.cupsHeight            = htonl(r->header.cupsHeight);
1053     fh.cupsBitsPerColor      = htonl(r->header.cupsBitsPerColor);
1054     fh.cupsBitsPerPixel      = htonl(r->header.cupsBitsPerPixel);
1055     fh.cupsBytesPerLine      = htonl(r->header.cupsBytesPerLine);
1056     fh.cupsColorOrder        = htonl(r->header.cupsColorOrder);
1057     fh.cupsColorSpace        = htonl(r->header.cupsColorSpace);
1058     fh.cupsNumColors         = htonl(r->header.cupsNumColors);
1059     fh.cupsInteger[0]        = htonl(r->header.cupsInteger[0]);
1060 					/* TotalPageCount */
1061     fh.cupsInteger[1]        = htonl(r->header.cupsInteger[1]);
1062 					/* CrossFeedTransform */
1063     fh.cupsInteger[2]        = htonl(r->header.cupsInteger[2]);
1064 					/* FeedTransform */
1065     fh.cupsInteger[3]        = htonl(r->header.cupsInteger[3]);
1066 					/* ImageBoxLeft */
1067     fh.cupsInteger[4]        = htonl(r->header.cupsInteger[4]);
1068 					/* ImageBoxTop */
1069     fh.cupsInteger[5]        = htonl(r->header.cupsInteger[5]);
1070 					/* ImageBoxRight */
1071     fh.cupsInteger[6]        = htonl(r->header.cupsInteger[6]);
1072 					/* ImageBoxBottom */
1073     fh.cupsInteger[7]        = htonl(r->header.cupsInteger[7]);
1074 					/* BlackPrimary */
1075     fh.cupsInteger[8]        = htonl(r->header.cupsInteger[8]);
1076 					/* PrintQuality */
1077     fh.cupsInteger[14]       = htonl(r->header.cupsInteger[14]);
1078 					/* VendorIdentifier */
1079     fh.cupsInteger[15]       = htonl(r->header.cupsInteger[15]);
1080 					/* VendorLength */
1081 
1082     void *dst = fh.cupsReal; /* Bypass bogus compiler warning */
1083     void *src = r->header.cupsReal;
1084     memcpy(dst, src, sizeof(fh.cupsReal) + sizeof(fh.cupsString));
1085 					/* VendorData */
1086 
1087     strlcpy(fh.cupsRenderingIntent, r->header.cupsRenderingIntent,
1088             sizeof(fh.cupsRenderingIntent));
1089     strlcpy(fh.cupsPageSizeName, r->header.cupsPageSizeName,
1090             sizeof(fh.cupsPageSizeName));
1091 
1092     return (cups_raster_io(r, (unsigned char *)&fh, sizeof(fh)) == sizeof(fh));
1093   }
1094   else if (r->mode == CUPS_RASTER_WRITE_APPLE)
1095   {
1096    /*
1097     * Raw raster data is always network byte order with most of the page header
1098     * zeroed.
1099     */
1100 
1101     unsigned char appleheader[32];	/* Raw page header */
1102 
1103     if (r->apple_page_count == 0xffffffffU)
1104     {
1105      /*
1106       * Write raw page count from raster page header...
1107       */
1108 
1109       r->apple_page_count = r->header.cupsInteger[0];
1110 
1111       appleheader[0] = 'A';
1112       appleheader[1] = 'S';
1113       appleheader[2] = 'T';
1114       appleheader[3] = 0;
1115       appleheader[4] = (unsigned char)(r->apple_page_count >> 24);
1116       appleheader[5] = (unsigned char)(r->apple_page_count >> 16);
1117       appleheader[6] = (unsigned char)(r->apple_page_count >> 8);
1118       appleheader[7] = (unsigned char)(r->apple_page_count);
1119 
1120       if (cups_raster_io(r, appleheader, 8) != 8)
1121         return (0);
1122     }
1123 
1124     memset(appleheader, 0, sizeof(appleheader));
1125 
1126     appleheader[0]  = (unsigned char)r->header.cupsBitsPerPixel;
1127     appleheader[1]  = r->header.cupsColorSpace == CUPS_CSPACE_SRGB ? 1 :
1128                         r->header.cupsColorSpace == CUPS_CSPACE_RGBW ? 2 :
1129                         r->header.cupsColorSpace == CUPS_CSPACE_ADOBERGB ? 3 :
1130                         r->header.cupsColorSpace == CUPS_CSPACE_W ? 4 :
1131                         r->header.cupsColorSpace == CUPS_CSPACE_RGB ? 5 :
1132                         r->header.cupsColorSpace == CUPS_CSPACE_CMYK ? 6 : 0;
1133     appleheader[12] = (unsigned char)(r->header.cupsWidth >> 24);
1134     appleheader[13] = (unsigned char)(r->header.cupsWidth >> 16);
1135     appleheader[14] = (unsigned char)(r->header.cupsWidth >> 8);
1136     appleheader[15] = (unsigned char)(r->header.cupsWidth);
1137     appleheader[16] = (unsigned char)(r->header.cupsHeight >> 24);
1138     appleheader[17] = (unsigned char)(r->header.cupsHeight >> 16);
1139     appleheader[18] = (unsigned char)(r->header.cupsHeight >> 8);
1140     appleheader[19] = (unsigned char)(r->header.cupsHeight);
1141     appleheader[20] = (unsigned char)(r->header.HWResolution[0] >> 24);
1142     appleheader[21] = (unsigned char)(r->header.HWResolution[0] >> 16);
1143     appleheader[22] = (unsigned char)(r->header.HWResolution[0] >> 8);
1144     appleheader[23] = (unsigned char)(r->header.HWResolution[0]);
1145 
1146     return (cups_raster_io(r, appleheader, sizeof(appleheader)) == sizeof(appleheader));
1147   }
1148   else
1149     return (cups_raster_io(r, (unsigned char *)&(r->header), sizeof(r->header))
1150 		== sizeof(r->header));
1151 }
1152 
1153 
1154 /*
1155  * 'cupsRasterWriteHeader2()' - Write a raster page header from a version 2
1156  *                              page header structure.
1157  *
1158  * The page header can be initialized using @link cupsRasterInitPWGHeader@.
1159  *
1160  * @since CUPS 1.2/macOS 10.5@
1161  */
1162 
1163 unsigned				/* O - 1 on success, 0 on failure */
cupsRasterWriteHeader2(cups_raster_t * r,cups_page_header2_t * h)1164 cupsRasterWriteHeader2(
1165     cups_raster_t       *r,		/* I - Raster stream */
1166     cups_page_header2_t *h)		/* I - Raster page header */
1167 {
1168   DEBUG_printf(("cupsRasterWriteHeader(r=%p, h=%p)", (void *)r, (void *)h));
1169 
1170   if (r == NULL || r->mode == CUPS_RASTER_READ)
1171   {
1172     DEBUG_puts("1cupsRasterWriteHeader2: Returning 0.");
1173     return (0);
1174   }
1175 
1176   DEBUG_printf(("1cupsRasterWriteHeader2: cupsColorSpace=%s", cups_color_spaces[h->cupsColorSpace]));
1177   DEBUG_printf(("1cupsRasterWriteHeader2: cupsBitsPerColor=%u", h->cupsBitsPerColor));
1178   DEBUG_printf(("1cupsRasterWriteHeader2: cupsBitsPerPixel=%u", h->cupsBitsPerPixel));
1179   DEBUG_printf(("1cupsRasterWriteHeader2: cupsBytesPerLine=%u", h->cupsBytesPerLine));
1180   DEBUG_printf(("1cupsRasterWriteHeader2: cupsWidth=%u", h->cupsWidth));
1181   DEBUG_printf(("1cupsRasterWriteHeader2: cupsHeight=%u", h->cupsHeight));
1182 
1183  /*
1184   * Make a copy of the header, and compute the number of raster
1185   * lines in the page image...
1186   */
1187 
1188   memcpy(&(r->header), h, sizeof(cups_page_header2_t));
1189 
1190   if (!cups_raster_update(r))
1191   {
1192     DEBUG_puts("1cupsRasterWriteHeader: Unable to update parameters, returning 0.");
1193     return (0);
1194   }
1195 
1196   if (r->mode == CUPS_RASTER_WRITE_APPLE)
1197   {
1198     r->rowheight = h->HWResolution[0] / h->HWResolution[1];
1199 
1200     if (h->HWResolution[0] != (r->rowheight * h->HWResolution[1]))
1201       return (0);
1202   }
1203   else
1204     r->rowheight = 1;
1205 
1206  /*
1207   * Write the raster header...
1208   */
1209 
1210   if (r->mode == CUPS_RASTER_WRITE_PWG)
1211   {
1212    /*
1213     * PWG raster data is always network byte order with most of the page header
1214     * zeroed.
1215     */
1216 
1217     cups_page_header2_t	fh;		/* File page header */
1218 
1219     memset(&fh, 0, sizeof(fh));
1220     strlcpy(fh.MediaClass, "PwgRaster", sizeof(fh.MediaClass));
1221     strlcpy(fh.MediaColor, r->header.MediaColor, sizeof(fh.MediaColor));
1222     strlcpy(fh.MediaType, r->header.MediaType, sizeof(fh.MediaType));
1223     strlcpy(fh.OutputType, r->header.OutputType, sizeof(fh.OutputType));
1224     strlcpy(fh.cupsRenderingIntent, r->header.cupsRenderingIntent,
1225             sizeof(fh.cupsRenderingIntent));
1226     strlcpy(fh.cupsPageSizeName, r->header.cupsPageSizeName,
1227             sizeof(fh.cupsPageSizeName));
1228 
1229     fh.CutMedia              = htonl(r->header.CutMedia);
1230     fh.Duplex                = htonl(r->header.Duplex);
1231     fh.HWResolution[0]       = htonl(r->header.HWResolution[0]);
1232     fh.HWResolution[1]       = htonl(r->header.HWResolution[1]);
1233     fh.ImagingBoundingBox[0] = htonl(r->header.ImagingBoundingBox[0]);
1234     fh.ImagingBoundingBox[1] = htonl(r->header.ImagingBoundingBox[1]);
1235     fh.ImagingBoundingBox[2] = htonl(r->header.ImagingBoundingBox[2]);
1236     fh.ImagingBoundingBox[3] = htonl(r->header.ImagingBoundingBox[3]);
1237     fh.InsertSheet           = htonl(r->header.InsertSheet);
1238     fh.Jog                   = htonl(r->header.Jog);
1239     fh.LeadingEdge           = htonl(r->header.LeadingEdge);
1240     fh.ManualFeed            = htonl(r->header.ManualFeed);
1241     fh.MediaPosition         = htonl(r->header.MediaPosition);
1242     fh.MediaWeight           = htonl(r->header.MediaWeight);
1243     fh.NumCopies             = htonl(r->header.NumCopies);
1244     fh.Orientation           = htonl(r->header.Orientation);
1245     fh.PageSize[0]           = htonl(r->header.PageSize[0]);
1246     fh.PageSize[1]           = htonl(r->header.PageSize[1]);
1247     fh.Tumble                = htonl(r->header.Tumble);
1248     fh.cupsWidth             = htonl(r->header.cupsWidth);
1249     fh.cupsHeight            = htonl(r->header.cupsHeight);
1250     fh.cupsBitsPerColor      = htonl(r->header.cupsBitsPerColor);
1251     fh.cupsBitsPerPixel      = htonl(r->header.cupsBitsPerPixel);
1252     fh.cupsBytesPerLine      = htonl(r->header.cupsBytesPerLine);
1253     fh.cupsColorOrder        = htonl(r->header.cupsColorOrder);
1254     fh.cupsColorSpace        = htonl(r->header.cupsColorSpace);
1255     fh.cupsNumColors         = htonl(r->header.cupsNumColors);
1256     fh.cupsInteger[0]        = htonl(r->header.cupsInteger[0]);
1257     fh.cupsInteger[1]        = htonl(r->header.cupsInteger[1]);
1258     fh.cupsInteger[2]        = htonl(r->header.cupsInteger[2]);
1259     fh.cupsInteger[3]        = htonl((unsigned)(r->header.cupsImagingBBox[0] * r->header.HWResolution[0] / 72.0));
1260     fh.cupsInteger[4]        = htonl((unsigned)(r->header.cupsImagingBBox[1] * r->header.HWResolution[1] / 72.0));
1261     fh.cupsInteger[5]        = htonl((unsigned)(r->header.cupsImagingBBox[2] * r->header.HWResolution[0] / 72.0));
1262     fh.cupsInteger[6]        = htonl((unsigned)(r->header.cupsImagingBBox[3] * r->header.HWResolution[1] / 72.0));
1263     fh.cupsInteger[7]        = htonl(0xffffff);
1264 
1265     return (cups_raster_io(r, (unsigned char *)&fh, sizeof(fh)) == sizeof(fh));
1266   }
1267   else if (r->mode == CUPS_RASTER_WRITE_APPLE)
1268   {
1269    /*
1270     * Raw raster data is always network byte order with most of the page header
1271     * zeroed.
1272     */
1273 
1274     unsigned char appleheader[32];	/* Raw page header */
1275     unsigned height = r->header.cupsHeight * r->rowheight;
1276 					/* Computed page height */
1277 
1278     if (r->apple_page_count == 0xffffffffU)
1279     {
1280      /*
1281       * Write raw page count from raster page header...
1282       */
1283 
1284       r->apple_page_count = r->header.cupsInteger[0];
1285 
1286       appleheader[0] = 'A';
1287       appleheader[1] = 'S';
1288       appleheader[2] = 'T';
1289       appleheader[3] = 0;
1290       appleheader[4] = (unsigned char)(r->apple_page_count >> 24);
1291       appleheader[5] = (unsigned char)(r->apple_page_count >> 16);
1292       appleheader[6] = (unsigned char)(r->apple_page_count >> 8);
1293       appleheader[7] = (unsigned char)(r->apple_page_count);
1294 
1295       if (cups_raster_io(r, appleheader, 8) != 8)
1296         return (0);
1297     }
1298 
1299     memset(appleheader, 0, sizeof(appleheader));
1300 
1301     appleheader[0]  = (unsigned char)r->header.cupsBitsPerPixel;
1302     appleheader[1]  = r->header.cupsColorSpace == CUPS_CSPACE_SRGB ? 1 :
1303                         r->header.cupsColorSpace == CUPS_CSPACE_RGBW ? 2 :
1304                         r->header.cupsColorSpace == CUPS_CSPACE_ADOBERGB ? 3 :
1305                         r->header.cupsColorSpace == CUPS_CSPACE_W ? 4 :
1306                         r->header.cupsColorSpace == CUPS_CSPACE_RGB ? 5 :
1307                         r->header.cupsColorSpace == CUPS_CSPACE_CMYK ? 6 : 0;
1308     appleheader[12] = (unsigned char)(r->header.cupsWidth >> 24);
1309     appleheader[13] = (unsigned char)(r->header.cupsWidth >> 16);
1310     appleheader[14] = (unsigned char)(r->header.cupsWidth >> 8);
1311     appleheader[15] = (unsigned char)(r->header.cupsWidth);
1312     appleheader[16] = (unsigned char)(height >> 24);
1313     appleheader[17] = (unsigned char)(height >> 16);
1314     appleheader[18] = (unsigned char)(height >> 8);
1315     appleheader[19] = (unsigned char)(height);
1316     appleheader[20] = (unsigned char)(r->header.HWResolution[0] >> 24);
1317     appleheader[21] = (unsigned char)(r->header.HWResolution[0] >> 16);
1318     appleheader[22] = (unsigned char)(r->header.HWResolution[0] >> 8);
1319     appleheader[23] = (unsigned char)(r->header.HWResolution[0]);
1320 
1321     return (cups_raster_io(r, appleheader, sizeof(appleheader)) == sizeof(appleheader));
1322   }
1323   else
1324     return (cups_raster_io(r, (unsigned char *)&(r->header), sizeof(r->header))
1325 		== sizeof(r->header));
1326 }
1327 
1328 
1329 /*
1330  * 'cupsRasterWritePixels()' - Write raster pixels.
1331  *
1332  * For best performance, filters should write one or more whole lines.
1333  * The "cupsBytesPerLine" value from the page header can be used to allocate
1334  * the line buffer and as the number of bytes to write.
1335  */
1336 
1337 unsigned				/* O - Number of bytes written */
cupsRasterWritePixels(cups_raster_t * r,unsigned char * p,unsigned len)1338 cupsRasterWritePixels(cups_raster_t *r,	/* I - Raster stream */
1339                       unsigned char *p,	/* I - Bytes to write */
1340 		      unsigned      len)/* I - Number of bytes to write */
1341 {
1342   ssize_t	bytes;			/* Bytes read */
1343   unsigned	remaining;		/* Bytes remaining */
1344 
1345 
1346   DEBUG_printf(("cupsRasterWritePixels(r=%p, p=%p, len=%u), remaining=%u", (void *)r, (void *)p, len, r->remaining));
1347 
1348   if (r == NULL || r->mode == CUPS_RASTER_READ || r->remaining == 0)
1349     return (0);
1350 
1351   if (!r->compressed)
1352   {
1353    /*
1354     * Without compression, just write the raster data raw unless the data needs
1355     * to be swapped...
1356     */
1357 
1358     r->remaining -= len / r->header.cupsBytesPerLine;
1359 
1360     if (r->swapped &&
1361         (r->header.cupsBitsPerColor == 16 ||
1362          r->header.cupsBitsPerPixel == 12 ||
1363          r->header.cupsBitsPerPixel == 16))
1364     {
1365       unsigned char	*bufptr;	/* Pointer into write buffer */
1366 
1367      /*
1368       * Allocate a write buffer as needed...
1369       */
1370 
1371       if ((size_t)len > r->bufsize)
1372       {
1373 	if (r->buffer)
1374 	  bufptr = realloc(r->buffer, len);
1375 	else
1376 	  bufptr = malloc(len);
1377 
1378 	if (!bufptr)
1379 	  return (0);
1380 
1381 	r->buffer  = bufptr;
1382 	r->bufsize = len;
1383       }
1384 
1385      /*
1386       * Byte swap the pixels and write them...
1387       */
1388 
1389       cups_swap_copy(r->buffer, p, len);
1390 
1391       bytes = cups_raster_io(r, r->buffer, len);
1392     }
1393     else
1394       bytes = cups_raster_io(r, p, len);
1395 
1396     if (bytes < len)
1397       return (0);
1398     else
1399       return (len);
1400   }
1401 
1402  /*
1403   * Otherwise, compress each line...
1404   */
1405 
1406   for (remaining = len; remaining > 0; remaining -= (unsigned)bytes, p += bytes)
1407   {
1408    /*
1409     * Figure out the number of remaining bytes on the current line...
1410     */
1411 
1412     if ((bytes = (ssize_t)remaining) > (ssize_t)(r->pend - r->pcurrent))
1413       bytes = (ssize_t)(r->pend - r->pcurrent);
1414 
1415     if (r->count > 0)
1416     {
1417      /*
1418       * Check to see if this line is the same as the previous line...
1419       */
1420 
1421       if (memcmp(p, r->pcurrent, (size_t)bytes))
1422       {
1423         if (cups_raster_write(r, r->pixels) <= 0)
1424 	  return (0);
1425 
1426 	r->count = 0;
1427       }
1428       else
1429       {
1430        /*
1431         * Mark more bytes as the same...
1432 	*/
1433 
1434         r->pcurrent += bytes;
1435 
1436 	if (r->pcurrent >= r->pend)
1437 	{
1438 	 /*
1439           * Increase the repeat count...
1440 	  */
1441 
1442 	  r->count += r->rowheight;
1443 	  r->pcurrent = r->pixels;
1444 
1445 	 /*
1446           * Flush out this line if it is the last one...
1447 	  */
1448 
1449 	  r->remaining --;
1450 
1451 	  if (r->remaining == 0)
1452 	  {
1453 	    if (cups_raster_write(r, r->pixels) <= 0)
1454 	      return (0);
1455 	    else
1456 	      return (len);
1457 	  }
1458 	  else if (r->count > (256 - r->rowheight))
1459 	  {
1460 	    if (cups_raster_write(r, r->pixels) <= 0)
1461 	      return (0);
1462 
1463 	    r->count = 0;
1464 	  }
1465 	}
1466 
1467 	continue;
1468       }
1469     }
1470 
1471     if (r->count == 0)
1472     {
1473      /*
1474       * Copy the raster data to the buffer...
1475       */
1476 
1477       memcpy(r->pcurrent, p, (size_t)bytes);
1478 
1479       r->pcurrent += bytes;
1480 
1481       if (r->pcurrent >= r->pend)
1482       {
1483        /*
1484         * Increase the repeat count...
1485 	*/
1486 
1487 	r->count += r->rowheight;
1488 	r->pcurrent = r->pixels;
1489 
1490        /*
1491         * Flush out this line if it is the last one...
1492 	*/
1493 
1494 	r->remaining --;
1495 
1496 	if (r->remaining == 0)
1497 	{
1498 	  if (cups_raster_write(r, r->pixels) <= 0)
1499 	    return (0);
1500 	}
1501       }
1502     }
1503   }
1504 
1505   return (len);
1506 }
1507 
1508 
1509 /*
1510  * 'cups_raster_read_header()' - Read a raster page header.
1511  */
1512 
1513 static unsigned				/* O - 1 on success, 0 on fail */
cups_raster_read_header(cups_raster_t * r)1514 cups_raster_read_header(
1515     cups_raster_t *r)			/* I - Raster stream */
1516 {
1517   size_t	len;			/* Length for read/swap */
1518 
1519 
1520   DEBUG_printf(("3cups_raster_read_header(r=%p), r->mode=%s", (void *)r, r ? cups_modes[r->mode] : ""));
1521 
1522   if (r == NULL || r->mode != CUPS_RASTER_READ)
1523     return (0);
1524 
1525   DEBUG_printf(("4cups_raster_read_header: r->iocount=" CUPS_LLFMT, CUPS_LLCAST r->iocount));
1526 
1527   memset(&(r->header), 0, sizeof(r->header));
1528 
1529  /*
1530   * Read the header...
1531   */
1532 
1533   switch (r->sync)
1534   {
1535     default :
1536        /*
1537 	* Get the length of the raster header...
1538 	*/
1539 
1540 	if (r->sync == CUPS_RASTER_SYNCv1 || r->sync == CUPS_RASTER_REVSYNCv1)
1541 	  len = sizeof(cups_page_header_t);
1542 	else
1543 	  len = sizeof(cups_page_header2_t);
1544 
1545 	DEBUG_printf(("4cups_raster_read_header: len=%d", (int)len));
1546 
1547        /*
1548         * Read it...
1549         */
1550 
1551 	if (cups_raster_read(r, (unsigned char *)&(r->header), len) < (ssize_t)len)
1552 	{
1553 	  DEBUG_printf(("4cups_raster_read_header: EOF, r->iocount=" CUPS_LLFMT, CUPS_LLCAST r->iocount));
1554 	  return (0);
1555 	}
1556 
1557        /*
1558 	* Swap bytes as needed...
1559 	*/
1560 
1561 	if (r->swapped)
1562 	{
1563 	  unsigned	*s,		/* Current word */
1564 			temp;		/* Temporary copy */
1565 
1566 
1567 	  DEBUG_puts("4cups_raster_read_header: Swapping header bytes.");
1568 
1569 	  for (len = 81, s = &(r->header.AdvanceDistance);
1570 	       len > 0;
1571 	       len --, s ++)
1572 	  {
1573 	    temp = *s;
1574 	    *s   = ((temp & 0xff) << 24) |
1575 		   ((temp & 0xff00) << 8) |
1576 		   ((temp & 0xff0000) >> 8) |
1577 		   ((temp & 0xff000000) >> 24);
1578 
1579 	    DEBUG_printf(("4cups_raster_read_header: %08x => %08x", temp, *s));
1580 	  }
1581 	}
1582         break;
1583 
1584     case CUPS_RASTER_SYNCapple :
1585     case CUPS_RASTER_REVSYNCapple :
1586         {
1587           unsigned char	appleheader[32];	/* Raw header */
1588           static const unsigned rawcspace[] =
1589           {
1590             CUPS_CSPACE_SW,
1591             CUPS_CSPACE_SRGB,
1592             CUPS_CSPACE_RGBW,
1593             CUPS_CSPACE_ADOBERGB,
1594             CUPS_CSPACE_W,
1595             CUPS_CSPACE_RGB,
1596             CUPS_CSPACE_CMYK
1597           };
1598           static const unsigned rawnumcolors[] =
1599           {
1600             1,
1601             3,
1602             4,
1603             3,
1604             1,
1605             3,
1606             4
1607           };
1608 
1609 	  if (cups_raster_read(r, appleheader, sizeof(appleheader)) < (ssize_t)sizeof(appleheader))
1610 	  {
1611 	    DEBUG_printf(("4cups_raster_read_header: EOF, r->iocount=" CUPS_LLFMT, CUPS_LLCAST r->iocount));
1612 	    return (0);
1613 	  }
1614 
1615 	  strlcpy(r->header.MediaClass, "PwgRaster", sizeof(r->header.MediaClass));
1616 					      /* PwgRaster */
1617           r->header.cupsBitsPerPixel = appleheader[0];
1618           r->header.cupsColorSpace   = appleheader[1] >= (sizeof(rawcspace) / sizeof(rawcspace[0])) ? CUPS_CSPACE_DEVICE1 : rawcspace[appleheader[1]];
1619           r->header.cupsNumColors    = appleheader[1] >= (sizeof(rawnumcolors) / sizeof(rawnumcolors[0])) ? 1 : rawnumcolors[appleheader[1]];
1620           r->header.cupsBitsPerColor = r->header.cupsBitsPerPixel / r->header.cupsNumColors;
1621           r->header.cupsWidth        = ((((((unsigned)appleheader[12] << 8) | (unsigned)appleheader[13]) << 8) | (unsigned)appleheader[14]) << 8) | (unsigned)appleheader[15];
1622           r->header.cupsHeight       = ((((((unsigned)appleheader[16] << 8) | (unsigned)appleheader[17]) << 8) | (unsigned)appleheader[18]) << 8) | (unsigned)appleheader[19];
1623           r->header.cupsBytesPerLine = r->header.cupsWidth * r->header.cupsBitsPerPixel / 8;
1624           r->header.cupsColorOrder   = CUPS_ORDER_CHUNKED;
1625           r->header.HWResolution[0]  = r->header.HWResolution[1] = ((((((unsigned)appleheader[20] << 8) | (unsigned)appleheader[21]) << 8) | (unsigned)appleheader[22]) << 8) | (unsigned)appleheader[23];
1626 
1627           if (r->header.HWResolution[0] > 0)
1628           {
1629 	    r->header.PageSize[0]     = (unsigned)(r->header.cupsWidth * 72 / r->header.HWResolution[0]);
1630 	    r->header.PageSize[1]     = (unsigned)(r->header.cupsHeight * 72 / r->header.HWResolution[1]);
1631 	    r->header.cupsPageSize[0] = (float)(r->header.cupsWidth * 72.0 / r->header.HWResolution[0]);
1632 	    r->header.cupsPageSize[1] = (float)(r->header.cupsHeight * 72.0 / r->header.HWResolution[1]);
1633           }
1634 
1635           r->header.cupsInteger[0] = r->apple_page_count;
1636           r->header.cupsInteger[7] = 0xffffff;
1637         }
1638         break;
1639   }
1640 
1641  /*
1642   * Update the header and row count...
1643   */
1644 
1645   if (!cups_raster_update(r))
1646     return (0);
1647 
1648   DEBUG_printf(("4cups_raster_read_header: cupsBitsPerPixel=%u, cupsBitsPerColor=%u, cupsBytesPerLine=%u, cupsWidth=%u, cupsHeight=%u, r->bpp=%d", r->header.cupsBitsPerPixel, r->header.cupsBitsPerColor, r->header.cupsBytesPerLine, r->header.cupsWidth, r->header.cupsHeight, r->bpp));
1649 
1650   return (r->header.cupsBitsPerPixel > 0 && r->header.cupsBitsPerPixel <= 240 && r->header.cupsBitsPerColor > 0 && r->header.cupsBitsPerColor <= 16 && r->header.cupsBytesPerLine > 0 && r->header.cupsBytesPerLine <= 0x7fffffff && r->header.cupsHeight != 0 && (r->header.cupsBytesPerLine % r->bpp) == 0);
1651 }
1652 
1653 
1654 /*
1655  * 'cups_raster_io()' - Read/write bytes from a context, handling interruptions.
1656  */
1657 
1658 static ssize_t				/* O - Bytes read/write or -1 */
cups_raster_io(cups_raster_t * r,unsigned char * buf,size_t bytes)1659 cups_raster_io(cups_raster_t *r,	/* I - Raster stream */
1660                unsigned char *buf,	/* I - Buffer for read/write */
1661                size_t        bytes)	/* I - Number of bytes to read/write */
1662 {
1663   ssize_t	count,			/* Number of bytes read/written */
1664 		total;			/* Total bytes read/written */
1665 
1666 
1667   DEBUG_printf(("5cups_raster_io(r=%p, buf=%p, bytes=" CUPS_LLFMT ")", (void *)r, (void *)buf, CUPS_LLCAST bytes));
1668 
1669   for (total = 0; total < (ssize_t)bytes; total += count, buf += count)
1670   {
1671     count = (*r->iocb)(r->ctx, buf, bytes - (size_t)total);
1672 
1673     DEBUG_printf(("6cups_raster_io: count=%d, total=%d", (int)count, (int)total));
1674     if (count == 0)
1675       break;
1676     else if (count < 0)
1677     {
1678       DEBUG_puts("6cups_raster_io: Returning -1 on error.");
1679       return (-1);
1680     }
1681 
1682 #ifdef DEBUG
1683     r->iocount += (size_t)count;
1684 #endif /* DEBUG */
1685   }
1686 
1687   DEBUG_printf(("6cups_raster_io: iocount=" CUPS_LLFMT, CUPS_LLCAST r->iocount));
1688   DEBUG_printf(("6cups_raster_io: Returning " CUPS_LLFMT ".", CUPS_LLCAST total));
1689 
1690   return (total);
1691 }
1692 
1693 
1694 /*
1695  * 'cups_raster_read()' - Read through the raster buffer.
1696  */
1697 
1698 static ssize_t				/* O - Number of bytes read */
cups_raster_read(cups_raster_t * r,unsigned char * buf,size_t bytes)1699 cups_raster_read(cups_raster_t *r,	/* I - Raster stream */
1700                  unsigned char *buf,	/* I - Buffer */
1701                  size_t        bytes)	/* I - Number of bytes to read */
1702 {
1703   ssize_t	count,			/* Number of bytes read */
1704 		remaining,		/* Remaining bytes in buffer */
1705 		total;			/* Total bytes read */
1706 
1707 
1708   DEBUG_printf(("4cups_raster_read(r=%p, buf=%p, bytes=" CUPS_LLFMT "), offset=" CUPS_LLFMT, (void *)r, (void *)buf, CUPS_LLCAST bytes, CUPS_LLCAST (r->iostart + r->bufptr - r->buffer)));
1709 
1710   if (!r->compressed)
1711     return (cups_raster_io(r, buf, bytes));
1712 
1713  /*
1714   * Allocate a read buffer as needed...
1715   */
1716 
1717   count = (ssize_t)(2 * r->header.cupsBytesPerLine);
1718   if (count < 65536)
1719     count = 65536;
1720 
1721   if ((size_t)count > r->bufsize)
1722   {
1723     ssize_t offset = r->bufptr - r->buffer;
1724 					/* Offset to current start of buffer */
1725     ssize_t end = r->bufend - r->buffer;/* Offset to current end of buffer */
1726     unsigned char *rptr;		/* Pointer in read buffer */
1727 
1728     if (r->buffer)
1729       rptr = realloc(r->buffer, (size_t)count);
1730     else
1731       rptr = malloc((size_t)count);
1732 
1733     if (!rptr)
1734       return (0);
1735 
1736     r->buffer  = rptr;
1737     r->bufptr  = rptr + offset;
1738     r->bufend  = rptr + end;
1739     r->bufsize = (size_t)count;
1740   }
1741 
1742  /*
1743   * Loop until we have read everything...
1744   */
1745 
1746   for (total = 0, remaining = (int)(r->bufend - r->bufptr);
1747        total < (ssize_t)bytes;
1748        total += count, buf += count)
1749   {
1750     count = (ssize_t)bytes - total;
1751 
1752     DEBUG_printf(("5cups_raster_read: count=" CUPS_LLFMT ", remaining=" CUPS_LLFMT ", buf=%p, bufptr=%p, bufend=%p", CUPS_LLCAST count, CUPS_LLCAST remaining, (void *)buf, (void *)r->bufptr, (void *)r->bufend));
1753 
1754     if (remaining == 0)
1755     {
1756       if (count < 16)
1757       {
1758        /*
1759         * Read into the raster buffer and then copy...
1760 	*/
1761 
1762 #ifdef DEBUG
1763         r->iostart += (size_t)(r->bufend - r->buffer);
1764 #endif /* DEBUG */
1765 
1766         remaining = (*r->iocb)(r->ctx, r->buffer, r->bufsize);
1767 	if (remaining <= 0)
1768 	  return (0);
1769 
1770 	r->bufptr = r->buffer;
1771 	r->bufend = r->buffer + remaining;
1772 
1773 #ifdef DEBUG
1774         r->iocount += (size_t)remaining;
1775 #endif /* DEBUG */
1776       }
1777       else
1778       {
1779        /*
1780         * Read directly into "buf"...
1781 	*/
1782 
1783 	count = (*r->iocb)(r->ctx, buf, (size_t)count);
1784 
1785 	if (count <= 0)
1786 	  return (0);
1787 
1788 #ifdef DEBUG
1789 	r->iostart += (size_t)count;
1790         r->iocount += (size_t)count;
1791 #endif /* DEBUG */
1792 
1793 	continue;
1794       }
1795     }
1796 
1797    /*
1798     * Copy bytes from raster buffer to "buf"...
1799     */
1800 
1801     if (count > remaining)
1802       count = remaining;
1803 
1804     if (count == 1)
1805     {
1806      /*
1807       * Copy 1 byte...
1808       */
1809 
1810       *buf = *(r->bufptr)++;
1811       remaining --;
1812     }
1813     else if (count < 128)
1814     {
1815      /*
1816       * Copy up to 127 bytes without using memcpy(); this is
1817       * faster because it avoids an extra function call and is
1818       * often further optimized by the compiler...
1819       */
1820 
1821       unsigned char	*bufptr;	/* Temporary buffer pointer */
1822 
1823       remaining -= count;
1824 
1825       for (bufptr = r->bufptr; count > 0; count --, total ++)
1826 	*buf++ = *bufptr++;
1827 
1828       r->bufptr = bufptr;
1829     }
1830     else
1831     {
1832      /*
1833       * Use memcpy() for a large read...
1834       */
1835 
1836       memcpy(buf, r->bufptr, (size_t)count);
1837       r->bufptr += count;
1838       remaining -= count;
1839     }
1840   }
1841 
1842   DEBUG_printf(("5cups_raster_read: Returning %ld", (long)total));
1843 
1844   return (total);
1845 }
1846 
1847 
1848 /*
1849  * 'cups_raster_update()' - Update the raster header and row count for the
1850  *                          current page.
1851  */
1852 
1853 static int				/* O - 1 on success, 0 on failure */
cups_raster_update(cups_raster_t * r)1854 cups_raster_update(cups_raster_t *r)	/* I - Raster stream */
1855 {
1856   if (r->sync == CUPS_RASTER_SYNCv1 || r->sync == CUPS_RASTER_REVSYNCv1 ||
1857       r->header.cupsNumColors == 0)
1858   {
1859    /*
1860     * Set the "cupsNumColors" field according to the colorspace...
1861     */
1862 
1863     switch (r->header.cupsColorSpace)
1864     {
1865       case CUPS_CSPACE_W :
1866       case CUPS_CSPACE_K :
1867       case CUPS_CSPACE_WHITE :
1868       case CUPS_CSPACE_GOLD :
1869       case CUPS_CSPACE_SILVER :
1870       case CUPS_CSPACE_SW :
1871           r->header.cupsNumColors = 1;
1872 	  break;
1873 
1874       case CUPS_CSPACE_RGB :
1875       case CUPS_CSPACE_CMY :
1876       case CUPS_CSPACE_YMC :
1877       case CUPS_CSPACE_CIEXYZ :
1878       case CUPS_CSPACE_CIELab :
1879       case CUPS_CSPACE_SRGB :
1880       case CUPS_CSPACE_ADOBERGB :
1881       case CUPS_CSPACE_ICC1 :
1882       case CUPS_CSPACE_ICC2 :
1883       case CUPS_CSPACE_ICC3 :
1884       case CUPS_CSPACE_ICC4 :
1885       case CUPS_CSPACE_ICC5 :
1886       case CUPS_CSPACE_ICC6 :
1887       case CUPS_CSPACE_ICC7 :
1888       case CUPS_CSPACE_ICC8 :
1889       case CUPS_CSPACE_ICC9 :
1890       case CUPS_CSPACE_ICCA :
1891       case CUPS_CSPACE_ICCB :
1892       case CUPS_CSPACE_ICCC :
1893       case CUPS_CSPACE_ICCD :
1894       case CUPS_CSPACE_ICCE :
1895       case CUPS_CSPACE_ICCF :
1896           r->header.cupsNumColors = 3;
1897 	  break;
1898 
1899       case CUPS_CSPACE_RGBA :
1900       case CUPS_CSPACE_RGBW :
1901       case CUPS_CSPACE_CMYK :
1902       case CUPS_CSPACE_YMCK :
1903       case CUPS_CSPACE_KCMY :
1904       case CUPS_CSPACE_GMCK :
1905       case CUPS_CSPACE_GMCS :
1906           r->header.cupsNumColors = 4;
1907 	  break;
1908 
1909       case CUPS_CSPACE_KCMYcm :
1910           if (r->header.cupsBitsPerPixel < 8)
1911             r->header.cupsNumColors = 6;
1912 	  else
1913             r->header.cupsNumColors = 4;
1914 	  break;
1915 
1916       case CUPS_CSPACE_DEVICE1 :
1917       case CUPS_CSPACE_DEVICE2 :
1918       case CUPS_CSPACE_DEVICE3 :
1919       case CUPS_CSPACE_DEVICE4 :
1920       case CUPS_CSPACE_DEVICE5 :
1921       case CUPS_CSPACE_DEVICE6 :
1922       case CUPS_CSPACE_DEVICE7 :
1923       case CUPS_CSPACE_DEVICE8 :
1924       case CUPS_CSPACE_DEVICE9 :
1925       case CUPS_CSPACE_DEVICEA :
1926       case CUPS_CSPACE_DEVICEB :
1927       case CUPS_CSPACE_DEVICEC :
1928       case CUPS_CSPACE_DEVICED :
1929       case CUPS_CSPACE_DEVICEE :
1930       case CUPS_CSPACE_DEVICEF :
1931           r->header.cupsNumColors = r->header.cupsColorSpace -
1932 	                            CUPS_CSPACE_DEVICE1 + 1;
1933 	  break;
1934 
1935       default :
1936           /* Unknown color space */
1937           return (0);
1938     }
1939   }
1940 
1941  /*
1942   * Set the number of bytes per pixel/color...
1943   */
1944 
1945   if (r->header.cupsColorOrder == CUPS_ORDER_CHUNKED)
1946     r->bpp = (r->header.cupsBitsPerPixel + 7) / 8;
1947   else
1948     r->bpp = (r->header.cupsBitsPerColor + 7) / 8;
1949 
1950   if (r->bpp == 0)
1951     r->bpp = 1;
1952 
1953  /*
1954   * Set the number of remaining rows...
1955   */
1956 
1957   if (r->header.cupsColorOrder == CUPS_ORDER_PLANAR)
1958     r->remaining = r->header.cupsHeight * r->header.cupsNumColors;
1959   else
1960     r->remaining = r->header.cupsHeight;
1961 
1962  /*
1963   * Allocate the compression buffer...
1964   */
1965 
1966   if (r->compressed)
1967   {
1968     if (r->pixels != NULL)
1969       free(r->pixels);
1970 
1971     if ((r->pixels = calloc(r->header.cupsBytesPerLine, 1)) == NULL)
1972     {
1973       r->pcurrent = NULL;
1974       r->pend     = NULL;
1975       r->count    = 0;
1976 
1977       return (0);
1978     }
1979 
1980     r->pcurrent = r->pixels;
1981     r->pend     = r->pixels + r->header.cupsBytesPerLine;
1982     r->count    = 0;
1983   }
1984 
1985   return (1);
1986 }
1987 
1988 
1989 /*
1990  * 'cups_raster_write()' - Write a row of compressed raster data...
1991  */
1992 
1993 static ssize_t				/* O - Number of bytes written */
cups_raster_write(cups_raster_t * r,const unsigned char * pixels)1994 cups_raster_write(
1995     cups_raster_t       *r,		/* I - Raster stream */
1996     const unsigned char *pixels)	/* I - Pixel data to write */
1997 {
1998   const unsigned char	*start,		/* Start of sequence */
1999 			*ptr,		/* Current pointer in sequence */
2000 			*pend,		/* End of raster buffer */
2001 			*plast;		/* Pointer to last pixel */
2002   unsigned char		*wptr;		/* Pointer into write buffer */
2003   unsigned		bpp,		/* Bytes per pixel */
2004 			count;		/* Count */
2005   _cups_copyfunc_t	cf;		/* Copy function */
2006 
2007 
2008   DEBUG_printf(("3cups_raster_write(r=%p, pixels=%p)", (void *)r, (void *)pixels));
2009 
2010  /*
2011   * Determine whether we need to swap bytes...
2012   */
2013 
2014   if (r->swapped && (r->header.cupsBitsPerColor == 16 || r->header.cupsBitsPerPixel == 12 || r->header.cupsBitsPerPixel == 16))
2015   {
2016     DEBUG_puts("4cups_raster_write: Swapping bytes when writing.");
2017     cf = (_cups_copyfunc_t)cups_swap_copy;
2018   }
2019   else
2020     cf = (_cups_copyfunc_t)memcpy;
2021 
2022   /*
2023   * Allocate a write buffer as needed...
2024   */
2025 
2026   count = r->header.cupsBytesPerLine * 2;
2027   if (count < 65536)
2028     count = 65536;
2029 
2030   if ((size_t)count > r->bufsize)
2031   {
2032     if (r->buffer)
2033       wptr = realloc(r->buffer, count);
2034     else
2035       wptr = malloc(count);
2036 
2037     if (!wptr)
2038     {
2039       DEBUG_printf(("4cups_raster_write: Unable to allocate " CUPS_LLFMT " bytes for raster buffer: %s", CUPS_LLCAST count, strerror(errno)));
2040       return (-1);
2041     }
2042 
2043     r->buffer  = wptr;
2044     r->bufsize = count;
2045   }
2046 
2047  /*
2048   * Write the row repeat count...
2049   */
2050 
2051   bpp     = r->bpp;
2052   pend    = pixels + r->header.cupsBytesPerLine;
2053   plast   = pend - bpp;
2054   wptr    = r->buffer;
2055   *wptr++ = (unsigned char)(r->count - 1);
2056 
2057  /*
2058   * Write using a modified PackBits compression...
2059   */
2060 
2061   for (ptr = pixels; ptr < pend;)
2062   {
2063     start = ptr;
2064     ptr += bpp;
2065 
2066     if (ptr == pend)
2067     {
2068      /*
2069       * Encode a single pixel at the end...
2070       */
2071 
2072       *wptr++ = 0;
2073       (*cf)(wptr, start, bpp);
2074       wptr += bpp;
2075     }
2076     else if (!memcmp(start, ptr, bpp))
2077     {
2078      /*
2079       * Encode a sequence of repeating pixels...
2080       */
2081 
2082       for (count = 2; count < 128 && ptr < plast; count ++, ptr += bpp)
2083         if (memcmp(ptr, ptr + bpp, bpp))
2084 	  break;
2085 
2086       *wptr++ = (unsigned char)(count - 1);
2087       (*cf)(wptr, ptr, bpp);
2088       wptr += bpp;
2089       ptr  += bpp;
2090     }
2091     else
2092     {
2093      /*
2094       * Encode a sequence of non-repeating pixels...
2095       */
2096 
2097       for (count = 1; count < 128 && ptr < plast; count ++, ptr += bpp)
2098         if (!memcmp(ptr, ptr + bpp, bpp))
2099 	  break;
2100 
2101       if (ptr >= plast && count < 128)
2102       {
2103         count ++;
2104 	ptr += bpp;
2105       }
2106 
2107       *wptr++ = (unsigned char)(257 - count);
2108 
2109       count *= bpp;
2110       (*cf)(wptr, start, count);
2111       wptr += count;
2112     }
2113   }
2114 
2115   DEBUG_printf(("4cups_raster_write: Writing " CUPS_LLFMT " bytes.", CUPS_LLCAST (wptr - r->buffer)));
2116 
2117   return (cups_raster_io(r, r->buffer, (size_t)(wptr - r->buffer)));
2118 }
2119 
2120 
2121 /*
2122  * 'cups_read_fd()' - Read bytes from a file.
2123  */
2124 
2125 static ssize_t				/* O - Bytes read or -1 */
cups_read_fd(void * ctx,unsigned char * buf,size_t bytes)2126 cups_read_fd(void          *ctx,	/* I - File descriptor as pointer */
2127              unsigned char *buf,	/* I - Buffer for read */
2128 	     size_t        bytes)	/* I - Maximum number of bytes to read */
2129 {
2130   int		fd = (int)((intptr_t)ctx);
2131 					/* File descriptor */
2132   ssize_t	count;			/* Number of bytes read */
2133 
2134 
2135 #ifdef _WIN32 /* Sigh */
2136   while ((count = read(fd, buf, (unsigned)bytes)) < 0)
2137 #else
2138   while ((count = read(fd, buf, bytes)) < 0)
2139 #endif /* _WIN32 */
2140     if (errno != EINTR && errno != EAGAIN)
2141     {
2142       DEBUG_printf(("8cups_read_fd: %s", strerror(errno)));
2143       return (-1);
2144     }
2145 
2146   DEBUG_printf(("8cups_read_fd: Returning %d bytes.", (int)count));
2147 
2148   return (count);
2149 }
2150 
2151 
2152 /*
2153  * 'cups_swap()' - Swap bytes in raster data...
2154  */
2155 
2156 static void
cups_swap(unsigned char * buf,size_t bytes)2157 cups_swap(unsigned char *buf,		/* I - Buffer to swap */
2158           size_t        bytes)		/* I - Number of bytes to swap */
2159 {
2160   unsigned char	even, odd;		/* Temporary variables */
2161 
2162 
2163   bytes /= 2;
2164 
2165   while (bytes > 0)
2166   {
2167     even   = buf[0];
2168     odd    = buf[1];
2169     buf[0] = odd;
2170     buf[1] = even;
2171 
2172     buf += 2;
2173     bytes --;
2174   }
2175 }
2176 
2177 
2178 /*
2179  * 'cups_swap_copy()' - Copy and swap bytes in raster data...
2180  */
2181 
2182 static void
cups_swap_copy(unsigned char * dst,const unsigned char * src,size_t bytes)2183 cups_swap_copy(
2184     unsigned char       *dst,		/* I - Destination */
2185     const unsigned char *src,		/* I - Source */
2186     size_t              bytes)		/* I - Number of bytes to swap */
2187 {
2188   bytes /= 2;
2189 
2190   while (bytes > 0)
2191   {
2192     dst[0] = src[1];
2193     dst[1] = src[0];
2194 
2195     dst += 2;
2196     src += 2;
2197     bytes --;
2198   }
2199 }
2200 
2201 
2202 /*
2203  * 'cups_write_fd()' - Write bytes to a file.
2204  */
2205 
2206 static ssize_t				/* O - Bytes written or -1 */
cups_write_fd(void * ctx,unsigned char * buf,size_t bytes)2207 cups_write_fd(void          *ctx,	/* I - File descriptor pointer */
2208               unsigned char *buf,	/* I - Bytes to write */
2209 	      size_t        bytes)	/* I - Number of bytes to write */
2210 {
2211   int		fd = (int)((intptr_t)ctx);
2212 					/* File descriptor */
2213   ssize_t	count;			/* Number of bytes written */
2214 
2215 
2216 #ifdef _WIN32 /* Sigh */
2217   while ((count = write(fd, buf, (unsigned)bytes)) < 0)
2218 #else
2219   while ((count = write(fd, buf, bytes)) < 0)
2220 #endif /* _WIN32 */
2221     if (errno != EINTR && errno != EAGAIN)
2222     {
2223       DEBUG_printf(("8cups_write_fd: %s", strerror(errno)));
2224       return (-1);
2225     }
2226 
2227   return (count);
2228 }
2229