Coverage Report

Created: 2025-06-24 07:01

/src/ghostpdl/devices/vector/gdevpdfj.c
Line
Count
Source (jump to first uncovered line)
1
/* Copyright (C) 2001-2025 Artifex Software, Inc.
2
   All Rights Reserved.
3
4
   This software is provided AS-IS with no warranty, either express or
5
   implied.
6
7
   This software is distributed under license and may not be copied,
8
   modified or distributed except as expressly authorized under the terms
9
   of the license contained in the file LICENSE in this distribution.
10
11
   Refer to licensing information at http://www.artifex.com or contact
12
   Artifex Software, Inc.,  39 Mesa Street, Suite 108A, San Francisco,
13
   CA 94129, USA, for further information.
14
*/
15
16
17
/* Image-writing utilities for pdfwrite driver */
18
#include "memory_.h"
19
#include "gx.h"
20
#include "gserrors.h"
21
#include "gdevpdfx.h"
22
#include "gdevpdfg.h"
23
#include "gdevpdfo.h"
24
#include "gxcspace.h"
25
#include "gsiparm4.h"
26
#include "gdevpsds.h"
27
#include "spngpx.h"
28
#include <stdlib.h> /* for atoi */
29
30
#define CHECK(expr)\
31
2.72M
  BEGIN if ((code = (expr)) < 0) return code; END
32
33
/* GC descriptors */
34
public_st_pdf_image_writer();
35
0
static ENUM_PTRS_WITH(pdf_image_writer_enum_ptrs, pdf_image_writer *piw)
36
0
     index -= 4;
37
0
     if (index < psdf_binary_writer_max_ptrs * piw->alt_writer_count) {
38
0
         gs_ptr_type_t ret =
39
0
             ENUM_USING(st_psdf_binary_writer, &piw->binary[index / psdf_binary_writer_max_ptrs],
40
0
                        sizeof(psdf_binary_writer), index % psdf_binary_writer_max_ptrs);
41
42
0
         if (ret == 0)   /* don't stop early */
43
0
             ENUM_RETURN(0);
44
0
         return ret;
45
0
    }
46
0
    return 0;
47
0
case 0: ENUM_RETURN(piw->pres);
48
0
case 1: ENUM_RETURN(piw->data);
49
0
case 2: ENUM_RETURN(piw->named);
50
0
case 3: ENUM_RETURN(piw->pres_mask);
51
0
ENUM_PTRS_END
52
0
static RELOC_PTRS_WITH(pdf_image_writer_reloc_ptrs, pdf_image_writer *piw)
53
0
{
54
0
    int i;
55
56
0
    for (i = 0; i < piw->alt_writer_count; ++i)
57
0
        RELOC_USING(st_psdf_binary_writer, &piw->binary[i],
58
0
                    sizeof(psdf_binary_writer));
59
0
    RELOC_VAR(piw->pres);
60
0
    RELOC_VAR(piw->data);
61
0
    RELOC_VAR(piw->named);
62
0
    RELOC_VAR(piw->pres_mask);
63
0
}
64
0
RELOC_PTRS_END
65
66
/* ---------------- Image stream dictionaries ---------------- */
67
68
const pdf_image_names_t pdf_image_names_full = {
69
    { PDF_COLOR_SPACE_NAMES },
70
    { PDF_FILTER_NAMES },
71
    PDF_IMAGE_PARAM_NAMES
72
};
73
const pdf_image_names_t pdf_image_names_short = {
74
    { PDF_COLOR_SPACE_NAMES_SHORT },
75
    { PDF_FILTER_NAMES_SHORT },
76
    PDF_IMAGE_PARAM_NAMES_SHORT
77
};
78
79
/* Store the values of image parameters other than filters. */
80
/* pdev is used only for updating procsets. */
81
/* pcsvalue is not used for masks. */
82
static int
83
pdf_put_pixel_image_values(cos_dict_t *pcd, gx_device_pdf *pdev,
84
                           const gs_pixel_image_t *pim,
85
                           const gs_color_space *pcs,
86
                           const pdf_image_names_t *pin,
87
                           const cos_value_t *pcsvalue)
88
221k
{
89
221k
    int num_components;
90
221k
    float indexed_decode[2];
91
221k
    const float *default_decode = NULL;
92
221k
    int code;
93
94
221k
    if (pcs) {
95
27.8k
        CHECK(cos_dict_put_c_key(pcd, pin->ColorSpace, pcsvalue));
96
27.8k
        pdf_color_space_procsets(pdev, pcs);
97
27.8k
        num_components = gs_color_space_num_components(pcs);
98
27.8k
        if (gs_color_space_get_index(pcs) == gs_color_space_index_Indexed) {
99
1.89k
            indexed_decode[0] = 0;
100
1.89k
            indexed_decode[1] = (float)((1 << pim->BitsPerComponent) - 1);
101
1.89k
            default_decode = indexed_decode;
102
1.89k
        }
103
27.8k
    } else
104
193k
        num_components = 1;
105
221k
    CHECK(cos_dict_put_c_key_int(pcd, pin->Width, pim->Width));
106
221k
    CHECK(cos_dict_put_c_key_int(pcd, pin->Height, pim->Height));
107
221k
    CHECK(cos_dict_put_c_key_int(pcd, pin->BitsPerComponent,
108
221k
                                 pim->BitsPerComponent));
109
221k
    {
110
221k
        int i;
111
112
360k
        for (i = 0; i < num_components * 2; ++i) {
113
328k
            if (pim->Decode[i] !=
114
328k
                (default_decode ? default_decode[i] : i & 1)
115
328k
                )
116
188k
                break;
117
328k
        }
118
221k
        if (i < num_components * 2) {
119
188k
            cos_array_t *pca =
120
188k
                cos_array_alloc(pdev, "pdf_put_pixel_image_values(decode)");
121
122
188k
            if (pca == 0)
123
0
                return_error(gs_error_VMerror);
124
188k
            if (pcs == NULL) {
125
                /* 269-01.ps sets /Decode[0 100] with a mask image. */
126
565k
                for (i = 0; i < num_components * 2; ++i)
127
377k
                    CHECK(cos_array_add_real(pca, min(pim->Decode[i], 1)));
128
188k
            } else {
129
874
                for (i = 0; i < num_components * 2; ++i)
130
732
                    CHECK(cos_array_add_real(pca, pim->Decode[i]));
131
142
            }
132
188k
            CHECK(cos_dict_put_c_key_object(pcd, pin->Decode,
133
188k
                                            COS_OBJECT(pca)));
134
188k
        }
135
221k
    }
136
221k
    if (pim->Interpolate) {
137
13.7k
        if (pdev->PDFA != 0)
138
0
            emprintf(pdev->memory,
139
13.7k
                     "PDFA doesn't allow images with Interpolate true.\n");
140
13.7k
        else
141
13.7k
            CHECK(cos_dict_put_c_strings(pcd, pin->Interpolate, "true"));
142
13.7k
    }
143
221k
    return 0;
144
221k
}
145
int
146
pdf_put_image_values(cos_dict_t *pcd, gx_device_pdf *pdev,
147
                     const gs_pixel_image_t *pic,
148
                     const pdf_image_names_t *pin,
149
                     const cos_value_t *pcsvalue)
150
221k
{
151
221k
    const gs_color_space *pcs = pic->ColorSpace;
152
221k
    int code;
153
154
221k
    switch (pic->type->index) {
155
221k
    case 1: {
156
221k
        const gs_image1_t *pim = (const gs_image1_t *)pic;
157
158
221k
        if (pim->ImageMask) {
159
193k
            CHECK(cos_dict_put_c_strings(pcd, pin->ImageMask, "true"));
160
193k
            pdev->procsets |= ImageB;
161
193k
            pcs = NULL;
162
193k
        }
163
221k
    }
164
221k
        break;
165
221k
    case 3: {
166
        /*
167
         * Clients must treat this as a special case: they must call
168
         * pdf_put_image_values for the MaskDict separately, and must
169
         * add the Mask entry to the main image stream (dictionary).
170
         */
171
        /*const gs_image3_t *pim = (const gs_image3_t *)pic;*/
172
173
        /* Masked images are only supported starting in PDF 1.3. */
174
0
        if (pdev->CompatibilityLevel < 1.3)
175
0
            return_error(gs_error_rangecheck);
176
0
    }
177
0
        break;
178
0
    case 4: {
179
0
        const gs_image4_t *pim = (const gs_image4_t *)pic;
180
0
        int num_components = gs_color_space_num_components(pcs);
181
0
        cos_array_t *pca;
182
0
        int i;
183
184
        /* Masked images are only supported starting in PDF 1.3. */
185
0
        if (pdev->CompatibilityLevel < 1.3)
186
0
            break; /* Will convert into an imagemask with a pattern color. */
187
0
        pca = cos_array_alloc(pdev, "pdf_put_image_values(mask)");
188
0
        if (pca == 0)
189
0
            return_error(gs_error_VMerror);
190
0
        for (i = 0; i < num_components; ++i) {
191
0
            int lo, hi;
192
193
0
            if (pim->MaskColor_is_range)
194
0
                lo = pim->MaskColor[i * 2], hi = pim->MaskColor[i * 2 + 1];
195
0
            else
196
0
                lo = hi = pim->MaskColor[i];
197
0
            CHECK(cos_array_add_int(pca, lo));
198
0
            CHECK(cos_array_add_int(pca, hi));
199
0
        }
200
0
        CHECK(cos_dict_put_c_key_object(pcd, "/Mask", COS_OBJECT(pca)));
201
0
    }
202
0
        break;
203
0
    default:
204
0
        return_error(gs_error_rangecheck);
205
221k
    }
206
221k
    return pdf_put_pixel_image_values(pcd, pdev, pic, pcs, pin, pcsvalue);
207
221k
}
208
209
/* Store filters for an image. */
210
/* Currently this only saves parameters for CCITTFaxDecode. */
211
int
212
pdf_put_image_filters(cos_dict_t *pcd, gx_device_pdf *pdev,
213
                      const psdf_binary_writer * pbw,
214
                      const pdf_image_names_t *pin)
215
221k
{
216
221k
    return pdf_put_filters(pcd, pdev, pbw->strm, &pin->filter_names);
217
221k
}
218
219
/* ---------------- Image writing ---------------- */
220
221
/*
222
 * Fill in the image parameters for a device space bitmap.
223
 * PDF images are always specified top-to-bottom.
224
 * data_h is the actual number of data rows, which may be less than h.
225
 */
226
void
227
pdf_make_bitmap_matrix(gs_matrix * pmat, int x, int y, int w, int h,
228
                       int h_actual)
229
1.89M
{
230
1.89M
    pmat->xx = (float)w;
231
1.89M
    pmat->xy = 0;
232
1.89M
    pmat->yx = 0;
233
1.89M
    pmat->yy = (float)(-h_actual);
234
1.89M
    pmat->tx = (float)x;
235
1.89M
    pmat->ty = (float)(y + h);
236
1.89M
}
237
238
/*
239
 * Put out the gsave and matrix for an image.  y_scale adjusts the matrix
240
 * for images that end prematurely.
241
 */
242
void
243
pdf_put_image_matrix(gx_device_pdf * pdev, const gs_matrix * pmat,
244
                     double y_scale)
245
75.1k
{
246
75.1k
    gs_matrix imat = {1, 0, 0, 1, 0 ,0};
247
248
75.1k
    gs_matrix_translate(pmat, 0.0, 1.0 - y_scale, &imat);
249
75.1k
    gs_matrix_scale(&imat, 1.0, y_scale, &imat);
250
75.1k
    pdf_put_matrix(pdev, "q ", &imat, "cm\n");
251
75.1k
}
252
253
/* Put out a reference to an image resource. */
254
int
255
pdf_do_image_by_id(gx_device_pdf * pdev, double scale,
256
             const gs_matrix * pimat, bool in_contents, gs_id id)
257
4.27k
{
258
    /* fixme : in_contents is always true (there are no calls with false). */
259
4.27k
    if (in_contents) {
260
4.27k
        int code = pdf_open_contents(pdev, PDF_IN_STREAM);
261
262
4.27k
        if (code < 0)
263
0
            return code;
264
4.27k
    }
265
4.27k
    if (pimat)
266
4.27k
        pdf_put_image_matrix(pdev, pimat, scale);
267
4.27k
    pprintld1(pdev->strm, "/R%ld Do\nQ\n", id);
268
4.27k
    return 0;
269
4.27k
}
270
int
271
pdf_do_image(gx_device_pdf * pdev, const pdf_resource_t * pres,
272
             const gs_matrix * pimat, bool in_contents)
273
4.27k
{
274
    /* fixme : call pdf_do_image_by_id when pimam == NULL. */
275
4.27k
    double scale = 1;
276
277
4.27k
    if (pimat) {
278
        /* Adjust the matrix to account for short images. */
279
4.27k
        const pdf_x_object_t *const pxo = (const pdf_x_object_t *)pres;
280
4.27k
        scale = (double)pxo->data_height / pxo->height;
281
4.27k
    }
282
4.27k
    return pdf_do_image_by_id(pdev, scale, pimat, in_contents, pdf_resource_id(pres));
283
4.27k
}
284
285
/* ------ Begin / finish ------ */
286
287
/* Initialize image writer. */
288
void
289
pdf_image_writer_init(pdf_image_writer * piw)
290
214k
{
291
214k
    memset(piw, 0, sizeof(*piw));
292
214k
    piw->alt_writer_count = 1; /* Default. */
293
214k
}
294
295
/*
296
 * Begin writing an image, creating the resource if not in-line, and setting
297
 * up the binary writer.  If pnamed != 0, it is a stream object created by a
298
 * NI pdfmark.
299
 */
300
int
301
pdf_begin_write_image(gx_device_pdf * pdev, pdf_image_writer * piw,
302
                      gx_bitmap_id id, int w, int h, cos_dict_t *named,
303
                      bool in_line)
304
214k
{
305
    /* Patch pdev->strm so the right stream gets into the writer. */
306
214k
    stream *save_strm = pdev->strm;
307
214k
    cos_stream_t *data;
308
214k
    bool mask = (piw->data != NULL);
309
214k
    int alt_stream_index = (!mask ? 0 : piw->alt_writer_count);
310
214k
    int code;
311
312
214k
    if (in_line) {
313
206k
        piw->pres = 0;
314
206k
        piw->pin = &pdf_image_names_short;
315
206k
        data = cos_stream_alloc(pdev, "pdf_begin_image_data");
316
206k
        if (data == 0)
317
0
            return_error(gs_error_VMerror);
318
206k
        piw->end_string = " Q";
319
206k
        piw->named = 0;   /* must have named == 0 */
320
206k
    } else {
321
8.08k
        pdf_x_object_t *pxo;
322
8.08k
        cos_stream_t *pcos;
323
8.08k
        pdf_resource_t *pres;
324
325
        /*
326
         * Note that if named != 0, there are two objects with the same id
327
         * while the image is being accumulated: named, and pres->object.
328
         */
329
8.08k
        code = pdf_alloc_resource(pdev, resourceXObject, id, &pres,
330
8.08k
                                  (named ? named->id : -1L));
331
8.08k
        if (code < 0)
332
0
            return code;
333
8.08k
        *(mask ? &piw->pres_mask : &piw->pres) = pres;
334
8.08k
        cos_become(pres->object, cos_type_stream);
335
8.08k
        pres->rid = id;
336
8.08k
        piw->pin = &pdf_image_names_full;
337
8.08k
        pxo = (pdf_x_object_t *)pres;
338
8.08k
        pcos = (cos_stream_t *)pxo->object;
339
8.08k
        CHECK(cos_dict_put_c_strings(cos_stream_dict(pcos), "/Subtype",
340
8.08k
                                     "/Image"));
341
8.08k
        pxo->width = w;
342
8.08k
        pxo->height = h;
343
        /* Initialize data_height for the benefit of copy_{mono,color}. */
344
8.08k
        pxo->data_height = h;
345
8.08k
        data = pcos;
346
8.08k
        if (!mask)
347
8.08k
            piw->named = named;
348
8.08k
    }
349
214k
    pdev->strm = pdev->streams.strm;
350
214k
    pdev->strm = cos_write_stream_alloc(data, pdev, "pdf_begin_write_image");
351
214k
    if (pdev->strm == 0) {
352
0
        pdev->strm = save_strm;
353
0
        return_error(gs_error_VMerror);
354
0
    }
355
214k
    if (!mask)
356
214k
        piw->data = data;
357
214k
    piw->height = h;
358
214k
    code = psdf_begin_binary((gx_device_psdf *) pdev, &piw->binary[alt_stream_index]);
359
214k
    piw->binary[alt_stream_index].target = NULL; /* We don't need target with cos_write_stream. */
360
214k
    pdev->strm = save_strm;
361
214k
    return code;
362
214k
}
363
364
/*
365
 *  Make alternative stream for image compression choice.
366
 */
367
int
368
pdf_make_alt_stream(gx_device_pdf * pdev, psdf_binary_writer * pbw)
369
6.25k
{
370
6.25k
    stream *save_strm = pdev->strm;
371
6.25k
    cos_stream_t *pcos = cos_stream_alloc(pdev, "pdf_make_alt_stream");
372
6.25k
    int code;
373
374
6.25k
    if (pcos == 0)
375
0
        return_error(gs_error_VMerror);
376
6.25k
    pcos->id = 0;
377
6.25k
    CHECK(cos_dict_put_c_strings(cos_stream_dict(pcos), "/Subtype", "/Image"));
378
6.25k
    pbw->strm = cos_write_stream_alloc(pcos, pdev, "pdf_make_alt_stream");
379
6.25k
    if (pbw->strm == 0)
380
0
        return_error(gs_error_VMerror);
381
6.25k
    pbw->dev = (gx_device_psdf *)pdev;
382
6.25k
    pbw->memory = pdev->pdf_memory;
383
6.25k
    pdev->strm = pbw->strm;
384
6.25k
    code = psdf_begin_binary((gx_device_psdf *) pdev, pbw);
385
6.25k
    pdev->strm = save_strm;
386
6.25k
    pbw->target = NULL; /* We don't need target with cos_write_stream. */
387
6.25k
    return code;
388
6.25k
}
389
390
/* Begin writing the image data, setting up the dictionary and filters. */
391
int
392
pdf_begin_image_data(gx_device_pdf * pdev, pdf_image_writer * piw,
393
                     const gs_pixel_image_t * pim, const cos_value_t *pcsvalue,
394
                     int alt_writer_index)
395
221k
{
396
397
221k
    cos_stream_t *s;
398
221k
    cos_dict_t *pcd;
399
221k
    int code;
400
401
221k
    s = cos_stream_from_pipeline(piw->binary[alt_writer_index].strm);
402
221k
    if (s == 0L)
403
0
        return gs_note_error(gs_error_ioerror);
404
405
221k
    pcd = cos_stream_dict(s);
406
221k
    code = pdf_put_image_values(pcd, pdev, pim, piw->pin, pcsvalue);
407
221k
    if (code >= 0)
408
221k
        code = pdf_put_image_filters(pcd, pdev, &piw->binary[alt_writer_index], piw->pin);
409
221k
    if (code < 0) {
410
0
        if (!piw->pres)
411
0
            COS_FREE(piw->data, "pdf_begin_image_data");
412
0
        piw->data = 0;
413
0
    }
414
221k
    if (pdev->JPEG_PassThrough) {
415
765
        CHECK(cos_dict_put_c_strings(pcd, "/Filter", "/DCTDecode"));
416
765
    }
417
221k
    if (pdev->JPX_PassThrough) {
418
373
        CHECK(cos_dict_put_c_strings(pcd, "/Filter", "/JPXDecode"));
419
373
    }
420
221k
    if (pdev->PendingOC != 0) {
421
0
        char str[256];
422
0
        gs_param_string param;
423
0
        cos_object_t *pco = NULL;
424
425
0
        param.data = (const byte *)pdev->PendingOC;
426
0
        param.size = strlen(pdev->PendingOC);
427
0
        code = pdf_refer_named(pdev, &param, &pco);
428
0
        gs_free_object(pdev->memory, pdev->PendingOC, "");
429
0
        if(code < 0)
430
0
            return code;
431
432
0
        gs_snprintf(str, sizeof(str), "%"PRId64" 0 R", pco->id);
433
0
        if (piw->pres != NULL && piw->pres->object != NULL)
434
0
            code = cos_dict_put_string_copy((cos_dict_t *)piw->pres->object, "/OC", str);
435
436
0
        pdev->PendingOC = 0;
437
0
    }
438
221k
    return code;
439
221k
}
440
441
/* Complete image data. */
442
int
443
pdf_complete_image_data(gx_device_pdf *pdev, pdf_image_writer *piw, int data_h,
444
                        int width, int bits_per_pixel)
445
7.19k
{
446
7.19k
    if (data_h != piw->height) {
447
699
        if (piw->binary[0].strm->procs.process == s_DCTE_template.process ||
448
699
            piw->binary[0].strm->procs.process == s_PNGPE_template.process ) {
449
            /*  Since DCTE and PNGPE can't safely close with incomplete data,
450
                we add stub data to complete the stream.
451
            */
452
653
            int bytes_per_line = (width * bits_per_pixel + 7) / 8;
453
653
            int lines_left = piw->height - data_h;
454
653
            byte buf[256];
455
653
            const uint lb = sizeof(buf);
456
653
            int i, l;
457
653
            uint ignore;
458
459
653
            memset(buf, 128, lb);
460
332k
            for (; lines_left; lines_left--)
461
1.32M
                for (i = 0; i < piw->alt_writer_count; i++) {
462
2.16M
                    for (l = bytes_per_line; l > 0; l -= lb)
463
1.17M
                        if ((sputs(piw->binary[i].strm, buf, min(l, lb),
464
1.17M
                                            &ignore)) < 0)
465
0
                            return_error(gs_error_ioerror);
466
991k
                }
467
653
        }
468
699
    }
469
7.19k
    return 0;
470
7.19k
}
471
472
/* Finish writing the binary image data. */
473
int
474
pdf_end_image_binary(gx_device_pdf *pdev, pdf_image_writer *piw, int data_h)
475
214k
{
476
214k
    int code, code1 = 0;
477
478
214k
    if (piw->alt_writer_count > 2)
479
6.25k
        code = pdf_choose_compression(piw, true);
480
208k
    else
481
208k
        code = psdf_end_binary(&piw->binary[0]);
482
    /* If the image ended prematurely, update the Height. */
483
214k
    if (data_h != piw->height) {
484
4.01k
        char data[256];
485
4.01k
        int OutHeight;
486
4.01k
        cos_value_t *value;
487
4.01k
        value = (cos_value_t *)cos_dict_find(cos_stream_dict(piw->data),
488
4.01k
                                      (const byte *)piw->pin->Height, strlen(piw->pin->Height));
489
4.01k
        if (!value || value->contents.chars.size > 255)
490
0
            return(gs_error_rangecheck);
491
4.01k
        strncpy((char *)&data, (const char *)value->contents.chars.data, value->contents.chars.size);
492
4.01k
        data[value->contents.chars.size] = 0x00;
493
4.01k
        OutHeight = atoi(data);
494
4.01k
        if (OutHeight != piw->height) {
495
            /* Looks like we are downsampling, so we can't use the number
496
             * of rows of data actually received, we must divide those by
497
             * the sampling factor.
498
             */
499
0
            float factor = (float)OutHeight / piw->height;
500
0
            OutHeight = (int)(factor * data_h);
501
0
            code1 = cos_dict_put_c_key_int(cos_stream_dict(piw->data),
502
0
                                      piw->pin->Height, OutHeight);
503
4.01k
        } else {
504
505
4.01k
            code1 = cos_dict_put_c_key_int(cos_stream_dict(piw->data),
506
4.01k
                                      piw->pin->Height, data_h);
507
4.01k
        }
508
4.01k
    }
509
214k
    return code < 0 ? code : code1;
510
214k
}
511
512
/* When writing out an image, we check to see if its a duplicate of an existing image, and if so we simply
513
 * use the existing image. There is one potential problem here; if we have an image with a SMask, the SMask is
514
 * itself animage, and the SMask image and the image which uses it are identical. Because we don't add the SMask
515
 * entry to the image dictionary until we have closed the image, its possible that the image can detect the alredy
516
 * stored SMask image as being identical and attempt to use the SMask image instead. This leads to an image with
517
 * an SMask entry referencing itself.
518
 * We detect this here simply by checking if the detected image resource ID is the same as any current SMask. Worst
519
 * case is we fail to detect a duplicate, which is better than detecting an incorrect duplicate.
520
 * This check function is only used in pdf_end_write_image() below as an argument to pdf_substitute_resource().
521
 */
522
static int
523
smask_image_check(gx_device_pdf * pdev, pdf_resource_t *pres0, pdf_resource_t *pres1)
524
5.07k
{
525
5.07k
    cos_value_t *v = NULL;
526
527
    /* image_mask_id is non-zero if we have a pending SMask image */
528
5.07k
    if (pdev->image_mask_id != 0) {
529
2.08k
        if (pres0->object->id == pdev->image_mask_id || pres1->object->id == pdev->image_mask_id)
530
0
            return 0;
531
2.08k
        if (pdev->image_mask_is_SMask)
532
2.08k
            v = (cos_value_t *)cos_dict_find_c_key((const cos_dict_t *)pres1->object, "/SMask");
533
0
        else
534
0
            v = (cos_value_t *)cos_dict_find_c_key((const cos_dict_t *)pres1->object, "/Mask");
535
2.08k
        if (v == 0)
536
0
            return 0;
537
2.08k
        if (v != 0) {
538
2.08k
            const byte *p = v->contents.chars.data;
539
2.08k
            int ix = 0;
540
541
7.06k
            while (*p != 0x20) {
542
4.98k
                if (p > v->contents.chars.data + v->contents.chars.size)
543
0
                    return 0;
544
4.98k
                ix *= 10;
545
4.98k
                ix += (*p++) - 0x30;
546
4.98k
            }
547
2.08k
            if (ix != pdev->image_mask_id)
548
0
                return 0;
549
2.08k
        }
550
2.08k
    }
551
5.07k
    return 1;
552
5.07k
}
553
554
555
/* Abort an image without writing it.
556
 * Frees any associated memory.
557
 */
558
int
559
pdf_end_abort_image(gx_device_pdf * pdev, pdf_image_writer * piw)
560
2.60k
{
561
2.60k
    pdf_resource_t *pres = piw->pres;
562
563
2.60k
    if (!pres) {
564
1.71k
        COS_FREE(piw->data, "pdf_end_write_image");
565
1.71k
    }
566
2.60k
    return 0;
567
2.60k
}
568
569
/*
570
 * Finish writing an image.  If in-line, write the BI/dict/ID/data/EI and
571
 * return 1; if a resource, write the resource definition and return 0.
572
 */
573
int
574
pdf_end_write_image(gx_device_pdf * pdev, pdf_image_writer * piw)
575
212k
{
576
212k
    pdf_resource_t *pres = piw->pres;
577
578
212k
    if (pres) {     /* image resource */
579
7.19k
        cos_object_t *const pco = pres->object;
580
7.19k
        cos_stream_t *const pcs = (cos_stream_t *)pco;
581
7.19k
        cos_dict_t *named = piw->named;
582
7.19k
        int code;
583
584
7.19k
        if (named) {
585
6
            if (pdev->ForOPDFRead) {
586
6
                code = cos_dict_put_c_key_bool(named, "/.Global", true);
587
6
                if (code < 0)
588
0
                    return code;
589
6
            }
590
            /*
591
             * This image was named by NI.  Copy any dictionary elements
592
             * from the named dictionary to the image stream, and then
593
             * associate the name with the stream.
594
             */
595
6
            code = cos_dict_move_all(cos_stream_dict(pcs), named);
596
6
            if (code < 0)
597
0
                return code;
598
6
            pres->named = true;
599
            /*
600
             * We need to make the entry in the name dictionary point to
601
             * the stream (pcs) rather than the object created by NI (named).
602
             * Unfortunately, we no longer know what dictionary to use.
603
             * Instead, overwrite the latter with the former's contents,
604
             * and change the only relevant pointer.
605
             */
606
6
            *(cos_object_t *)named = *pco;
607
6
            pres->object = COS_OBJECT(named);
608
7.19k
        } else if (!pres->named) { /* named objects are written at the end */
609
7.19k
            if (pdev->DetectDuplicateImages) {
610
7.19k
                pdf_x_object_t *pxo = (pdf_x_object_t *)piw->pres;
611
7.19k
                int height = pxo->height, width = pxo->width;
612
613
7.19k
                code = pdf_substitute_resource(pdev, &piw->pres, resourceXObject, smask_image_check, false);
614
7.19k
                if (code < 0)
615
0
                    return code;
616
617
                /* These values are related to the image matrix and should *not* be
618
                 * substituted if we found a duplicate image, or the matrix calculation
619
                 * will be incorrect! This only seems to matter for the PCL interpreter.
620
                 */
621
7.19k
                pxo = (pdf_x_object_t *)piw->pres;
622
7.19k
                pxo->height = height;
623
7.19k
                pxo->width = width;
624
7.19k
            } else {
625
0
                pdf_reserve_object_id(pdev, piw->pres, gs_no_id);
626
0
            }
627
            /*  Warning : If the substituted image used alternate streams,
628
                its space in the pdev->streams.strm file won't be released. */
629
7.19k
            piw->pres->where_used |= pdev->used_mask;
630
7.19k
        }
631
7.19k
        code = pdf_add_resource(pdev, pdev->substream_Resources, "/XObject", piw->pres);
632
7.19k
        if (code < 0)
633
0
            return code;
634
7.19k
        return 0;
635
205k
    } else {     /* in-line image */
636
205k
        stream *s = pdev->strm;
637
205k
        uint KeyLength = pdev->KeyLength;
638
639
205k
        stream_puts(s, "BI\n");
640
205k
        cos_stream_elements_write(piw->data, pdev);
641
205k
        stream_puts(s, (pdev->binary_ok ? "ID " : "ID\n"));
642
205k
        pdev->KeyLength = 0; /* Disable encryption for the inline image. */
643
205k
        cos_stream_contents_write(piw->data, pdev);
644
205k
        pdev->KeyLength = KeyLength;
645
205k
        pprints1(s, "\nEI%s\n", piw->end_string);
646
205k
        COS_FREE(piw->data, "pdf_end_write_image");
647
205k
        return 1;
648
205k
    }
649
212k
}
650
651
/* ------ Copy data ------ */
652
653
/* Copy the data for a mask or monobit bitmap. */
654
int
655
pdf_copy_mask_bits(stream *s, const byte *base, int sourcex, int raster,
656
                   int w, int h, byte invert)
657
137k
{
658
137k
    int yi;
659
660
3.51M
    for (yi = 0; yi < h; ++yi) {
661
3.37M
        const byte *data = base + yi * raster + (sourcex >> 3);
662
3.37M
        int sbit = sourcex & 7;
663
664
3.37M
        if (sbit == 0) {
665
3.37M
            int nbytes = (w + 7) >> 3;
666
3.37M
            int i;
667
668
29.5M
            for (i = 0; i < nbytes; ++data, ++i)
669
26.1M
                sputc(s, (byte)(*data ^ invert));
670
3.37M
        } else {
671
0
            int wleft = w;
672
0
            int rbit = 8 - sbit;
673
674
0
            for (; wleft + sbit > 8; ++data, wleft -= 8)
675
0
                sputc(s, (byte)(((*data << sbit) + (data[1] >> rbit)) ^ invert));
676
0
            if (wleft > 0)
677
0
                sputc(s, (byte)(((*data << sbit) ^ invert) &
678
0
                      (byte) (0xff00 >> wleft)));
679
0
        }
680
3.37M
    }
681
137k
    return 0;
682
137k
}
683
684
/* Copy the data for a colored image (device pixels). */
685
int
686
pdf_copy_color_bits(stream *s, const byte *base, int sourcex, int raster,
687
                    int w, int h, int bytes_per_pixel)
688
2.54k
{
689
2.54k
    int yi;
690
691
257k
    for (yi = 0; yi < h; ++yi) {
692
254k
        uint ignore;
693
694
254k
        sputs(s, base + sourcex * bytes_per_pixel + yi * raster,
695
254k
              w * bytes_per_pixel, &ignore);
696
254k
    }
697
2.54k
    return 0;
698
2.54k
}
699
700
/* Choose image compression - auxiliary procs */
701
static inline bool much_bigger__DL(long l1, long l2)
702
1.01M
{
703
1.01M
    return l1 > 1024*1024 && (l2 > 0 && l2 < l1 / 3);
704
1.01M
}
705
static void
706
pdf_choose_compression_cos(pdf_image_writer *piw, cos_stream_t *s[2], bool force)
707
513k
{   /*  Assume s[0] is Flate, s[1] is DCT, s[2] is chooser. */
708
513k
    long l0, l1;
709
513k
    int k0, k1;
710
711
513k
    l0 = cos_stream_length(s[0]);
712
513k
    l1 = cos_stream_length(s[1]);
713
714
513k
    if ((force && l0 <= l1) || l1 == -1)
715
5.58k
        k0 = 1; /* Use Flate if it is not longer. Or if the DCT failed */
716
508k
    else {
717
508k
        k0 = s_compr_chooser__get_choice(
718
508k
            (stream_compr_chooser_state *)piw->binary[2].strm->state, force);
719
508k
        if (k0 && l0 > 0 && l1 > 0)
720
616
            k0--;
721
507k
        else if (much_bigger__DL(l0, l1))
722
0
            k0 = 0;
723
507k
        else if (much_bigger__DL(l1, l0) || force)
724
54
            k0 = 1;
725
507k
        else
726
507k
           return;
727
508k
    }
728
6.25k
    k1 = 1 - k0;
729
6.25k
    s_close_filters(&piw->binary[k0].strm, piw->binary[k0].target);
730
6.25k
    s[k0]->cos_procs->release((cos_object_t *)s[k0], "pdf_image_choose_filter");
731
6.25k
    s[k0]->written = 1;
732
6.25k
    piw->binary[0].strm = piw->binary[k1].strm;
733
6.25k
    s_close_filters(&piw->binary[2].strm, piw->binary[2].target);
734
6.25k
    piw->binary[1].strm = piw->binary[2].strm = 0; /* for GC */
735
6.25k
    piw->binary[1].target = piw->binary[2].target = 0;
736
6.25k
    s[k1]->id = piw->pres->object->id;
737
6.25k
    piw->pres->object = (cos_object_t *)s[k1];
738
6.25k
    piw->data = s[k1];
739
6.25k
    if (piw->alt_writer_count > 3) {
740
0
        piw->binary[1] = piw->binary[3];
741
0
        piw->binary[3].strm = 0; /* for GC */
742
0
        piw->binary[3].target = 0;
743
0
    }
744
6.25k
    piw->alt_writer_count -= 2;
745
6.25k
}
746
747
/* End binary with choosing image compression. */
748
int
749
pdf_choose_compression(pdf_image_writer * piw, bool end_binary)
750
513k
{
751
513k
    cos_stream_t *s[2];
752
513k
    int status;
753
754
513k
    s[0] = cos_stream_from_pipeline(piw->binary[0].strm);
755
513k
    s[1] = cos_stream_from_pipeline(piw->binary[1].strm);
756
757
513k
    if (s[0] == 0L) {
758
0
        return_error(gs_error_ioerror);
759
0
    }
760
513k
    if (s[1] == 0L) {
761
0
        s_close_filters(&piw->binary[0].strm, piw->binary[0].target);
762
0
        return_error(gs_error_ioerror);
763
0
    }
764
513k
    if (end_binary) {
765
6.25k
        status = s_close_filters(&piw->binary[0].strm, piw->binary[0].target);
766
6.25k
        if (status < 0)
767
0
            return_error(gs_error_ioerror);
768
6.25k
        status = s_close_filters(&piw->binary[1].strm, piw->binary[1].target);
769
6.25k
        if (status < 0)
770
352
            s[1]->length = -1;
771
6.25k
    }
772
513k
    pdf_choose_compression_cos(piw, s, end_binary);
773
513k
    return 0;
774
513k
}