Coverage Report

Created: 2026-11-12 07:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/ghostpdl/pdf/pdf_image.c
Line
Count
Source
1
/* Copyright (C) 2018-2026 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
/* Image operations for the PDF interpreter */
17
18
#include "pdf_int.h"
19
#include "pdf_stack.h"
20
#include "pdf_font_types.h"
21
#include "pdf_gstate.h"
22
#include "pdf_doc.h"
23
#include "pdf_page.h"
24
#include "pdf_image.h"
25
#include "pdf_file.h"
26
#include "pdf_dict.h"
27
#include "pdf_array.h"
28
#include "pdf_loop_detect.h"
29
#include "pdf_colour.h"
30
#include "pdf_trans.h"
31
#include "pdf_misc.h"
32
#include "pdf_optcontent.h"
33
#include "pdf_mark.h"
34
#include "pdf_path.h"
35
#include "stream.h"     /* for stell() */
36
#include "gsicc_cache.h"
37
38
#include "gspath2.h"
39
#include "gsiparm4.h"
40
#include "gsiparm3.h"
41
#include "gsipar3x.h"
42
#include "gsform1.h"
43
#include "gstrans.h"
44
#include "gxdevsop.h"               /* For special ops */
45
#include "gspath.h"         /* For gs_moveto() and friends */
46
#include "gsstate.h"        /* For gs_setoverprintmode() */
47
#include "gscoord.h"        /* for gs_concat() and others */
48
#include "gxgstate.h"
49
50
int pdfi_BI(pdf_context *ctx)
51
224k
{
52
224k
    int code;
53
54
224k
    if (ctx->text.BlockDepth != 0) {
55
20
        ctx->text.BlockDepth = 0;
56
20
        if (ctx->text.TextClip) {
57
0
            gx_device *dev = gs_currentdevice_inline(ctx->pgs);
58
59
0
            ctx->text.TextClip = false;
60
0
            (void)dev_proc(dev, dev_spec_op)(dev, gxdso_hilevel_text_clip, (void *)0, 1);
61
0
        }
62
20
        code = pdfi_set_warning_stop(ctx, gs_note_error(gs_error_syntaxerror), NULL, W_PDF_OPINVALIDINTEXT, "pdfi_BI", NULL);
63
20
        if (code < 0)
64
0
            return code;
65
20
    }
66
67
224k
    return pdfi_mark_stack(ctx, PDF_DICT_MARK);
68
224k
}
69
70
typedef struct {
71
    int comps;
72
    int bpc;
73
    uint32_t cs_enum;
74
    bool iccbased;
75
    bool no_data;
76
    bool is_valid;
77
    uint32_t icc_offset;
78
    uint32_t icc_length;
79
} pdfi_jpx_info_t;
80
81
typedef struct {
82
    /* Type and SubType were already checked by caller */
83
    /* OPI, Metadata -- do we care? */
84
    bool ImageMask;
85
    bool Interpolate;
86
    int64_t Length;
87
    int64_t Height;
88
    int64_t Width;
89
    int64_t BPC;
90
    int64_t StructParent;
91
    int64_t SMaskInData;
92
    pdf_obj *Mask;
93
    pdf_obj *SMask;
94
    pdf_obj *ColorSpace;
95
    pdf_name *Intent;
96
    pdf_obj *Alternates;
97
    pdf_obj *Name; /* obsolete, do we still support? */
98
    pdf_obj *Decode;
99
    pdf_dict *OC;  /* Optional Content */
100
    /* Filter and DecodeParms handled by pdfi_filter() (can probably remove, but I like the info while debugging) */
101
    bool is_JPXDecode;
102
    pdf_obj *Filter;
103
    pdf_obj *DecodeParms;
104
105
    /* Convenience variables (save these here instead of passing around as params) */
106
    pdf_dict *page_dict;
107
    pdf_dict *stream_dict;
108
    bool inline_image;
109
    pdfi_jpx_info_t jpx_info;
110
} pdfi_image_info_t;
111
112
static void
113
pdfi_free_image_info_components(pdfi_image_info_t *info)
114
900k
{
115
900k
    if (info->Mask)
116
711
        pdfi_countdown(info->Mask);
117
900k
    if (info->SMask)
118
25.6k
        pdfi_countdown(info->SMask);
119
900k
    if (info->ColorSpace)
120
90.3k
        pdfi_countdown(info->ColorSpace);
121
900k
    if (info->Intent)
122
7.01k
        pdfi_countdown(info->Intent);
123
900k
    if (info->Alternates)
124
0
        pdfi_countdown(info->Alternates);
125
900k
    if (info->Name)
126
18.2k
        pdfi_countdown(info->Name);
127
900k
    if (info->Decode)
128
198k
        pdfi_countdown(info->Decode);
129
900k
    if (info->OC)
130
42
        pdfi_countdown(info->OC);
131
900k
    if (info->Filter)
132
95.4k
        pdfi_countdown(info->Filter);
133
900k
    if (info->DecodeParms)
134
31.9k
        pdfi_countdown(info->DecodeParms);
135
900k
    memset(info, 0, sizeof(*info));
136
900k
}
137
138
139
static inline uint64_t
140
pdfi_get_image_data_size(gs_data_image_t *pim, int comps)
141
282k
{
142
282k
    int64_t size, H, W, B;
143
144
282k
    H = pim->Height;
145
282k
    W = pim->Width;
146
282k
    B = pim->BitsPerComponent;
147
148
282k
    size = (((W * comps * B) + 7) / 8) * H;
149
282k
    return size;
150
282k
}
151
152
/* Find first dictionary in array that contains "/DefaultForPrinting true" */
153
static pdf_stream *
154
pdfi_find_alternate(pdf_context *ctx, pdf_obj *alt)
155
0
{
156
0
    pdf_array *array = NULL;
157
0
    pdf_obj *item = NULL;
158
0
    pdf_stream *alt_stream = NULL;
159
0
    int i;
160
0
    int code;
161
0
    bool flag;
162
163
0
    if (pdfi_type_of(alt) != PDF_ARRAY)
164
0
        return NULL;
165
166
0
    array = (pdf_array *)alt;
167
0
    for (i=0; i<pdfi_array_size(array);i++) {
168
0
        code = pdfi_array_get_type(ctx, array, (uint64_t)i, PDF_DICT, &item);
169
0
        if (code != 0)
170
0
            continue;
171
0
        code = pdfi_dict_get_bool(ctx, (pdf_dict *)item, "DefaultForPrinting", &flag);
172
0
        if (code != 0 || !flag) {
173
0
            pdfi_countdown(item);
174
0
            item = NULL;
175
0
            continue;
176
0
        }
177
0
        code = pdfi_dict_get_type(ctx, (pdf_dict *)item, "Image", PDF_STREAM, (pdf_obj **)&alt_stream);
178
0
        pdfi_countdown(item);
179
0
        item = NULL;
180
0
        if (code != 0)
181
0
            continue;
182
0
        return alt_stream;
183
0
    }
184
0
    return NULL;
185
0
}
186
187
99.4k
#define READ32BE(i) (((i)[0] << 24) | ((i)[1] << 16) | ((i)[2] << 8) | (i)[3])
188
7.99k
#define READ16BE(i) (((i)[0] << 8) | (i)[1])
189
44.0k
#define K4(a, b, c, d) ((a << 24) + (b << 16) + (c << 8) + d)
190
23.9k
#define LEN_IHDR 14
191
10.1k
#define LEN_DATA 2048
192
193
/* Returns either < 0, or exactly 8 */
194
static int
195
get_box(pdf_context *ctx, pdf_c_stream *source, int length, uint32_t *box_len, uint32_t *box_val)
196
45.7k
{
197
45.7k
    int code;
198
45.7k
    byte blob[4];
199
200
45.7k
    if (length < 8)
201
3
        return_error(gs_error_limitcheck);
202
45.7k
    code = pdfi_read_bytes(ctx, blob, 1, 4, source);
203
45.7k
    if (code < 0)
204
0
        return code;
205
45.7k
    *box_len = READ32BE(blob);
206
45.7k
    if (*box_len < 8)
207
13
        return_error(gs_error_limitcheck);
208
45.7k
    code = pdfi_read_bytes(ctx, blob, 1, 4, source);
209
45.7k
    if (code < 0)
210
0
        return code;
211
45.7k
    *box_val = READ32BE(blob);
212
213
45.7k
    if(ctx->args.pdfdebug)
214
45.7k
        dbgmprintf3(ctx->memory, "JPXFilter: BOX: l:%d, v:%x (%4.4s)\n", *box_len, *box_val, blob);
215
45.7k
    return 8;
216
45.7k
}
217
218
/* Scan JPX image for header info */
219
static int
220
pdfi_scan_jpxfilter(pdf_context *ctx, pdf_c_stream *source, int length, pdfi_jpx_info_t *info)
221
10.1k
{
222
10.1k
    uint32_t box_len = 0;
223
10.1k
    uint32_t box_val = 0;
224
10.1k
    int code;
225
10.1k
    byte ihdr_data[LEN_IHDR];
226
10.1k
    byte *data = NULL;
227
10.1k
    int data_buf_len = 0;
228
10.1k
    int avail = length;
229
10.1k
    int bpc = 0;
230
10.1k
    int comps = 0;
231
10.1k
    int cs_meth = 0;
232
10.1k
    uint32_t cs_enum = 0;
233
10.1k
    bool got_color = false;
234
235
10.1k
    if (ctx->args.pdfdebug)
236
10.1k
        dbgmprintf1(ctx->memory, "JPXFilter: Image length %d\n", length);
237
238
    /* Clear out the info param */
239
10.1k
    memset(info, 0, sizeof(pdfi_jpx_info_t));
240
241
10.1k
    info->no_data = false;
242
243
    /* Allocate a data buffer that hopefully is big enough */
244
10.1k
    data_buf_len = LEN_DATA;
245
10.1k
    data = gs_alloc_bytes(ctx->memory, data_buf_len, "pdfi_scan_jpxfilter (data)");
246
10.1k
    if (!data) {
247
0
        code = gs_note_error(gs_error_VMerror);
248
0
        goto exit;
249
0
    }
250
251
    /* Find the 'jp2h' box, skipping over everything else */
252
30.1k
    while (avail > 0) {
253
29.6k
        code = get_box(ctx, source, avail, &box_len, &box_val);
254
29.6k
        if (code < 0)
255
11
            goto exit;
256
29.6k
        avail -= 8;
257
29.6k
        box_len -= 8;
258
29.6k
        if (box_len <= 0 || box_len > avail) {
259
1.63k
            code = pdfi_set_error_stop(ctx, gs_note_error(gs_error_syntaxerror), NULL, E_PDF_INVALID_JPX_HDR, "pdfi_scan_jpxfilter", NULL);
260
1.63k
            goto exit;
261
1.63k
        }
262
27.9k
        if (box_val == K4('j','p','2','h')) {
263
7.99k
            break;
264
7.99k
        }
265
19.9k
        pdfi_seek(ctx, source, box_len, SEEK_CUR);
266
19.9k
        avail -= box_len;
267
19.9k
    }
268
8.51k
    if (avail <= 0) {
269
517
        info->no_data = true;
270
517
        code = gs_note_error(gs_error_ioerror);
271
517
        goto exit;
272
517
    }
273
274
    /* Now we are only looking inside the jp2h box */
275
7.99k
    avail = box_len;
276
277
    /* The first thing in the 'jp2h' box is an 'ihdr', get that */
278
7.99k
    code = get_box(ctx, source, avail, &box_len, &box_val);
279
7.99k
    if (code < 0)
280
0
        goto exit;
281
7.99k
    avail -= 8;
282
7.99k
    box_len -= 8;
283
7.99k
    if (box_val != K4('i','h','d','r')) {
284
0
        code = gs_note_error(gs_error_syntaxerror);
285
0
        goto exit;
286
0
    }
287
7.99k
    if (box_len != LEN_IHDR) {
288
0
        code = gs_note_error(gs_error_syntaxerror);
289
0
        goto exit;
290
0
    }
291
292
    /* Get things we care about from ihdr */
293
7.99k
    code = pdfi_read_bytes(ctx, ihdr_data, 1, LEN_IHDR, source);
294
7.99k
    if (code < 0)
295
0
        goto exit;
296
7.99k
    avail -= LEN_IHDR;
297
7.99k
    comps = READ16BE(ihdr_data+8);
298
7.99k
    if (ctx->args.pdfdebug)
299
7.99k
        dbgmprintf1(ctx->memory, "    COMPS: %d\n", comps);
300
7.99k
    bpc = ihdr_data[10];
301
7.99k
    if (bpc != 255)
302
7.99k
        bpc += 1;
303
7.99k
    if (ctx->args.pdfdebug)
304
7.99k
        dbgmprintf1(ctx->memory, "    BPC: %d\n", bpc);
305
306
    /* Parse the rest of the things */
307
16.0k
    while (avail > 0) {
308
8.09k
        code = get_box(ctx, source, avail, &box_len, &box_val);
309
8.09k
        if (code < 0)
310
5
            goto exit;
311
8.09k
        avail -= 8;
312
8.09k
        box_len -= 8;
313
8.09k
        if (box_len <= 0) {
314
0
            code = gs_note_error(gs_error_syntaxerror);
315
0
            goto exit;
316
0
        }
317
        /* Re-alloc buffer if it wasn't big enough (unlikely) */
318
8.09k
        if (box_len > data_buf_len) {
319
8
            if (ctx->args.pdfdebug)
320
8
                dbgmprintf2(ctx->memory, "data buffer (size %d) was too small, reallocing to size %d\n",
321
8
                      data_buf_len, box_len);
322
8
            gs_free_object(ctx->memory, data, "pdfi_scan_jpxfilter (data)");
323
8
            data_buf_len = box_len;
324
8
            data = gs_alloc_bytes(ctx->memory, data_buf_len, "pdfi_scan_jpxfilter (data)");
325
8
            if (!data) {
326
5
                code = gs_note_error(gs_error_VMerror);
327
5
                goto exit;
328
5
            }
329
8
        }
330
8.08k
        code = pdfi_read_bytes(ctx, data, 1, box_len, source);
331
8.08k
        if (code < 0)
332
0
            goto exit;
333
8.08k
        avail -= box_len;
334
8.08k
        switch(box_val) {
335
0
        case K4('b','p','c','c'):
336
0
            {
337
0
                int i;
338
0
                int bpc2;
339
340
0
                if (comps > box_len) {
341
0
                    code = gs_note_error(gs_error_syntaxerror);
342
0
                    goto exit;
343
0
                }
344
0
                bpc2 = data[0];
345
0
                for (i=1;i<comps;i++) {
346
0
                    if (bpc2 != data[i]) {
347
0
                        emprintf(ctx->memory,
348
0
                                 "*** Error: JPX image colour channels do not all have the same colour depth\n");
349
0
                        emprintf(ctx->memory,
350
0
                                 "    Output may be incorrect.\n");
351
0
                    }
352
0
                }
353
0
                bpc = bpc2+1;
354
0
                if (ctx->args.pdfdebug)
355
0
                    dbgmprintf1(ctx->memory, "    BPCC: %d\n", bpc);
356
0
            }
357
0
            break;
358
7.98k
        case K4('c','o','l','r'):
359
7.98k
            if (got_color) {
360
0
                if (ctx->args.pdfdebug)
361
0
                    dbgmprintf(ctx->memory, "JPXFilter: Ignore extra COLR specs\n");
362
0
                break;
363
0
            }
364
7.98k
            cs_meth = data[0];
365
7.98k
            if (cs_meth == 1) {
366
7.98k
                if (box_len < 7) {
367
0
                    code = gs_note_error(gs_error_syntaxerror);
368
0
                    goto exit;
369
0
                }
370
7.98k
                cs_enum = READ32BE(data+3);
371
7.98k
            }
372
3
            else if (cs_meth == 2 || cs_meth == 3) {
373
                /* This is an ICCBased color space just sitting there in the buffer.
374
                 * TODO: I could create the colorspace now while I have the buffer,
375
                 * but code flow is more consistent if I do it later.  Could change this.
376
                 *
377
                 * NOTE: cs_meth == 3 is apparently treated the same as 2.
378
                 * No idea why... it's really not documented anywhere.
379
                 */
380
0
                if (box_len < 3) {
381
0
                    code = gs_note_error(gs_error_syntaxerror);
382
0
                    goto exit;
383
0
                }
384
0
                info->iccbased = true;
385
0
                info->icc_offset = pdfi_tell(source) - (box_len-3);
386
0
                info->icc_length = box_len - 3;
387
0
                if (ctx->args.pdfdebug)
388
0
                    dbgmprintf5(ctx->memory, "JPXDecode: COLR Meth %d at offset %d(0x%x), length %d(0x%x)\n",
389
0
                                cs_meth, info->icc_offset, info->icc_offset,
390
0
                                info->icc_length, info->icc_length);
391
0
                cs_enum = 0;
392
3
            } else {
393
3
                if (ctx->args.pdfdebug)
394
3
                    dbgmprintf1(ctx->memory, "JPXDecode: COLR unexpected method %d\n", cs_meth);
395
3
                cs_enum = 0;
396
3
            }
397
7.98k
            if (ctx->args.pdfdebug)
398
7.98k
                dbgmprintf2(ctx->memory, "    COLR: M:%d, ENUM:%d\n", cs_meth, cs_enum);
399
7.98k
            got_color = true;
400
7.98k
            break;
401
12
        case K4('p','c','l','r'):
402
            /* Apparently we just grab the BPC out of this */
403
12
            if (ctx->args.pdfdebug)
404
12
                dbgmprintf7(ctx->memory, "    PCLR Data: %x %x %x %x %x %x %x\n",
405
12
                      data[0], data[1], data[2], data[3], data[4], data[5], data[6]);
406
12
            if (box_len < 4) {
407
0
                code = gs_note_error(gs_error_syntaxerror);
408
0
                goto exit;
409
0
            }
410
12
            bpc = data[3];
411
12
            bpc = (bpc & 0x7) + 1;
412
12
            if (ctx->args.pdfdebug)
413
12
                dbgmprintf1(ctx->memory, "    PCLR BPC: %d\n", bpc);
414
12
            break;
415
75
        case K4('c','d','e','f'):
416
75
            dbgmprintf(ctx->memory, "JPXDecode: CDEF not supported yet\n");
417
75
            break;
418
17
        default:
419
17
            break;
420
8.08k
        }
421
422
8.08k
    }
423
424
7.98k
    info->comps = comps;
425
7.98k
    info->bpc = bpc;
426
7.98k
    info->cs_enum = cs_enum;
427
7.98k
    info->is_valid = true;
428
429
10.1k
 exit:
430
10.1k
    if (data)
431
10.1k
        gs_free_object(ctx->memory, data, "pdfi_scan_jpxfilter (data)");
432
    /* Always return 0 -- there are cases where this no image header at all, and just ignoring
433
     * the header seems to work.  In this case is_valid will be false, so we know not to rely on
434
     * the data from it.
435
     * Sample: tests_private/comparefiles/Bug694873.pdf
436
     */
437
10.1k
    return 0;
438
7.98k
}
439
440
/* Get image info out of dict into more convenient form, enforcing some requirements from the spec */
441
static int
442
pdfi_get_image_info(pdf_context *ctx, pdf_stream *image_obj,
443
                    pdf_dict *page_dict, pdf_dict *stream_dict, bool inline_image,
444
                    pdfi_image_info_t *info)
445
303k
{
446
303k
    int code;
447
303k
    double temp_f;
448
303k
    pdf_dict *image_dict = NULL;
449
450
303k
    memset(info, 0, sizeof(*info));
451
303k
    info->page_dict = page_dict;
452
303k
    info->stream_dict = stream_dict;
453
303k
    info->inline_image = inline_image;
454
455
    /* Not Handled: "ID", "OPI" */
456
457
    /* Length if it's in a stream dict */
458
303k
    info->Length = pdfi_stream_length(ctx, image_obj);
459
460
303k
    code = pdfi_dict_from_obj(ctx, (pdf_obj *)image_obj, &image_dict);
461
303k
    if (code < 0)
462
0
        goto errorExit;
463
464
    /* Required */
465
303k
    code = pdfi_dict_get_number2(ctx, image_dict, "Height", "H", &temp_f);
466
303k
    if (code < 0)
467
1.05k
        goto errorExit;
468
    /* This is bonkers, but... Bug695872.pdf has /W and /H which are real numbers */
469
302k
    info->Height = (int)temp_f;
470
302k
    if ((int)temp_f != (int)(temp_f+.5)) {
471
42
        if ((code = pdfi_set_warning_stop(ctx, gs_note_error(gs_error_rangecheck), NULL, W_PDF_BAD_IMAGEDICT, "pdfi_get_image_info", NULL)) < 0)
472
0
            goto errorExit;
473
42
    }
474
302k
    if (info->Height < 0) {
475
42
        if ((code = pdfi_set_warning_stop(ctx, gs_note_error(gs_error_rangecheck), NULL, W_PDF_BAD_IMAGEDICT, "pdfi_get_image_info", NULL)) < 0)
476
0
            goto errorExit;
477
42
        info->Height = 0;
478
42
    }
479
480
    /* Required */
481
302k
    code = pdfi_dict_get_number2(ctx, image_dict, "Width", "W", &temp_f);
482
302k
    if (code < 0)
483
488
        goto errorExit;
484
302k
    info->Width = (int)temp_f;
485
302k
    if ((int)temp_f != (int)(temp_f+.5)) {
486
18
        if ((code = pdfi_set_warning_stop(ctx, gs_note_error(gs_error_rangecheck), NULL, W_PDF_BAD_IMAGEDICT, "pdfi_get_image_info", NULL)) < 0)
487
0
            goto errorExit;
488
18
    }
489
302k
    if (info->Width < 0) {
490
16
        if ((code = pdfi_set_warning_stop(ctx, gs_note_error(gs_error_rangecheck), NULL, W_PDF_BAD_IMAGEDICT, "pdfi_get_image_info", NULL)) < 0)
491
0
            goto errorExit;
492
16
        info->Width = 0;
493
16
    }
494
495
    /* Optional, default false */
496
302k
    code = pdfi_dict_get_bool2(ctx, image_dict, "ImageMask", "IM", &info->ImageMask);
497
302k
    if (code != 0) {
498
96.5k
        if (code != gs_error_undefined)
499
8
            goto errorExit;
500
96.5k
        info->ImageMask = false;
501
96.5k
    }
502
503
    /* Optional, default false */
504
302k
    code = pdfi_dict_get_bool2(ctx, image_dict, "Interpolate", "I", &info->Interpolate);
505
302k
    if (code != 0) {
506
267k
        if (code != gs_error_undefined)
507
3
            goto errorExit;
508
267k
        info->Interpolate = false;
509
267k
    }
510
511
    /* Optional (Required, unless ImageMask is true)
512
     * But apparently for JPXDecode filter, this can be omitted.
513
     * Let's try a default of 1 for now...
514
     */
515
302k
    code = pdfi_dict_get_int2(ctx, image_dict, "BitsPerComponent", "BPC", &info->BPC);
516
302k
    if (code < 0) {
517
4.79k
        if (code != gs_error_undefined) {
518
6
            goto errorExit;
519
6
        }
520
4.78k
        info->BPC = 1;
521
4.78k
    }
522
297k
    else if (info->BPC != 1 && info->BPC != 2 && info->BPC != 4 && info->BPC != 8 && info->BPC != 16) {
523
229
        code = gs_note_error(gs_error_rangecheck);
524
229
        goto errorExit;
525
229
    }
526
    /* TODO: spec says if ImageMask is specified, and BPC is specified, then BPC must be 1
527
       Should we flag an error if this is violated?
528
     */
529
530
    /* Optional (apparently there is no "M" abbreviation for "Mask"? */
531
302k
    code = pdfi_dict_get(ctx, image_dict, "Mask", &info->Mask);
532
302k
    if (code < 0) {
533
        /* A lack of a Mask is not an error. If there is a genuine error reading
534
         * the Mask, ignore it unless PDFSTOPONWARNING is set. We can still render
535
         * the image. Arguably we should not, and Acrobat doesn't, but the current
536
         * GS implementation does.
537
         */
538
301k
        if (code != gs_error_undefined) {
539
72
           if ((code = pdfi_set_warning_stop(ctx, code, NULL, W_PDF_BAD_IMAGEDICT, "pdfi_get_image_info", NULL)) < 0)
540
0
               goto errorExit;
541
72
        }
542
301k
    }
543
302k
    if (info->Mask != NULL && (pdfi_type_of(info->Mask) != PDF_ARRAY && pdfi_type_of(info->Mask) != PDF_STREAM)) {
544
4
        pdfi_countdown(info->Mask);
545
4
        info->Mask = NULL;
546
4
        if ((code = pdfi_set_warning_stop(ctx, gs_note_error(gs_error_typecheck), NULL, W_PDF_BAD_IMAGEDICT, "pdfi_get_image_info", NULL)) < 0)
547
0
            goto errorExit;
548
4
    }
549
550
    /* Optional (apparently there is no abbreviation for "SMask"? */
551
302k
    code = pdfi_dict_get(ctx, image_dict, "SMask", &info->SMask);
552
302k
    if (code < 0) {
553
276k
        if (code != gs_error_undefined) {
554
            /* Broken SMask, Warn, and ignore the SMask */
555
4.31k
            if ((code = pdfi_set_warning_stop(ctx, code, NULL, W_PDF_BAD_IMAGEDICT, "pdfi_get_image_info", (char *)"*** Warning: Image has invalid SMask.  Ignoring it")) < 0)
556
0
                goto errorExit;
557
4.31k
        }
558
276k
    } else {
559
25.8k
        if (pdfi_type_of(info->SMask) == PDF_NAME) {
560
4
            pdf_obj *o = NULL;
561
562
4
            code = pdfi_find_resource(ctx, (unsigned char *)"ExtGState", (pdf_name *)info->SMask, image_dict, page_dict, &o);
563
4
            if (code >= 0) {
564
0
                pdfi_countdown(info->SMask);
565
0
                info->SMask = o;
566
0
            }
567
4
        }
568
569
25.8k
        if (pdfi_type_of(info->SMask) != PDF_STREAM){
570
189
            pdfi_countdown(info->SMask);
571
189
            info->SMask = NULL;
572
189
            if ((code = pdfi_set_warning_stop(ctx, gs_note_error(gs_error_typecheck), NULL, W_PDF_BAD_IMAGEDICT, "pdfi_get_image_info", NULL)) < 0)
573
0
                goto errorExit;
574
189
        }
575
25.8k
    }
576
577
    /* Optional, for JPXDecode filter images
578
     * (If non-zero, then SMask shouldn't be  specified)
579
     * Default: 0
580
     */
581
302k
    code = pdfi_dict_get_int(ctx, image_dict, "SMaskInData", &info->SMaskInData);
582
302k
    if (code < 0) {
583
302k
        if (code != gs_error_undefined)
584
0
            goto errorExit;
585
302k
        info->SMaskInData = 0;
586
302k
    }
587
588
    /* Optional (Required except for ImageMask, not allowed for ImageMask)*/
589
    /* TODO: Should we enforce this required/not allowed thing? */
590
302k
    code = pdfi_dict_get2(ctx, image_dict, "ColorSpace", "CS", &info->ColorSpace);
591
302k
    if (code < 0) {
592
210k
        if (code != gs_error_undefined)
593
95
            goto errorExit;
594
210k
    }
595
302k
    if (info->ColorSpace != NULL && (pdfi_type_of(info->ColorSpace) != PDF_NAME && pdfi_type_of(info->ColorSpace) != PDF_ARRAY)) {
596
111
        pdfi_countdown(info->ColorSpace);
597
111
        info->ColorSpace = NULL;
598
111
        if ((code = pdfi_set_warning_stop(ctx, gs_note_error(gs_error_typecheck), NULL, W_PDF_BAD_IMAGEDICT, "pdfi_get_image_info", NULL)) < 0)
599
0
            goto errorExit;
600
111
    }
601
602
    /* Optional (default is to use from graphics state) */
603
    /* (no abbreviation for inline) */
604
302k
    code = pdfi_dict_get_type(ctx, image_dict, "Intent", PDF_NAME, (pdf_obj **)&info->Intent);
605
302k
    if (code < 0) {
606
295k
        if (code != gs_error_undefined)
607
0
            goto errorExit;
608
295k
    }
609
610
    /* Optional (array of alternate image dicts, can't be nested) */
611
302k
    code = pdfi_dict_get(ctx, image_dict, "Alternates", &info->Alternates);
612
302k
    if (code < 0) {
613
302k
        if (code != gs_error_undefined)
614
0
            goto errorExit;
615
302k
    }
616
302k
    if (info->Alternates != NULL && pdfi_type_of(info->Alternates) != PDF_ARRAY) {
617
0
        pdfi_countdown(info->Alternates);
618
0
        info->Alternates = NULL;
619
0
        if ((code = pdfi_set_warning_stop(ctx, gs_note_error(gs_error_typecheck), NULL, W_PDF_BAD_IMAGEDICT, "pdfi_get_image_info", NULL)) < 0)
620
0
            goto errorExit;
621
0
    }
622
623
    /* Optional (required in PDF1.0, obsolete, do we support?) */
624
302k
    code = pdfi_dict_get(ctx, image_dict, "Name", &info->Name);
625
302k
    if (code < 0) {
626
283k
        if (code != gs_error_undefined)
627
0
            goto errorExit;
628
283k
    }
629
302k
    if (info->Name != NULL && pdfi_type_of(info->Name) != PDF_NAME) {
630
0
        pdfi_countdown(info->Name);
631
0
        info->Name = NULL;
632
0
        if ((code = pdfi_set_warning_stop(ctx, gs_note_error(gs_error_typecheck), NULL, W_PDF_BAD_IMAGENAME, "pdfi_get_image_info", NULL)) < 0)
633
0
            goto errorExit;
634
0
    }
635
636
    /* Required "if image is structural content item" */
637
    /* TODO: Figure out what to do here */
638
302k
    code = pdfi_dict_get_int(ctx, image_dict, "StructParent", &info->StructParent);
639
302k
    if (code < 0) {
640
302k
        if (code != gs_error_undefined)
641
0
            goto errorExit;
642
302k
    }
643
644
    /* Optional (default is probably [0,1] per component) */
645
302k
    code = pdfi_dict_get2(ctx, image_dict, "Decode", "D", &info->Decode);
646
302k
    if (code < 0) {
647
103k
        if (code != gs_error_undefined)
648
0
            goto errorExit;
649
103k
    }
650
302k
    if (info->Decode != NULL && pdfi_type_of(info->Decode) != PDF_ARRAY) {
651
227
        pdfi_countdown(info->Decode);
652
227
        info->Decode = NULL;
653
227
        if ((code = pdfi_set_warning_stop(ctx, gs_note_error(gs_error_typecheck), NULL, W_PDF_BAD_IMAGEDICT, "pdfi_get_image_info", NULL)) < 0)
654
0
            goto errorExit;
655
227
    }
656
657
    /* Optional "Optional Content" */
658
302k
    code = pdfi_dict_get_type(ctx, image_dict, "OC", PDF_DICT, (pdf_obj **)&info->OC);
659
302k
    if (code < 0) {
660
302k
        if (code != gs_error_undefined)
661
0
            goto errorExit;
662
302k
    }
663
664
    /* Optional */
665
302k
    code = pdfi_dict_get2(ctx, image_dict, "Filter", "F", &info->Filter);
666
302k
    if (code < 0) {
667
206k
        if (code != gs_error_undefined)
668
0
            goto errorExit;
669
206k
    }
670
302k
    if (info->Filter != NULL && (pdfi_type_of(info->Filter) != PDF_NAME && pdfi_type_of(info->Filter) != PDF_ARRAY)) {
671
0
        pdfi_countdown(info->Filter);
672
0
        info->Filter = NULL;
673
0
        if ((code = pdfi_set_warning_stop(ctx, gs_note_error(gs_error_typecheck), NULL, W_PDF_BAD_IMAGEDICT, "pdfi_get_image_info", NULL)) < 0)
674
0
             goto errorExit;
675
0
    }
676
677
    /* Check and set JPXDecode flag for later */
678
302k
    info->is_JPXDecode = false;
679
302k
    if (info->Filter) {
680
95.4k
        if (pdfi_type_of(info->Filter) == PDF_NAME) {
681
85.3k
            if (pdfi_name_is((pdf_name *)info->Filter, "JPXDecode"))
682
8.06k
                info->is_JPXDecode = true;
683
85.3k
        }
684
10.0k
        else if (pdfi_type_of(info->Filter) == PDF_ARRAY) {
685
10.0k
            int32_t l = (int32_t)pdfi_array_size((pdf_array *)info->Filter);
686
10.0k
            pdf_obj *f;
687
688
20.7k
            while (--l >= 0) {
689
10.7k
                code = pdfi_array_get(ctx, (pdf_array *)info->Filter, l, &f);
690
10.7k
                if (code >= 0) {
691
10.7k
                    if (pdfi_type_of(f) == PDF_NAME && pdfi_name_is((pdf_name *)f, "JPXDecode")) {
692
86
                        info->is_JPXDecode = true;
693
86
                        break;
694
86
                    }
695
10.7k
                }
696
10.7k
            }
697
10.0k
        }
698
95.4k
    }
699
700
    /* Optional */
701
302k
    code = pdfi_dict_get2(ctx, image_dict, "DecodeParms", "DP", &info->DecodeParms);
702
302k
    if (code < 0) {
703
270k
        if (code != gs_error_undefined)
704
6
            goto errorExit;
705
270k
    }
706
302k
    if (info->DecodeParms != NULL && (pdfi_type_of(info->DecodeParms) != PDF_DICT && pdfi_type_of(info->DecodeParms) != PDF_ARRAY)) {
707
        /* null is legal. Pointless but legal. */
708
0
        if (pdfi_type_of(info->DecodeParms) != PDF_NULL) {
709
0
            if ((code = pdfi_set_warning_stop(ctx, gs_note_error(gs_error_typecheck), NULL, W_PDF_BAD_IMAGEDICT, "pdfi_get_image_info", NULL)) < 0)
710
0
                goto errorExit;
711
0
        }
712
0
        pdfi_countdown(info->DecodeParms);
713
0
        info->DecodeParms = NULL;
714
0
    }
715
716
302k
    return 0;
717
718
1.88k
 errorExit:
719
1.88k
    pdfi_free_image_info_components(info);
720
1.88k
    return code;
721
302k
}
722
723
static int pdfi_check_inline_image_keys(pdf_context *ctx, pdf_dict *image_dict)
724
91.0k
{
725
91.0k
    bool known = false;
726
727
91.0k
    pdfi_dict_known(ctx, image_dict, "BPC", &known);
728
91.0k
    if (known)
729
0
        goto error_inline_check;
730
91.0k
    pdfi_dict_known(ctx, image_dict, "CS", &known);
731
91.0k
    if (known)
732
0
        goto error_inline_check;
733
91.0k
    pdfi_dict_known(ctx, image_dict, "D", &known);
734
91.0k
    if (known)
735
0
        goto error_inline_check;
736
91.0k
    pdfi_dict_known(ctx, image_dict, "DP", &known);
737
91.0k
    if (known)
738
0
        goto error_inline_check;
739
91.0k
    pdfi_dict_known(ctx, image_dict, "F", &known);
740
91.0k
    if (known)
741
0
        goto error_inline_check;
742
91.0k
    pdfi_dict_known(ctx, image_dict, "H", &known);
743
91.0k
    if (known)
744
0
        goto error_inline_check;
745
91.0k
    pdfi_dict_known(ctx, image_dict, "IM", &known);
746
91.0k
    if (known)
747
0
        goto error_inline_check;
748
91.0k
    pdfi_dict_known(ctx, image_dict, "I", &known);
749
91.0k
    if (known)
750
0
        goto error_inline_check;
751
91.0k
    pdfi_dict_known(ctx, image_dict, "W", &known);
752
91.0k
    if (known)
753
1
        goto error_inline_check;
754
755
91.0k
    return 0;
756
757
1
error_inline_check:
758
1
    return pdfi_set_warning_stop(ctx, gs_note_error(gs_error_syntaxerror), NULL, W_PDF_BAD_INLINEIMAGEKEY, "pdfi_check_inline_image_keys", NULL);
759
91.0k
}
760
761
/* Render a PDF image
762
 * pim can be type1 (or imagemask), type3, type4
763
 */
764
static int
765
pdfi_render_image(pdf_context *ctx, gs_pixel_image_t *pim, pdf_c_stream *image_stream,
766
                  unsigned char *mask_buffer, uint64_t mask_size,
767
                  int comps, bool ImageMask)
768
284k
{
769
284k
    int code;
770
284k
    gs_image_enum *penum = NULL;
771
284k
    uint64_t bytes_left;
772
284k
    uint64_t bytes_used = 0;
773
284k
    uint64_t bytes_avail = 0;
774
284k
    gs_const_string plane_data[GS_IMAGE_MAX_COMPONENTS];
775
284k
    int main_plane=0, mask_plane=0;
776
284k
    bool no_progress = false;
777
284k
    int min_left;
778
779
#if DEBUG_IMAGES
780
    dbgmprintf(ctx->memory, "pdfi_render_image BEGIN\n");
781
#endif
782
783
284k
    code = pdfi_gsave(ctx);
784
284k
    if (code < 0)
785
0
        return code;
786
787
    /* Disable overprint mode for images that are not a mask */
788
284k
    if (!ImageMask)
789
78.6k
        gs_setoverprintmode(ctx->pgs, 0);
790
791
284k
    penum = gs_image_enum_alloc(ctx->memory, "pdfi_render_image (gs_image_enum_alloc)");
792
284k
    if (!penum) {
793
0
        code = gs_note_error(gs_error_VMerror);
794
0
        goto cleanupExit;
795
0
    }
796
797
    /* Took this logic from gs_image_init()
798
     * (the other tests in there have already been handled elsewhere)
799
     */
800
284k
    {
801
284k
        gx_image_enum_common_t *pie;
802
803
284k
        if (!ImageMask) {
804
            /* TODO: Can in_cachedevice ever be set in PDF? */
805
78.6k
            if (ctx->pgs->in_cachedevice != CACHE_DEVICE_NONE) {
806
0
                code = gs_note_error(gs_error_undefined);
807
0
                goto cleanupExit;
808
0
            }
809
78.6k
        }
810
811
284k
        code = gs_image_begin_typed((const gs_image_common_t *)pim, ctx->pgs, ImageMask, false, &pie);
812
284k
        if (code < 0)
813
1.40k
            goto cleanupExit;
814
815
282k
        code = gs_image_enum_init(penum, pie, (const gs_data_image_t *)pim, ctx->pgs);
816
282k
        if (code < 0)
817
0
            goto cleanupExit;
818
282k
    }
819
820
    /* NOTE: I used image_file_continue() as my template for this code.
821
     * But this case is (hopefully) much much simpler.
822
     * We only handle two situations -- if there is mask_data, then we assume there are two planes.
823
     * If no mask_data, then there is one plane.
824
     */
825
282k
    if (mask_buffer) {
826
4.36k
        main_plane = 1;
827
4.36k
        mask_plane = 0;
828
4.36k
        plane_data[mask_plane].data = mask_buffer;
829
4.36k
        plane_data[mask_plane].size = mask_size;
830
278k
    } else {
831
278k
        main_plane = 0;
832
278k
    }
833
834
282k
    bytes_left = pdfi_get_image_data_size((gs_data_image_t *)pim, comps);
835
7.39M
    while (bytes_left > 0) {
836
7.13M
        uint used[GS_IMAGE_MAX_COMPONENTS];
837
838
14.0M
        while ((bytes_avail = sbufavailable(image_stream->s)) <= (min_left = sbuf_min_left(image_stream->s))) {
839
6.94M
            switch (image_stream->s->end_status) {
840
6.91M
            case 0:
841
6.91M
                s_process_read_buf(image_stream->s);
842
6.91M
                continue;
843
5.33k
            case EOFC:
844
5.33k
            case INTC:
845
5.33k
            case CALLC:
846
5.33k
                break;
847
22.5k
            default:
848
                /* case ERRC: */
849
22.5k
                code = gs_note_error(gs_error_ioerror);
850
22.5k
                goto cleanupExit;
851
6.94M
            }
852
5.33k
            break;   /* for EOFC */
853
6.94M
        }
854
855
        /*
856
         * Note that in the EOF case, we can get here with no data
857
         * available.
858
         */
859
7.11M
        if (bytes_avail >= min_left)
860
7.11M
            bytes_avail = (bytes_avail - min_left); /* may be 0 */
861
862
7.11M
        plane_data[main_plane].data = sbufptr(image_stream->s);
863
7.11M
        plane_data[main_plane].size = bytes_avail;
864
865
7.11M
        code = gs_image_next_planes(penum, plane_data, used, false);
866
7.11M
        if (code < 0) {
867
49
            goto cleanupExit;
868
49
        }
869
        /* If no data was consumed twice in a row, then there must be some kind of error,
870
         * even if the error code was not < 0.  Saw this with pdfwrite device.
871
         */
872
7.11M
        if (used[main_plane] == 0 && used[mask_plane] == 0) {
873
5.96k
            if (no_progress) {
874
2.98k
                code = gs_note_error(gs_error_unknownerror);
875
2.98k
                goto cleanupExit;
876
2.98k
            }
877
2.98k
            no_progress = true;
878
7.10M
        } else {
879
7.10M
            no_progress = false;
880
7.10M
        }
881
882
7.10M
        (void)sbufskip(image_stream->s, used[main_plane]);
883
884
        /* It might not always consume all the data, but so far the only case
885
         * I have seen with that was one that had mask data.
886
         * In that case, it used all of plane 0, and none of plane 1 on the first pass.
887
         * (image_2bpp.pdf)
888
         *
889
         * Anyway, this math should handle that case (as well as a case where it consumed only
890
         * part of the data, if that can actually happen).
891
         */
892
7.10M
        bytes_used = used[main_plane];
893
7.10M
        bytes_left -= bytes_used;
894
7.10M
        bytes_avail -= bytes_used;
895
7.10M
    }
896
897
257k
    code = 0;
898
899
284k
 cleanupExit:
900
284k
    if (penum)
901
284k
        gs_image_cleanup_and_free_enum(penum, ctx->pgs);
902
284k
    pdfi_grestore(ctx);
903
#if DEBUG_IMAGES
904
    dbgmprintf(ctx->memory, "pdfi_render_image END\n");
905
#endif
906
284k
    return code;
907
257k
}
908
909
/* Load up params common to the different image types */
910
static int
911
pdfi_data_image_params(pdf_context *ctx, pdfi_image_info_t *info,
912
                       gs_data_image_t *pim, int comps, gs_color_space *pcs)
913
290k
{
914
290k
    int code;
915
916
290k
    pim->BitsPerComponent = info->BPC;
917
290k
    pim->Width = info->Width;
918
290k
    pim->Height = info->Height;
919
290k
    pim->ImageMatrix.xx = (float)info->Width;
920
290k
    pim->ImageMatrix.yy = (float)(info->Height * -1);
921
290k
    pim->ImageMatrix.ty = (float)info->Height;
922
923
290k
    pim->Interpolate = info->Interpolate;
924
925
    /* Get the decode array (required for ImageMask, probably for everything) */
926
290k
    if (info->Decode) {
927
198k
        pdf_array *decode_array = (pdf_array *)info->Decode;
928
198k
        int i;
929
198k
        double num;
930
931
198k
        if (pdfi_array_size(decode_array) > GS_IMAGE_MAX_COMPONENTS * 2) {
932
0
            code = gs_note_error(gs_error_limitcheck);
933
0
            goto cleanupExit;
934
0
        }
935
936
597k
        for (i=0; i<pdfi_array_size(decode_array); i++) {
937
399k
            code = pdfi_array_get_number(ctx, decode_array, i, &num);
938
399k
            if (code < 0)
939
9
                goto cleanupExit;
940
399k
            pim->Decode[i] = (float)num;
941
399k
        }
942
198k
    } else {
943
        /* Provide a default if not specified [0 1 ...] per component */
944
92.1k
        int i;
945
92.1k
        float minval, maxval;
946
947
        /* TODO: Is there a less hacky way to identify Indexed case? */
948
92.1k
        if (pcs && (pcs->type == &gs_color_space_type_Indexed ||
949
71.3k
                    pcs->type == &gs_color_space_type_Indexed_Named)) {
950
            /* Default value is [0,N], where N=2^n-1, our hival (which depends on BPC)*/
951
8.46k
            minval = 0.0;
952
8.46k
            maxval = (float)((1 << info->BPC) - 1);
953
83.7k
        } else {
954
83.7k
            bool islab = false;
955
956
83.7k
            if (pcs && pcs->cmm_icc_profile_data != NULL)
957
71.1k
                islab = pcs->cmm_icc_profile_data->islab;
958
959
83.7k
            if(islab) {
960
0
                pim->Decode[0] = 0.0;
961
0
                pim->Decode[1] = 100.0;
962
0
                pim->Decode[2] = pcs->cmm_icc_profile_data->Range.ranges[1].rmin;
963
0
                pim->Decode[3] = pcs->cmm_icc_profile_data->Range.ranges[1].rmax;
964
0
                pim->Decode[4] = pcs->cmm_icc_profile_data->Range.ranges[2].rmin;
965
0
                pim->Decode[5] = pcs->cmm_icc_profile_data->Range.ranges[2].rmax;
966
0
                return 0;
967
83.7k
            } else {
968
83.7k
                minval = 0.0;
969
83.7k
                maxval = 1.0;
970
83.7k
            }
971
83.7k
        }
972
279k
        for (i=0; i<comps*2; i+=2) {
973
187k
            pim->Decode[i] = minval;
974
187k
            pim->Decode[i+1] = maxval;
975
187k
        }
976
92.1k
    }
977
290k
    code = 0;
978
979
290k
 cleanupExit:
980
290k
    return code;
981
290k
}
982
983
/* Returns number of components in Matte array or 0 if not found, <0 if error */
984
static int
985
pdfi_image_get_matte(pdf_context *ctx, pdf_obj *smask_obj, float *vals, int size, bool *has_Matte)
986
23.5k
{
987
23.5k
    int i;
988
23.5k
    pdf_array *Matte = NULL;
989
23.5k
    int code;
990
23.5k
    double f;
991
23.5k
    pdf_dict *smask_dict = NULL;
992
993
23.5k
    *has_Matte = false;
994
23.5k
    code = pdfi_dict_from_obj(ctx, smask_obj, &smask_dict);
995
23.5k
    if (code < 0)
996
0
        goto exit;
997
998
23.5k
    code = pdfi_dict_knownget_type(ctx, smask_dict, "Matte",
999
23.5k
                                   PDF_ARRAY, (pdf_obj **)&Matte);
1000
23.5k
    if (code <= 0)
1001
23.5k
        goto exit;
1002
1003
26
    *has_Matte = true;
1004
26
    if (pdfi_array_size(Matte) > size) {
1005
0
        code = gs_note_error(gs_error_rangecheck);
1006
0
        goto exit;
1007
0
    }
1008
1009
104
    for (i = 0; i < pdfi_array_size(Matte); i++) {
1010
78
        code = pdfi_array_get_number(ctx, Matte, (uint64_t)i, &f);
1011
78
        if (code < 0)
1012
0
            goto exit;
1013
78
        vals[i] = (float)f;
1014
78
    }
1015
26
    if (i == pdfi_array_size(Matte))
1016
26
        code = i;
1017
1018
23.5k
 exit:
1019
23.5k
    pdfi_countdown(Matte);
1020
23.5k
    return code;
1021
26
}
1022
1023
/* See ztrans.c/zbegintransparencymaskimage() and pdf_draw.ps/doimagesmask */
1024
static int
1025
pdfi_do_image_smask(pdf_context *ctx, pdf_c_stream *source, pdfi_image_info_t *image_info, bool *has_Matte)
1026
19.5k
{
1027
19.5k
    gs_rect bbox = { { 0, 0} , { 1, 1} };
1028
19.5k
    gs_transparency_mask_params_t params;
1029
19.5k
    gs_offset_t savedoffset = 0;
1030
19.5k
    int code, code1;
1031
19.5k
    pdfi_int_gstate *igs = (pdfi_int_gstate *)ctx->pgs->client_data;
1032
19.5k
    pdf_stream *stream_obj = NULL;
1033
19.5k
    gs_rect clip_box;
1034
19.5k
    int empty = 0;
1035
1036
#if DEBUG_IMAGES
1037
    dbgmprintf(ctx->memory, "pdfi_do_image_smask BEGIN\n");
1038
#endif
1039
1040
19.5k
    code = pdfi_loop_detector_mark(ctx);
1041
19.5k
    if (code < 0)
1042
0
        return code;
1043
1044
19.5k
    if (pdfi_type_of(image_info->SMask) != PDF_STREAM)
1045
0
        return_error(gs_error_typecheck);
1046
1047
19.5k
    if (image_info->SMask->object_num != 0) {
1048
19.5k
        if (pdfi_loop_detector_check_object(ctx, image_info->SMask->object_num))
1049
0
            return gs_note_error(gs_error_circular_reference);
1050
19.5k
        code = pdfi_loop_detector_add_object(ctx, image_info->SMask->object_num);
1051
19.5k
        if (code < 0)
1052
0
            goto exit;
1053
19.5k
    }
1054
1055
19.5k
    gs_trans_mask_params_init(&params, TRANSPARENCY_MASK_Luminosity);
1056
1057
    /* gs_begin_transparency_mask is going to crap all over the current
1058
     * graphics state. We need to be sure that everything goes back as
1059
     * it was. So, gsave here, and grestore on the 'end', right? Well
1060
     * that doesn't work, cos then we throw away the SMask we've just
1061
     * drawn! We'll do some magic to ensure that doesn't happen. */
1062
19.5k
    code = gs_gsave(ctx->pgs);
1063
19.5k
    if (code < 0)
1064
0
        goto exit;
1065
1066
19.5k
    if (gs_clip_bounds_in_user_space(ctx->pgs, &clip_box) >= 0)
1067
19.4k
    {
1068
19.4k
        rect_intersect(bbox, clip_box);
1069
19.4k
        if (bbox.p.x >= bbox.q.x || bbox.p.y >= bbox.q.y)
1070
737
        {
1071
            /* If the bbox is illegal, we still need to set up an empty mask.
1072
             * We can't just skip forwards as everything will now be unmasked!
1073
             * We can skip doing the actual work though. */
1074
737
            empty = 1;
1075
737
        }
1076
19.4k
    }
1077
1078
19.5k
    code = pdfi_image_get_matte(ctx, image_info->SMask, params.Matte, GS_CLIENT_COLOR_MAX_COMPONENTS, has_Matte);
1079
1080
19.5k
    if (code < 0) {
1081
0
        code = pdfi_set_warning_stop(ctx, code, NULL, W_PDF_ERROR_IN_MATTE, "", NULL);
1082
0
        if (code < 0)
1083
0
            goto exitSaved;
1084
0
    }
1085
19.5k
    if (code >= 0)
1086
19.5k
        params.Matte_components = code;
1087
1088
19.5k
    code = gs_begin_transparency_mask(ctx->pgs, &params, &bbox, true);
1089
19.5k
    if (code < 0)
1090
0
        goto exitSaved;
1091
19.5k
    if (empty)
1092
737
        goto exitMasked;
1093
18.7k
    savedoffset = pdfi_tell(ctx->main_stream);
1094
18.7k
    code = pdfi_gsave(ctx);
1095
18.7k
    if (code < 0)
1096
0
        goto exitMasked;
1097
1098
    /* Disable SMask for inner image */
1099
18.7k
    pdfi_gstate_smask_free(igs);
1100
1101
18.7k
    gs_setstrokeconstantalpha(ctx->pgs, 1.0);
1102
18.7k
    gs_setfillconstantalpha(ctx->pgs, 1.0);
1103
18.7k
    gs_setblendmode(ctx->pgs, BLEND_MODE_Compatible);
1104
1105
18.7k
    pdfi_seek(ctx, ctx->main_stream,
1106
18.7k
              pdfi_stream_offset(ctx, (pdf_stream *)image_info->SMask), SEEK_SET);
1107
1108
18.7k
    switch (pdfi_type_of(image_info->SMask)) {
1109
0
        case PDF_DICT:
1110
0
            code = pdfi_obj_dict_to_stream(ctx, (pdf_dict *)image_info->SMask, &stream_obj, false);
1111
0
            if (code == 0) {
1112
0
                code = pdfi_do_image_or_form(ctx, image_info->stream_dict,
1113
0
                                             image_info->page_dict, (pdf_obj *)stream_obj);
1114
1115
0
                pdfi_countdown(stream_obj);
1116
0
            }
1117
0
            break;
1118
18.7k
        case PDF_STREAM:
1119
18.7k
            code = pdfi_do_image_or_form(ctx, image_info->stream_dict,
1120
18.7k
                                         image_info->page_dict, image_info->SMask);
1121
18.7k
            break;
1122
0
        default:
1123
0
            code = gs_note_error(gs_error_typecheck);
1124
0
            goto exitSavedTwice;
1125
18.7k
    }
1126
1127
18.7k
exitSavedTwice:
1128
18.7k
    pdfi_seek(ctx, ctx->main_stream, savedoffset, SEEK_SET);
1129
1130
18.7k
    code1 = pdfi_grestore(ctx);
1131
18.7k
    if (code < 0)
1132
0
        code = code1;
1133
19.5k
exitMasked:
1134
19.5k
    code1 = gs_end_transparency_mask(ctx->pgs, TRANSPARENCY_CHANNEL_Opacity);
1135
19.5k
    if (code < 0)
1136
0
        code = code1;
1137
19.5k
exitSaved:
1138
    /* This is where we have to do some magic. If we just grestore here, then
1139
     * any SMask we've rendered will be popped away. */
1140
19.5k
    {
1141
        /* Stash the flag that means 'Pop the SMask'. */
1142
19.5k
        int flag = ctx->pgs->trans_flags.xstate_change;
1143
        /* Clear the flag so the SMask will live. */
1144
19.5k
        ctx->pgs->trans_flags.xstate_change = 0;
1145
19.5k
        code1 = gs_grestore(ctx->pgs);
1146
19.5k
        if (code < 0)
1147
0
            code = code1;
1148
        /* Put the flag back 1 level higher. This relies on the fact that
1149
         * the graphics state we return to does not already have this set.
1150
         * We ensure that by ensuring that callers have gsaved/grestored
1151
         * around this. */
1152
19.5k
        ctx->pgs->trans_flags.xstate_change = flag;
1153
19.5k
    }
1154
1155
19.5k
 exit:
1156
#if DEBUG_IMAGES
1157
    dbgmprintf(ctx->memory, "pdfi_do_image_smask END\n");
1158
#endif
1159
19.5k
    pdfi_loop_detector_cleartomark(ctx);
1160
19.5k
    return code;
1161
19.5k
}
1162
1163
1164
/* Setup for transparency (see pdf_draw.ps/doimage) */
1165
static int
1166
pdfi_image_setup_trans(pdf_context *ctx, pdfi_trans_state_t *state)
1167
5.69k
{
1168
5.69k
    int code;
1169
5.69k
    gs_rect bbox;
1170
1171
    /* We need to create a bbox in order to pass it to the transparency setup,
1172
     * which (potentially, at least, uses it to set up a transparency group.
1173
     * Setting up a 1x1 path, and establishing it's BBox will work, because
1174
     * the image scaling is already in place. We don't want to disturb the
1175
     * graphics state, so do this inside a gsave/grestore pair.
1176
     */
1177
5.69k
    code = pdfi_gsave(ctx);
1178
5.69k
    if (code < 0)
1179
0
        return code;
1180
1181
5.69k
    code = gs_newpath(ctx->pgs);
1182
5.69k
    if (code < 0)
1183
0
        goto exit;
1184
5.69k
    code = gs_moveto(ctx->pgs, 1.0, 1.0);
1185
5.69k
    if (code < 0)
1186
0
        goto exit;
1187
5.69k
    code = gs_lineto(ctx->pgs, 0., 0.);
1188
5.69k
    if (code < 0)
1189
0
        goto exit;
1190
1191
5.69k
    code = pdfi_get_current_bbox(ctx, &bbox, false);
1192
5.69k
    if (code < 0)
1193
452
        goto exit;
1194
1195
5.24k
    pdfi_grestore(ctx);
1196
1197
5.24k
    code = pdfi_trans_setup(ctx, state, &bbox, TRANSPARENCY_Caller_Image);
1198
5.69k
 exit:
1199
5.69k
    return code;
1200
5.24k
}
1201
1202
1203
/* Setup a type 4 image, particularly the MaskColor array.
1204
 * Handles error situations like pdf_draw.ps/makemaskimage
1205
 */
1206
static int
1207
pdfi_image_setup_type4(pdf_context *ctx, pdfi_image_info_t *image_info,
1208
                       gs_image4_t *t4image,
1209
                       pdf_array *mask_array, gs_color_space *pcs)
1210
157
{
1211
157
    int i;
1212
157
    double num;
1213
157
    int code = 0;
1214
157
    int bpc = image_info->BPC;
1215
157
    uint mask = (1 << bpc) - 1;
1216
157
    uint maxval = mask;
1217
157
    int64_t intval;
1218
157
    bool had_range_error = false;
1219
157
    bool had_float_error = false;
1220
    /* Check for special case of Indexed and BPC=1 (to match AR)
1221
     * See bugs: 692852, 697919, 689717
1222
     */
1223
157
    bool indexed_case = (pcs && pcs->type == &gs_color_space_type_Indexed && bpc == 1);
1224
1225
157
    memset(t4image, 0, sizeof(gs_image4_t));
1226
157
    gs_image4_t_init(t4image, NULL);
1227
1228
157
    if (pdfi_array_size(mask_array) > GS_IMAGE_MAX_COMPONENTS * 2) {
1229
0
        code = gs_note_error(gs_error_rangecheck);
1230
0
        goto exit;
1231
0
    }
1232
1233
1.02k
    for (i=0; i<pdfi_array_size(mask_array); i++) {
1234
879
        code = pdfi_array_get_int(ctx, mask_array, i, &intval);
1235
879
        if (code == gs_error_typecheck) {
1236
7
            code = pdfi_array_get_number(ctx, mask_array, i, &num);
1237
7
            if (code == 0) {
1238
0
                intval = (int64_t)(num + 0.5);
1239
0
                had_float_error = true;
1240
0
            }
1241
7
        }
1242
879
        if (code < 0)
1243
7
            goto exit;
1244
872
        if (intval > maxval) {
1245
9
            had_range_error = true;
1246
9
            if (indexed_case) {
1247
0
                if (i == 0) {
1248
                    /* If first component is invalid, AR9 ignores the mask. */
1249
0
                    code = gs_note_error(gs_error_rangecheck);
1250
0
                    goto exit;
1251
0
                } else {
1252
                    /* If second component is invalid, AR9 replace it with 1. */
1253
0
                    intval = 1;
1254
0
                }
1255
9
            } else {
1256
9
                if (bpc != 1) {
1257
                    /* If not special handling, just mask it off to be in range */
1258
9
                    intval &= mask;
1259
9
                }
1260
9
            }
1261
9
        }
1262
872
        t4image->MaskColor[i] = intval;
1263
872
    }
1264
150
    t4image->MaskColor_is_range = true;
1265
1266
    /* Another special handling (see Bug701468)
1267
     * If 1 BPC and the two entries are not the same, ignore the mask
1268
     */
1269
150
    if (!indexed_case && bpc == 1 && had_range_error) {
1270
0
        if (t4image->MaskColor[0] != t4image->MaskColor[1]) {
1271
0
            code = gs_note_error(gs_error_rangecheck);
1272
0
            goto exit;
1273
0
        } else {
1274
0
            t4image->MaskColor[0] &= mask;
1275
0
            t4image->MaskColor[1] &= mask;
1276
0
        }
1277
0
    }
1278
1279
150
    code = 0;
1280
1281
157
 exit:
1282
157
    if (had_float_error) {
1283
0
        pdfi_set_warning(ctx, gs_note_error(gs_error_typecheck), NULL, W_PDF_IMAGE_ERROR, "pdfi_image_setup_type4", (char *)"*** Error: Some elements of Mask array are not integers");
1284
0
    }
1285
157
    if (had_range_error) {
1286
9
        pdfi_set_warning(ctx, gs_note_error(gs_error_typecheck), NULL, W_PDF_IMAGE_ERROR, "pdfi_image_setup_type4", (char *)"*** Error: Some elements of Mask array are out of range");
1287
9
    }
1288
157
    return code;
1289
150
}
1290
1291
/* Setup a type 3x image
1292
 */
1293
static int
1294
pdfi_image_setup_type3x(pdf_context *ctx, pdfi_image_info_t *image_info,
1295
                        gs_image3x_t *t3ximage, pdfi_image_info_t *smask_info, int comps)
1296
4.05k
{
1297
4.05k
    int code = 0;
1298
4.05k
    gs_image3x_mask_t *mask;
1299
1300
4.05k
    memset(t3ximage, 0, sizeof(*t3ximage));
1301
4.05k
    gs_image3x_t_init(t3ximage, NULL);
1302
4.05k
    if (gs_getalphaisshape(ctx->pgs))
1303
4
        mask = &t3ximage->Shape;
1304
4.05k
    else
1305
4.05k
        mask = &t3ximage->Opacity;
1306
4.05k
    mask->InterleaveType = 3;
1307
1308
4.05k
    code = pdfi_image_get_matte(ctx, image_info->SMask, mask->Matte, GS_CLIENT_COLOR_MAX_COMPONENTS, &mask->has_Matte);
1309
4.05k
    if (code < 0)
1310
0
        return code;
1311
1312
4.05k
    code = pdfi_data_image_params(ctx, smask_info, &mask->MaskDict, comps, NULL);
1313
4.05k
    return code;
1314
4.05k
}
1315
1316
static int pdfi_create_JPX_Lab(pdf_context *ctx, pdf_obj **ColorSpace)
1317
0
{
1318
0
    int code, i;
1319
0
    pdf_name *SpaceName = NULL, *WhitePointName = NULL;
1320
0
    pdf_dict *Params = NULL;
1321
0
    pdf_array *WhitePoint = NULL;
1322
0
    double WP[3] = {0.9505, 1.0, 1.0890};
1323
0
    pdf_num *num = NULL;
1324
1325
0
    *ColorSpace = NULL;
1326
0
    code = pdfi_name_alloc(ctx, (byte *)"Lab", 3, (pdf_obj **)&SpaceName);
1327
0
    if (code < 0)
1328
0
        goto cleanupExit;
1329
0
    pdfi_countup(SpaceName);
1330
1331
0
    code = pdfi_dict_alloc(ctx, 1, &Params);
1332
0
    if (code < 0)
1333
0
        goto cleanupExit;
1334
0
    pdfi_countup(Params);
1335
1336
0
    code = pdfi_name_alloc(ctx, (byte *)"WhitePoint", 3, (pdf_obj **)&WhitePointName);
1337
0
    if (code < 0)
1338
0
        goto cleanupExit;
1339
0
    pdfi_countup(WhitePointName);
1340
1341
0
    code = pdfi_array_alloc(ctx, 3, &WhitePoint);
1342
0
    if (code < 0)
1343
0
        goto cleanupExit;
1344
0
    pdfi_countup(WhitePoint);
1345
1346
0
    for (i = 0; i < 3; i++) {
1347
0
        code = pdfi_object_alloc(ctx, PDF_REAL, 0, (pdf_obj **)&num);
1348
0
        if (code < 0)
1349
0
            goto cleanupExit;
1350
0
        num->value.d = WP[i];
1351
0
        pdfi_countup(num);
1352
0
        code = pdfi_array_put(ctx, WhitePoint, i, (pdf_obj *)num);
1353
0
        if (code < 0)
1354
0
            goto cleanupExit;
1355
0
        pdfi_countdown(num);
1356
0
    }
1357
0
    num = NULL;
1358
1359
0
    code = pdfi_dict_put_obj(ctx, Params, (pdf_obj *)WhitePointName, (pdf_obj *)WhitePoint, true);
1360
0
    if (code < 0)
1361
0
        goto cleanupExit;
1362
1363
0
    pdfi_countdown(WhitePointName);
1364
0
    WhitePointName = NULL;
1365
0
    pdfi_countdown(WhitePoint);
1366
0
    WhitePoint = NULL;
1367
1368
0
    code = pdfi_array_alloc(ctx, 2, (pdf_array **)ColorSpace);
1369
0
    if (code < 0)
1370
0
        goto cleanupExit;
1371
1372
0
    code = pdfi_array_put(ctx, (pdf_array *)*ColorSpace, 0, (pdf_obj *)SpaceName);
1373
0
    if (code < 0)
1374
0
        goto cleanupExit;
1375
0
    pdfi_countdown(SpaceName);
1376
0
    SpaceName = NULL;
1377
1378
0
    code = pdfi_array_put(ctx, (pdf_array *)*ColorSpace, 1, (pdf_obj *)Params);
1379
0
    if (code < 0)
1380
0
        goto cleanupExit;
1381
0
    pdfi_countdown(Params);
1382
1383
0
    return 0;
1384
1385
0
cleanupExit:
1386
0
    pdfi_countdown(*ColorSpace);
1387
0
    pdfi_countdown(SpaceName);
1388
0
    pdfi_countdown(Params);
1389
0
    pdfi_countdown(WhitePointName);
1390
0
    pdfi_countdown(WhitePoint);
1391
0
    pdfi_countdown(num);
1392
0
    return code;
1393
0
}
1394
1395
static int
1396
pdfi_image_get_color(pdf_context *ctx, pdf_c_stream *source, pdfi_image_info_t *image_info,
1397
                     int *comps, ulong dictkey, gs_color_space **pcs)
1398
291k
{
1399
291k
    int code = 0;
1400
291k
    pdfi_jpx_info_t *jpx_info = &image_info->jpx_info;
1401
291k
    pdf_obj *ColorSpace = NULL;
1402
291k
    char *backup_color_name = NULL;
1403
291k
    bool using_enum_cs = false;
1404
1405
    /* NOTE: Spec says ImageMask and ColorSpace mutually exclusive
1406
     * We need to make sure we do not have both set or we could end up treating
1407
     * an image as a mask or vice versa and trying to use a non-existent colour space.
1408
     */
1409
291k
    if (image_info->ImageMask) {
1410
205k
        if (image_info->ColorSpace == NULL) {
1411
204k
                *comps = 1;
1412
204k
                *pcs = NULL;
1413
204k
                if (image_info->Mask) {
1414
0
                    pdfi_countdown(image_info->Mask);
1415
0
                    image_info->Mask = NULL;
1416
0
                }
1417
204k
                return 0;
1418
204k
        } else {
1419
1.18k
            if (image_info->BPC != 1 || image_info->Mask != NULL) {
1420
26
                if ((code = pdfi_set_error_stop(ctx, gs_note_error(gs_error_rangecheck), NULL, E_IMAGE_MASKWITHCOLOR, "pdfi_image_get_color", "BitsPerComonent is not 1, so treating as an image")) < 0) {
1421
0
                    return code;
1422
0
                }
1423
26
                image_info->ImageMask = 0;
1424
26
            }
1425
1.15k
            else {
1426
1.15k
                if ((code = pdfi_set_error_stop(ctx, gs_note_error(gs_error_rangecheck), NULL, E_IMAGE_MASKWITHCOLOR, "pdfi_image_get_color", "BitsPerComonent is 1, so treating as a mask")) < 0) {
1427
0
                    return code;
1428
0
                }
1429
1.15k
                pdfi_countdown(image_info->ColorSpace);
1430
1.15k
                image_info->ColorSpace = NULL;
1431
1.15k
                *comps = 1;
1432
1.15k
                *pcs = NULL;
1433
1.15k
                return 0;
1434
1.15k
            }
1435
1.18k
        }
1436
205k
    }
1437
1438
85.6k
    ColorSpace = image_info->ColorSpace;
1439
85.6k
    if (ColorSpace)
1440
79.7k
        pdfi_countup(ColorSpace);
1441
85.6k
    if (ColorSpace == NULL) {
1442
5.97k
        if (image_info->is_JPXDecode) {
1443
            /* The graphics library doesn't support 12-bit images, so the openjpeg layer
1444
             * (see sjpx_openjpeg.c/decode_image()) is going to translate the 12-bits up to 16-bits.
1445
             * That means we just treat it as 16-bit when rendering, so force the value
1446
             * to 16 here.
1447
             */
1448
5.95k
            if (jpx_info->bpc == 12) {
1449
0
                jpx_info->bpc = 16;
1450
0
            }
1451
5.95k
            image_info->BPC = jpx_info->bpc;
1452
1453
5.95k
            if (jpx_info->iccbased) {
1454
0
                int dummy; /* Holds number of components read from the ICC profile, we ignore this here */
1455
1456
0
                code = pdfi_create_icc_colorspace_from_stream(ctx, source, jpx_info->icc_offset,
1457
0
                                                              jpx_info->icc_length, jpx_info->comps, &dummy,
1458
0
                                                              dictkey, pcs);
1459
0
                if (code < 0) {
1460
0
                    code = pdfi_set_error_stop(ctx, code, NULL, E_PDF_JPX_CS_ERROR, "pdfi_image_get_color", NULL);
1461
0
                    dbgprintf2("WARNING JPXDecode: Error setting icc colorspace (offset=%d,len=%d)\n",
1462
0
                              jpx_info->icc_offset, jpx_info->icc_length);
1463
0
                    goto cleanupExit;
1464
0
                }
1465
0
                *comps = gs_color_space_num_components(*pcs);
1466
0
                goto cleanupExit;
1467
5.95k
            } else {
1468
5.95k
                char *color_str = NULL;
1469
1470
                /* TODO: These colorspace names are pulled from the gs code (jp2_csp_dict), but need
1471
                 * to be implemented to actually work.
1472
                 */
1473
5.95k
                backup_color_name = (char *)"DeviceRGB";
1474
5.95k
                switch(jpx_info->cs_enum) {
1475
0
                case 12:
1476
0
                    color_str = (char *)"DeviceCMYK";
1477
0
                    break;
1478
0
                case 14:
1479
                    /* All the other colour spaces are set by name, either a device name or a
1480
                     * 'special' internal name (same as Ghostscript) which is picked up in
1481
                     * pdfi_create_colorspace_by_name() in pdf_colour.c. These names must
1482
                     * match!
1483
                     * However for Lab we need to set a White Point and its simplest just
1484
                     * to create an appropriate color space array here.
1485
                     */
1486
0
                    code = pdfi_create_JPX_Lab(ctx, &ColorSpace);
1487
0
                    if (code < 0)
1488
0
                        goto cleanupExit;
1489
0
                    break;
1490
451
                case 16:
1491
451
                    color_str = (char *)"sRGBICC";
1492
451
                    break;
1493
3.42k
                case 17:
1494
3.42k
                    color_str = (char *)"sGrayICC";
1495
3.42k
                    backup_color_name = (char *)"DeviceGray";
1496
3.42k
                    break;
1497
0
                case 18:
1498
0
                    color_str = (char *)"DeviceRGB";
1499
0
                    break;
1500
0
                case 20:
1501
0
                case 24:
1502
0
                    color_str = (char *)"esRGBICC";
1503
0
                    break;
1504
0
                case 21:
1505
0
                    color_str = (char *)"rommRGBICC";
1506
0
                    break;
1507
2.08k
                default:
1508
2.08k
                    {
1509
2.08k
                        char extra_info[gp_file_name_sizeof];
1510
                        /* TODO: Could try DeviceRGB instead of erroring out? */
1511
2.08k
                        gs_snprintf(extra_info, sizeof(extra_info), "**** Error: JPXDecode: Unsupported EnumCS %d\n", jpx_info->cs_enum);
1512
2.08k
                        pdfi_set_error(ctx, 0, NULL, E_PDF_IMAGECOLOR_ERROR, "pdfi_image_get_color", extra_info);
1513
2.08k
                        code = gs_note_error(gs_error_rangecheck);
1514
2.08k
                        goto cleanupExit;
1515
0
                    }
1516
5.95k
                }
1517
1518
                /* Make a ColorSpace for the name */
1519
3.87k
                if (color_str != NULL) {
1520
3.87k
                    code = pdfi_name_alloc(ctx, (byte *)color_str, strlen(color_str), &ColorSpace);
1521
3.87k
                    if (code < 0)
1522
0
                        goto cleanupExit;
1523
3.87k
                    pdfi_countup(ColorSpace);
1524
3.87k
                    using_enum_cs = true;
1525
3.87k
                }
1526
3.87k
            }
1527
5.95k
        } else {
1528
            /* Assume DeviceRGB colorspace */
1529
20
            if ((code = pdfi_set_warning_stop(ctx, gs_note_error(gs_error_undefined), NULL, W_PDF_BAD_IMAGEDICT, "pdfi_image_get_color", (char *)"**** Error: image has no /ColorSpace key; assuming /DeviceRGB")) < 0)
1530
0
                goto cleanupExit;
1531
20
            code = pdfi_name_alloc(ctx, (byte *)"DeviceRGB", strlen("DeviceRGB"), &ColorSpace);
1532
20
            if (code < 0)
1533
0
                goto cleanupExit;
1534
20
            pdfi_countup(ColorSpace);
1535
20
        }
1536
79.7k
    } else {
1537
        /* Override BPC from JPXDecode if applicable
1538
         * Sample: tests_private/comparefiles/Bug695387.pdf
1539
         */
1540
79.7k
        if (image_info->is_JPXDecode && jpx_info->is_valid)
1541
4.10k
            image_info->BPC = jpx_info->bpc;
1542
79.7k
    }
1543
1544
    /* At this point ColorSpace is either a string we just made, or the one from the Image */
1545
83.6k
    code = pdfi_create_colorspace(ctx, ColorSpace,
1546
83.6k
                                  image_info->stream_dict, image_info->page_dict,
1547
83.6k
                                  pcs, image_info->inline_image);
1548
83.6k
    if (code < 0) {
1549
2.51k
        dbgprintf("WARNING: Image has unsupported ColorSpace ");
1550
2.51k
        if (pdfi_type_of(ColorSpace) == PDF_NAME) {
1551
544
            pdf_name *name = (pdf_name *)ColorSpace;
1552
544
            char str[100];
1553
544
            int length = name->length;
1554
1555
544
            if (length > 0) {
1556
534
                if (length > 99)
1557
9
                    length = 99;
1558
1559
534
                memcpy(str, (const char *)name->data, length);
1560
534
                str[length] = '\0';
1561
534
                dbgprintf1("NAME:%s\n", str);
1562
534
            }
1563
1.96k
        } else {
1564
1.96k
            dbgmprintf(ctx->memory, "(not a name)\n");
1565
1.96k
        }
1566
1567
        /* If we were trying an enum_cs, attempt to use backup_color_name instead */
1568
2.51k
        if (using_enum_cs) {
1569
0
            pdfi_countdown(ColorSpace);
1570
0
            code = pdfi_name_alloc(ctx, (byte *)backup_color_name, strlen(backup_color_name), &ColorSpace);
1571
0
            if (code < 0)
1572
0
                goto cleanupExit;
1573
0
            pdfi_countup(ColorSpace);
1574
            /* Try to set the backup name */
1575
0
            code = pdfi_create_colorspace(ctx, ColorSpace,
1576
0
                                          image_info->stream_dict, image_info->page_dict,
1577
0
                                          pcs, image_info->inline_image);
1578
1579
0
            if (code < 0) {
1580
0
                pdfi_set_error(ctx, 0, NULL, E_PDF_IMAGECOLOR_ERROR, "pdfi_image_get_color", NULL);
1581
0
                goto cleanupExit;
1582
0
            }
1583
2.51k
        } else {
1584
2.51k
            pdfi_set_error(ctx, 0, NULL, E_PDF_IMAGECOLOR_ERROR, "pdfi_image_get_color", NULL);
1585
2.51k
            goto cleanupExit;
1586
2.51k
        }
1587
2.51k
    }
1588
81.0k
    *comps = gs_color_space_num_components(*pcs);
1589
1590
85.6k
 cleanupExit:
1591
85.6k
    pdfi_countdown(ColorSpace);
1592
85.6k
    return code;
1593
81.0k
}
1594
1595
/* Make a fake SMask dict from a JPX SMaskInData */
1596
static int
1597
pdfi_make_smask_dict(pdf_context *ctx, pdf_stream *image_stream, pdfi_image_info_t *image_info,
1598
                     int comps)
1599
0
{
1600
0
    int code = 0;
1601
0
    pdf_dict *smask_dict = NULL;
1602
0
    pdf_stream *fake_smask = NULL;
1603
0
    pdf_array *array = NULL;
1604
0
    pdf_array *matte = NULL;
1605
0
    pdf_dict *image_dict = NULL, *dict = NULL; /* alias */
1606
1607
0
    if (image_info->SMask != NULL) {
1608
0
        code = pdfi_set_error_stop(ctx, code, NULL, E_PDF_SMASK_IN_SMASK, "pdfi_make_smask_dict", NULL);
1609
0
        goto exit;
1610
0
    }
1611
1612
0
    if (pdfi_type_of(image_stream) != PDF_STREAM) {
1613
0
        code = gs_note_error(gs_error_typecheck);
1614
0
        goto exit;
1615
0
    }
1616
0
    code = pdfi_dict_from_obj(ctx, (pdf_obj *)image_stream, &image_dict);
1617
0
    if (code < 0) goto exit;
1618
1619
    /* Make a new stream object and a dict for it */
1620
0
    code = pdfi_object_alloc(ctx, PDF_STREAM, 0, (pdf_obj **)&fake_smask);
1621
0
    if (code < 0) goto exit;
1622
0
    pdfi_countup(fake_smask);
1623
1624
0
    code = pdfi_dict_alloc(ctx, 32, &smask_dict);
1625
0
    if (code < 0) goto exit;
1626
1627
0
    fake_smask->stream_dict = smask_dict;
1628
0
    pdfi_countup(smask_dict);
1629
0
    smask_dict = NULL;
1630
0
    dict = fake_smask->stream_dict; /* alias */
1631
1632
    /* Copy everything from the image_dict */
1633
0
    code = pdfi_dict_copy(ctx, dict, image_dict);
1634
0
    fake_smask->stream_offset = image_stream->stream_offset;
1635
1636
0
    code = pdfi_dict_put_int(ctx, dict, "SMaskInData", 0);
1637
0
    if (code < 0) goto exit;
1638
1639
0
    code = pdfi_dict_put_name(ctx, dict, "ColorSpace", "DeviceGray");
1640
0
    if (code < 0) goto exit;
1641
1642
    /* BPC needs to come from the jpxinfo */
1643
0
    code = pdfi_dict_put_int(ctx, dict, "BitsPerComponent", image_info->jpx_info.bpc);
1644
0
    if (code < 0) goto exit;
1645
1646
    /* "Alpha" is a non-standard thing that gs code uses to tell
1647
     * the jpxfilter that it is doing an SMask.  I guess we can do
1648
     * the same, since we're making this dictionary anyway.
1649
     */
1650
0
    code = pdfi_dict_put_bool(ctx, dict, "Alpha", true);
1651
0
    if (code < 0) goto exit;
1652
1653
    /* Make an array [0,1] */
1654
0
    code = pdfi_array_alloc(ctx, 2, &array);
1655
0
    if (code < 0) goto exit;
1656
0
    pdfi_countup(array);
1657
0
    code = pdfi_array_put_int(ctx, array, 0, 0);
1658
0
    if (code < 0) goto exit;
1659
0
    code = pdfi_array_put_int(ctx, array, 1, 1);
1660
0
    if (code < 0) goto exit;
1661
0
    code = pdfi_dict_put(ctx, dict, "Decode", (pdf_obj *)array);
1662
0
    if (code < 0) goto exit;
1663
1664
    /* Make Matte array if needed */
1665
    /* This just makes an array [0,0,0...] of size 'comps'
1666
     * See pdf_draw.ps/makeimagekeys
1667
     * TODO: The only sample in our test suite that triggers this path is fts_17_1718.pdf
1668
     * and this code being there or not makes no difference on that sample, so.. ???
1669
     */
1670
0
    if (image_info->SMaskInData == 2) {
1671
0
        int i;
1672
0
        code = pdfi_array_alloc(ctx, comps, &matte);
1673
0
        if (code < 0) goto exit;
1674
0
        pdfi_countup(matte);
1675
0
        for (i=0; i<comps; i++) {
1676
0
            code = pdfi_array_put_int(ctx, matte, i, 0);
1677
0
            if (code < 0) goto exit;
1678
0
        }
1679
0
        code = pdfi_dict_put(ctx, dict, "Matte", (pdf_obj *)matte);
1680
0
        if (code < 0) goto exit;
1681
0
    }
1682
1683
0
    image_info->SMask = (pdf_obj *)fake_smask;
1684
1685
0
 exit:
1686
0
    if (code < 0) {
1687
0
        pdfi_countdown(fake_smask);
1688
0
        pdfi_countdown(smask_dict);
1689
0
    }
1690
0
    pdfi_countdown(array);
1691
0
    pdfi_countdown(matte);
1692
0
    return code;
1693
0
}
1694
1695
/* NOTE: "source" is the current input stream.
1696
 * on exit:
1697
 *  inline_image = TRUE, stream it will point to after the image data.
1698
 *  inline_image = FALSE, stream position undefined.
1699
 */
1700
static int
1701
pdfi_do_image(pdf_context *ctx, pdf_dict *page_dict, pdf_dict *stream_dict, pdf_stream *image_stream,
1702
              pdf_c_stream *source, bool inline_image)
1703
299k
{
1704
299k
    pdf_c_stream *new_stream = NULL, *SFD_stream = NULL;
1705
299k
    int code = 0, code1 = 0;
1706
299k
    int comps = 0;
1707
299k
    gs_color_space  *pcs = NULL;
1708
299k
    gs_image1_t t1image;
1709
299k
    gs_image4_t t4image;
1710
299k
    gs_image3_t t3image;
1711
299k
    gs_image3x_t t3ximage;
1712
299k
    gs_pixel_image_t *pim = NULL;
1713
299k
    pdf_stream *alt_stream = NULL;
1714
299k
    pdfi_image_info_t image_info, mask_info, smask_info;
1715
299k
    pdf_stream *mask_stream = NULL;
1716
299k
    pdf_stream *smask_stream = NULL; /* only non-null for imagetype 3x (PreserveSMask) */
1717
299k
    pdf_array *mask_array = NULL;
1718
299k
    unsigned char *mask_buffer = NULL;
1719
299k
    uint64_t mask_size = 0;
1720
299k
    pdfi_int_gstate *igs = (pdfi_int_gstate *)ctx->pgs->client_data;
1721
299k
    bool transparency_group = false;
1722
299k
    bool need_smask_cleanup = false;
1723
299k
    bool maybe_jpxdecode = false;
1724
299k
    pdfi_trans_state_t trans_state;
1725
299k
    gs_offset_t stream_offset;
1726
299k
    int trans_required;
1727
1728
#if DEBUG_IMAGES
1729
    dbgmprintf(ctx->memory, "pdfi_do_image BEGIN\n");
1730
#endif
1731
299k
    memset(&mask_info, 0, sizeof(mask_info));
1732
299k
    memset(&smask_info, 0, sizeof(mask_info));
1733
1734
    /* Make sure the image is a stream (which we will assume in later code) */
1735
299k
    if (pdfi_type_of(image_stream) != PDF_STREAM)
1736
0
        return_error(gs_error_typecheck);
1737
1738
299k
    if (!inline_image) {
1739
91.0k
        pdf_dict *image_dict = NULL;
1740
1741
        /* If we are not processing an inline image, check to see if any of the abbreviated
1742
         * keys are present in the image dictionary. If they are, and we need to abort, we'll
1743
         * get an error return, otherwise we can continue.
1744
         */
1745
91.0k
        code = pdfi_dict_from_obj(ctx, (pdf_obj *)image_stream, &image_dict);
1746
91.0k
        if (code < 0)
1747
0
            return code;
1748
1749
91.0k
        code = pdfi_check_inline_image_keys(ctx, image_dict);
1750
91.0k
        if (code < 0)
1751
0
            return code;
1752
91.0k
    }
1753
1754
    /* We want to gsave in here so that any changes made by the rendering
1755
     * don't affect the wider world. This is particularly important if we
1756
     * have an SMask here, because that RELIES on this gsave/grestore
1757
     * level being here. Because we want to handle SMask changes we need
1758
     * to push/pop the transparency state changes too. The easiest way to
1759
     * do this is to call 'q' and 'Q'. */
1760
299k
    code = pdfi_op_q(ctx);
1761
299k
    if (code < 0)
1762
0
        return code;
1763
1764
299k
    code = pdfi_get_image_info(ctx, image_stream, page_dict, stream_dict, inline_image, &image_info);
1765
299k
    if (code < 0)
1766
1.79k
        goto cleanupExit;
1767
1768
    /* Don't render this if turned off */
1769
297k
    if (pdfi_oc_is_off(ctx))
1770
6.48k
        goto cleanupExit;
1771
    /* If there is an OC dictionary, see if we even need to render this */
1772
291k
    if (image_info.OC) {
1773
42
        if (!(ctx->device_state.writepdfmarks && ctx->device_state.WantsOptionalContent)) {
1774
42
            if (!pdfi_oc_is_ocg_visible(ctx, image_info.OC))
1775
0
                goto cleanupExit;
1776
42
        }
1777
42
    }
1778
1779
    /* If there is an alternate, swap it in */
1780
    /* If image_info.Alternates, look in the array, see if any of them are flagged as "DefaultForPrinting"
1781
     * and if so, substitute that one for the image we are processing.
1782
     * (it can probably be either an array, or a reference to an array, need an example to test/implement)
1783
     * see p.274 of PDFReference.pdf
1784
     */
1785
1786
291k
    if (image_info.Alternates != NULL) {
1787
0
        alt_stream = pdfi_find_alternate(ctx, image_info.Alternates);
1788
0
        if (alt_stream != NULL) {
1789
0
            image_stream = alt_stream;
1790
0
            pdfi_free_image_info_components(&image_info);
1791
0
            code = pdfi_get_image_info(ctx, image_stream, page_dict, stream_dict, inline_image, &image_info);
1792
0
            if (code < 0)
1793
0
                goto cleanupExit;
1794
0
        }
1795
0
    }
1796
1797
    /* Grab stream_offset after alternate has (possibly) set */
1798
291k
    stream_offset = pdfi_stream_offset(ctx, image_stream);
1799
1800
    /* See if it might be a JPXDecode image even though not in the header */
1801
291k
    if (image_info.ColorSpace == NULL && !image_info.ImageMask)
1802
5.97k
        maybe_jpxdecode = true;
1803
1804
    /* Handle JPXDecode filter pre-scan of header */
1805
291k
    if ((maybe_jpxdecode || image_info.is_JPXDecode) && !inline_image) {
1806
10.1k
        pdfi_seek(ctx, source, stream_offset, SEEK_SET);
1807
10.1k
        code = pdfi_scan_jpxfilter(ctx, source, image_info.Length, &image_info.jpx_info);
1808
10.1k
        if (code < 0 && image_info.is_JPXDecode)
1809
0
            goto cleanupExit;
1810
1811
        /* I saw this JPXDecode images that have SMaskInData */
1812
10.1k
        if (image_info.jpx_info.no_data)
1813
517
            image_info.is_JPXDecode = false;
1814
1815
10.1k
        if (code == 0 && maybe_jpxdecode)
1816
5.95k
            image_info.is_JPXDecode = true;
1817
10.1k
    }
1818
1819
    /* Set the rendering intent if applicable */
1820
291k
    if (image_info.Intent) {
1821
6.96k
        code = pdfi_setrenderingintent(ctx, image_info.Intent);
1822
6.96k
        if (code < 0) {
1823
            /* TODO: Flag a warning on this?  Sample fts_17_1706.pdf has misspelled Intent
1824
               which gs renders without flagging an error */
1825
#if DEBUG_IMAGES
1826
            dbgmprintf(ctx->memory, "WARNING: Image with unexpected Intent\n");
1827
#endif
1828
0
        }
1829
6.96k
    }
1830
1831
    /* Get the color for this image */
1832
291k
    code = pdfi_image_get_color(ctx, source, &image_info, &comps, image_stream->object_num, &pcs);
1833
291k
    if (code < 0)
1834
4.59k
        goto cleanupExit;
1835
1836
286k
    if (image_info.BPC != 1 && image_info.BPC != 2 && image_info.BPC != 4 && image_info.BPC != 8 && image_info.BPC != 16) {
1837
3
        code = gs_note_error(gs_error_rangecheck);
1838
3
        goto cleanupExit;
1839
3
    }
1840
1841
    /* Set the colorspace */
1842
286k
    if (pcs) {
1843
81.0k
        gs_color_space  *pcs1 = pcs;
1844
1845
81.0k
        code = pdfi_gs_setcolorspace(ctx, pcs);
1846
81.0k
        if (code < 0)
1847
0
            goto cleanupExit;
1848
1849
81.0k
        if (pcs->type->index == gs_color_space_index_Indexed)
1850
9.07k
            pcs1 = pcs->base_space;
1851
1852
        /* It is possible that we get no error returned from setting an
1853
         * ICC space, but that we are not able when rendering to create a link
1854
         * between the ICC space and the output device profile.
1855
         * The PostScript PDF interpreter sets the colour after setting the space, which
1856
         * (eventually) causes us to set the device colour, and that actually creates the
1857
         * link. This is apparntly the only way we can detect this error. Otherwise we
1858
         * would carry on until we tried to render the image, and that would fail with
1859
         * a not terribly useful error of -1. So here we try to set the device colour,
1860
         * for images in an ICC profile space. If that fails then we try to manufacture
1861
         * a Device space from the number of components in the profile.
1862
         * I do feel this is something we should be able to handle better!
1863
         */
1864
81.0k
        if (pcs1->type->index == gs_color_space_index_ICC)
1865
80.8k
        {
1866
80.8k
            gs_client_color         cc;
1867
80.8k
            int comp = 0;
1868
80.8k
            pdf_obj *ColorSpace = NULL;
1869
1870
80.8k
            cc.pattern = 0;
1871
268k
            for (comp = 0; comp < pcs1->cmm_icc_profile_data->num_comps;comp++)
1872
187k
                cc.paint.values[comp] = 0;
1873
1874
80.8k
            code = gs_setcolor(ctx->pgs, &cc);
1875
80.8k
            if (code < 0)
1876
0
                goto cleanupExit;
1877
1878
80.8k
            code = gx_set_dev_color(ctx->pgs);
1879
80.8k
            if (code < 0) {
1880
1.90k
                if ((code = pdfi_set_warning_stop(ctx, code, NULL, W_PDF_BAD_ICC_PROFILE_LINK, "pdfi_do_image", "Attempting to use profile /N to create a device colour space")) < 0)
1881
0
                    goto cleanupExit;
1882
1883
                /* Possibly we couldn't create a link profile, soemthing wrong with the ICC profile, try to use a device space */
1884
1.90k
                switch(pcs1->cmm_icc_profile_data->num_comps) {
1885
337
                    case 1:
1886
337
                        code = pdfi_name_alloc(ctx, (byte *)"DeviceGray", 10, &ColorSpace);
1887
337
                        if (code < 0)
1888
0
                            goto cleanupExit;
1889
337
                        pdfi_countup(ColorSpace);
1890
337
                        break;
1891
1.57k
                    case 3:
1892
1.57k
                        code = pdfi_name_alloc(ctx, (byte *)"DeviceRGB", 9, &ColorSpace);
1893
1.57k
                        if (code < 0)
1894
0
                            goto cleanupExit;
1895
1.57k
                        pdfi_countup(ColorSpace);
1896
1.57k
                        break;
1897
0
                    case 4:
1898
0
                        code = pdfi_name_alloc(ctx, (byte *)"DeviceCMYK", 10, &ColorSpace);
1899
0
                        if (code < 0)
1900
0
                            goto cleanupExit;
1901
0
                        pdfi_countup(ColorSpace);
1902
0
                        break;
1903
0
                    default:
1904
0
                        code = gs_error_unknownerror;
1905
0
                        goto cleanupExit;
1906
0
                        break;
1907
1.90k
                }
1908
1.90k
                if (pcs != NULL)
1909
1.90k
                    rc_decrement_only_cs(pcs, "pdfi_do_image");
1910
                /* At this point ColorSpace is either a string we just made, or the one from the Image */
1911
1.90k
                code = pdfi_create_colorspace(ctx, ColorSpace,
1912
1.90k
                                  image_info.stream_dict, image_info.page_dict,
1913
1.90k
                                  &pcs, image_info.inline_image);
1914
1.90k
                pdfi_countdown(ColorSpace);
1915
1.90k
                if (code < 0)
1916
0
                    goto cleanupExit;
1917
1918
1.90k
                code = pdfi_gs_setcolorspace(ctx, pcs);
1919
1.90k
                if (code < 0)
1920
0
                    goto cleanupExit;
1921
1922
                /* Try to set the device color again as that failure
1923
                   is why we are here. If it fails again, something
1924
                   is very wrong */
1925
1.90k
                code = gx_set_dev_color(ctx->pgs);
1926
1.90k
                if (code < 0)
1927
65
                    goto cleanupExit;
1928
1.90k
            }
1929
80.8k
        }
1930
81.0k
    }
1931
205k
    else {
1932
205k
        if (image_info.ImageMask == 0) {
1933
0
            code = gs_note_error(gs_error_undefined);
1934
0
            goto cleanupExit;
1935
0
        }
1936
205k
    }
1937
1938
    /* Make a fake SMask dict if needed for JPXDecode */
1939
286k
    if (ctx->page.has_transparency && image_info.is_JPXDecode && image_info.SMaskInData != 0) {
1940
0
        code = pdfi_make_smask_dict(ctx, image_stream, &image_info, comps);
1941
0
        if (code < 0)
1942
0
            goto cleanupExit;
1943
0
    }
1944
1945
286k
    if (ctx->page.has_transparency == true && image_info.SMask != NULL) {
1946
23.5k
        bool has_Matte = false;
1947
1948
        /* If this flag is set, then device will process the SMask and we need do nothing
1949
         * here (e.g. pdfwrite).
1950
         */
1951
23.5k
        if (!ctx->device_state.preserve_smask) {
1952
19.5k
            code = pdfi_do_image_smask(ctx, source, &image_info, &has_Matte);
1953
19.5k
            if (code < 0)
1954
0
                goto cleanupExit;
1955
19.5k
            need_smask_cleanup = true;
1956
19.5k
        }
1957
1958
        /* If we are in an overprint situation this group will need
1959
           to have its blend mode set to compatible overprint. */
1960
23.5k
        if (ctx->page.needs_OP) {
1961
3.04k
            if (pdfi_trans_okOPcs(ctx)) {
1962
23
                if (gs_currentfilloverprint(ctx->pgs)) {
1963
0
                    code = gs_setblendmode(ctx->pgs, BLEND_MODE_CompatibleOverprint);
1964
0
                    if (code < 0)
1965
0
                        goto cleanupExit;
1966
0
                }
1967
23
            }
1968
3.04k
        }
1969
1970
23.5k
        if (has_Matte)
1971
25
            code = pdfi_trans_begin_isolated_group(ctx, true, pcs);
1972
23.4k
        else
1973
23.4k
            code = pdfi_trans_begin_isolated_group(ctx, true, NULL);
1974
23.5k
        if (code < 0)
1975
0
            goto cleanupExit;
1976
23.5k
        transparency_group = true;
1977
262k
    } else if (igs->SMask) {
1978
77
        code = pdfi_trans_begin_isolated_group(ctx, false, NULL);
1979
77
        if (code < 0)
1980
0
            goto cleanupExit;
1981
77
        transparency_group = true;
1982
77
    }
1983
1984
286k
    if (transparency_group && !ctx->device_state.preserve_smask) {
1985
19.5k
        gs_setstrokeconstantalpha(ctx->pgs, 1.0);
1986
19.5k
        gs_setfillconstantalpha(ctx->pgs, 1.0);
1987
19.5k
    }
1988
1989
    /* Get the Mask data either as an array or a dict, if present */
1990
286k
    if (image_info.Mask != NULL) {
1991
706
        switch (pdfi_type_of(image_info.Mask)) {
1992
157
            case PDF_ARRAY:
1993
157
                mask_array = (pdf_array *)image_info.Mask;
1994
157
                break;
1995
549
            case PDF_STREAM:
1996
549
                mask_stream = (pdf_stream *)image_info.Mask;
1997
549
                code = pdfi_get_image_info(ctx, mask_stream, page_dict,
1998
549
                                           stream_dict, inline_image, &mask_info);
1999
549
                if (code < 0)
2000
96
                    goto cleanupExit;
2001
453
                break;
2002
453
            default:
2003
0
                pdfi_countdown(image_info.Mask);
2004
0
                image_info.Mask = NULL;
2005
0
                if ((code = pdfi_set_warning_stop(ctx, gs_note_error(gs_error_typecheck), NULL, W_PDF_MASK_ERROR, "pdfi_do_image", NULL)) < 0)
2006
0
                    goto cleanupExit;
2007
706
        }
2008
706
    }
2009
2010
    /* Get the SMask info if we will need it (Type 3x images) */
2011
286k
    if (image_info.SMask && pdfi_type_of(image_info.SMask) == PDF_STREAM && ctx->device_state.preserve_smask) {
2012
        /* smask_dict non-NULL is used to flag a Type 3x image below */
2013
4.05k
        smask_stream = (pdf_stream *)image_info.SMask;
2014
4.05k
        code = pdfi_get_image_info(ctx, smask_stream, page_dict, stream_dict,
2015
4.05k
                                   inline_image, &smask_info);
2016
4.05k
        if (code < 0)
2017
1
            goto cleanupExit;
2018
4.05k
    }
2019
2020
    /* Get the image into a supported gs type (type1, type3, type4, type3x) */
2021
286k
    if (!image_info.Mask && !smask_stream) { /* Type 1 and ImageMask */
2022
281k
        memset(&t1image, 0, sizeof(t1image));
2023
281k
        pim = (gs_pixel_image_t *)&t1image;
2024
2025
281k
        if (image_info.ImageMask) {
2026
            /* Sets up timage.ImageMask, amongst other things */
2027
205k
            gs_image_t_init_adjust(&t1image, NULL, false);
2028
205k
        } else {
2029
76.2k
            gs_image_t_init_adjust(&t1image, pcs, true);
2030
76.2k
        }
2031
281k
    } else if (smask_stream) { /* Type 3x */
2032
        /* In the event where we have both /SMask and /Mask, favour /SMask
2033
           See tests_private/pdf/sumatra/1901_-_tiling_inconsistencies.pdf
2034
         */
2035
4.05k
        mask_stream = NULL;
2036
4.05k
        code = pdfi_image_setup_type3x(ctx, &image_info, &t3ximage, &smask_info, comps);
2037
4.05k
        if (code < 0) {
2038
0
            if ((code = pdfi_set_error_stop(ctx, gs_note_error(code), NULL, E_PDF_INVALID_MATTE, "pdfi_do_image", "")) < 0)
2039
0
                goto cleanupExitError;
2040
            /* If this got an error, setup as a Type 1 image */
2041
            /* NOTE: I did this error-handling the same as for Type 4 image below.
2042
             * Dunno if it's better to do this or to just abort the whole image?
2043
             */
2044
0
            memset(&t1image, 0, sizeof(t1image));
2045
0
            pim = (gs_pixel_image_t *)&t1image;
2046
0
            gs_image_t_init_adjust(&t1image, pcs, true);
2047
0
            smask_stream = mask_stream = NULL;
2048
4.05k
        } else {
2049
4.05k
            pim = (gs_pixel_image_t *)&t3ximage;
2050
4.05k
        }
2051
4.05k
    } else {
2052
610
        if (mask_array) { /* Type 4 */
2053
157
            code = pdfi_image_setup_type4(ctx, &image_info, &t4image, mask_array, pcs);
2054
157
            if (code < 0) {
2055
7
                 if ((code = pdfi_set_warning_stop(ctx, gs_note_error(gs_error_typecheck), NULL, W_PDF_IMAGE_ERROR, "pdfi_do_image", "")) < 0) {
2056
0
                     goto cleanupExit;
2057
0
                 }
2058
                /* If this got an error, setup as a Type 1 image */
2059
7
                memset(&t1image, 0, sizeof(t1image));
2060
7
                pim = (gs_pixel_image_t *)&t1image;
2061
7
                gs_image_t_init_adjust(&t1image, pcs, true);
2062
150
            } else {
2063
150
                pim = (gs_pixel_image_t *)&t4image;
2064
150
            }
2065
453
        } else { /* Type 3 */
2066
453
            memset(&t3image, 0, sizeof(t3image));
2067
453
            pim = (gs_pixel_image_t *)&t3image;
2068
453
            gs_image3_t_init(&t3image, NULL, interleave_separate_source);
2069
453
            code = pdfi_data_image_params(ctx, &mask_info, &t3image.MaskDict, 1, NULL);
2070
453
            if (code < 0)
2071
0
                goto cleanupExit;
2072
453
        }
2073
610
    }
2074
2075
2076
    /* At this point pim points to a structure containing the specific type
2077
     * of image, and then we can handle it generically from here.
2078
     * The underlying gs image functions will do different things for different
2079
     * types of images.
2080
     */
2081
2082
    /* Setup the common params */
2083
286k
    pim->ColorSpace = pcs;
2084
286k
    code = pdfi_data_image_params(ctx, &image_info, (gs_data_image_t *)pim, comps, pcs);
2085
286k
    if (code < 0)
2086
9
        goto cleanupExit;
2087
2088
    /* Grab the mask_image data buffer in advance.
2089
     * Doing it this way because I don't want to muck with reading from
2090
     * two streams simultaneously -- not even sure that is feasible?
2091
     */
2092
286k
    if (smask_stream) {
2093
4.05k
        mask_size = ((((smask_info.Width * smask_info.BPC) + 7) / 8) * smask_info.Height);
2094
        /* This will happen only in case of PreserveSMask (Type 3x) */
2095
4.05k
        code = pdfi_stream_to_buffer(ctx, smask_stream, &mask_buffer, (int64_t *)&mask_size);
2096
4.05k
        if (code < 0)
2097
64
            goto cleanupExit;
2098
282k
    } else if (mask_stream) {
2099
        /* Calculate expected mask size */
2100
453
        mask_size = ((((t3image.MaskDict.BitsPerComponent * (int64_t)t3image.MaskDict.Width) + 7) / 8) * (int64_t)t3image.MaskDict.Height);
2101
453
        code = pdfi_stream_to_buffer(ctx, mask_stream, &mask_buffer, (int64_t *)&mask_size);
2102
453
        if (code < 0)
2103
17
            goto cleanupExit;
2104
453
    }
2105
    /* Setup the data stream for the image data */
2106
286k
    if (!inline_image) {
2107
78.9k
        pdfi_seek(ctx, source, stream_offset, SEEK_SET);
2108
2109
78.9k
        code = pdfi_apply_SubFileDecode_filter(ctx, 0, "endstream", source, &SFD_stream, false);
2110
78.9k
        if (code < 0)
2111
0
            goto cleanupExit;
2112
78.9k
        source = SFD_stream;
2113
78.9k
    }
2114
2115
286k
    code = pdfi_filter(ctx, image_stream, source, &new_stream, inline_image);
2116
286k
    if (code < 0)
2117
1.73k
        goto cleanupExit;
2118
2119
    /* This duplicates the code in gs_img.ps; if we have an imagemask, with 1 bit per component (is there any other kind ?)
2120
     * and the image is to be interpolated, and we are nto sending it to a high level device. Then check the scaling.
2121
     * If we are scaling up (in device space) by afactor of more than 2, then we install the ImScaleDecode filter,
2122
     * which interpolates the input data by a factor of 4.
2123
     * The scaling of 2 is arbitrary (says so in gs_img.ps) but we use it for consistency. The scaling of the input
2124
     * by 4 is just a magic number, the scaling is always by 4, and we need to know it so we can adjust the Image Matrix
2125
     * and Width and Height values.
2126
     */
2127
284k
    if (image_info.ImageMask == 1 && image_info.BPC == 1 && image_info.Interpolate == 1 && !ctx->device_state.HighLevelDevice)
2128
0
    {
2129
0
        pdf_c_stream *s = new_stream;
2130
0
        gs_matrix mat4 = {4, 0, 0, 4, 0, 0}, inverseIM;
2131
0
        gs_point pt, pt1;
2132
0
        float s1, s2;
2133
2134
0
        code = gs_matrix_invert(&pim->ImageMatrix, &inverseIM);
2135
0
        if (code < 0)
2136
0
            goto cleanupExit;
2137
2138
0
        code = gs_distance_transform(0, 1, &inverseIM, &pt);
2139
0
        if (code < 0)
2140
0
            goto cleanupExit;
2141
2142
0
        code = gs_distance_transform(pt.x, pt.y, &ctm_only(ctx->pgs), &pt1);
2143
0
        if (code < 0)
2144
0
            goto cleanupExit;
2145
2146
0
        s1 = sqrt(pt1.x * pt1.x + pt1.y * pt1.y);
2147
2148
0
        code = gs_distance_transform(1, 0, &inverseIM, &pt);
2149
0
        if (code < 0)
2150
0
            goto cleanupExit;
2151
2152
0
        code = gs_distance_transform(pt.x, pt.y, &ctm_only(ctx->pgs), &pt1);
2153
0
        if (code < 0)
2154
0
            goto cleanupExit;
2155
2156
0
        s2 = sqrt(pt1.x * pt1.x + pt1.y * pt1.y);
2157
2158
0
        if (s1 > 2.0 || s2 > 2.0) {
2159
0
            code = pdfi_apply_imscale_filter(ctx, 0, image_info.Width, image_info.Height, s, &new_stream);
2160
0
            if (code < 0)
2161
0
                goto cleanupExit;
2162
            /* This adds the filter to the 'chain' of filter we created. When we close this filter
2163
             * it closes all the filters in the chain, back to either the SubFileDecode filter or the
2164
             * original main stream. If we don't patch this up then we leak memory for any filters
2165
             * applied in pdfi_filter above.
2166
             */
2167
0
            new_stream->original = s->original;
2168
2169
            /* We'e created a new 'new_stream', which is a C stream, to hold the filter chain
2170
             * but we still need to free the original C stream 'wrapper' we created with pdfi_filter()
2171
             * Do that now.
2172
             */
2173
0
            gs_free_object(ctx->memory, s, "free stream replaced by adding image scaling filter");
2174
0
            image_info.Width *= 4;
2175
0
            image_info.Height *= 4;
2176
0
            pim->Width *= 4;
2177
0
            pim->Height *= 4;
2178
0
            code = gs_matrix_multiply(&pim->ImageMatrix, &mat4, &pim->ImageMatrix);
2179
0
            if (code < 0)
2180
0
                goto cleanupExit;
2181
0
        }
2182
0
    }
2183
2184
284k
    trans_required = pdfi_trans_required(ctx);
2185
2186
284k
    if (trans_required) {
2187
5.69k
        code = pdfi_image_setup_trans(ctx, &trans_state);
2188
5.69k
        if (code < 0)
2189
452
            goto cleanupExit;
2190
5.69k
    }
2191
2192
    /* Render the image */
2193
284k
    code = pdfi_render_image(ctx, pim, new_stream,
2194
284k
                             mask_buffer, mask_size,
2195
284k
                             comps, image_info.ImageMask);
2196
284k
    if (code < 0) {
2197
26.9k
        if (ctx->args.pdfdebug)
2198
0
            outprintf(ctx->memory, "WARNING: pdfi_do_image: error %d from pdfi_render_image\n", code);
2199
26.9k
    }
2200
2201
284k
    if (trans_required) {
2202
5.24k
        code1 = pdfi_trans_teardown(ctx, &trans_state);
2203
5.24k
        if (code == 0)
2204
580
            code = code1;
2205
5.24k
    }
2206
2207
299k
 cleanupExit:
2208
299k
    if (code < 0)
2209
35.7k
        code = pdfi_set_warning_stop(ctx, code, NULL, W_PDF_IMAGE_ERROR, "pdfi_do_image", NULL);
2210
2211
299k
 cleanupExitError:
2212
299k
    if (transparency_group) {
2213
23.5k
        pdfi_trans_end_isolated_group(ctx);
2214
23.5k
        if (need_smask_cleanup)
2215
19.5k
            pdfi_trans_end_smask_notify(ctx);
2216
23.5k
    }
2217
2218
    /* See note above on the pdfi_op_q call. This does a grestore, and
2219
     * pops the transparency state. */
2220
299k
    (void)pdfi_op_Q(ctx);
2221
2222
299k
    if (new_stream)
2223
284k
        pdfi_close_file(ctx, new_stream);
2224
299k
    if (SFD_stream)
2225
78.9k
        pdfi_close_file(ctx, SFD_stream);
2226
299k
    if (mask_buffer)
2227
4.42k
        gs_free_object(ctx->memory, mask_buffer, "pdfi_do_image (mask_buffer)");
2228
2229
299k
    pdfi_countdown(alt_stream);
2230
2231
299k
    pdfi_free_image_info_components(&image_info);
2232
299k
    pdfi_free_image_info_components(&mask_info);
2233
299k
    pdfi_free_image_info_components(&smask_info);
2234
2235
299k
    if (pcs != NULL)
2236
81.0k
        rc_decrement_only_cs(pcs, "pdfi_do_image");
2237
2238
#if DEBUG_IMAGES
2239
    dbgmprintf(ctx->memory, "pdfi_do_image END\n");
2240
#endif
2241
299k
    return code;
2242
299k
}
2243
2244
int pdfi_ID(pdf_context *ctx, pdf_dict *stream_dict, pdf_dict *page_dict, pdf_c_stream *source)
2245
224k
{
2246
224k
    pdf_dict *d = NULL;
2247
224k
    int code;
2248
224k
    pdf_stream *image_stream;
2249
2250
224k
    if (ctx->text.BlockDepth != 0) {
2251
134
        ctx->text.BlockDepth = 0;
2252
134
        if (ctx->text.TextClip) {
2253
0
            gx_device *dev = gs_currentdevice_inline(ctx->pgs);
2254
2255
0
            ctx->text.TextClip = false;
2256
0
            (void)dev_proc(dev, dev_spec_op)(dev, gxdso_hilevel_text_clip, (void *)0, 1);
2257
0
        }
2258
134
        code = pdfi_set_warning_stop(ctx, gs_note_error(gs_error_syntaxerror), NULL, W_PDF_OPINVALIDINTEXT, "pdfi_ID", NULL);
2259
134
        if (code < 0)
2260
0
            return code;
2261
134
    }
2262
2263
    /* we want to have the indirect_num and indirect_gen of the created dictionary
2264
     * be 0, because we are reading from a stream, and the stream has already
2265
     * been decrypted, we don't need to decrypt any strings contained in the
2266
     * inline dictionary.
2267
     */
2268
224k
    code = pdfi_dict_from_stack(ctx, 0, 0, false);
2269
224k
    if (code < 0)
2270
        /* pdfi_dict_from_stack cleans up the stack so we don't need to in case of an error */
2271
16.6k
        return code;
2272
2273
208k
    d = (pdf_dict *)ctx->stack_top[-1];
2274
208k
    pdfi_countup(d);
2275
208k
    pdfi_pop(ctx, 1);
2276
2277
208k
    code = pdfi_obj_dict_to_stream(ctx, d, &image_stream, true);
2278
208k
    if (code < 0)
2279
0
        goto error;
2280
2281
208k
    code = pdfi_do_image(ctx, page_dict, stream_dict, image_stream, source, true);
2282
208k
error:
2283
208k
    pdfi_countdown(image_stream);
2284
208k
    pdfi_countdown(d);
2285
208k
    return code;
2286
208k
}
2287
2288
int pdfi_EI(pdf_context *ctx)
2289
220k
{
2290
220k
    if (ctx->text.BlockDepth != 0) {
2291
55
        ctx->text.BlockDepth = 0;
2292
55
        if (ctx->text.TextClip) {
2293
0
            gx_device *dev = gs_currentdevice_inline(ctx->pgs);
2294
2295
0
            ctx->text.TextClip = false;
2296
0
            (void)dev_proc(dev, dev_spec_op)(dev, gxdso_hilevel_text_clip, (void *)0, 1);
2297
0
        }
2298
55
        return pdfi_set_warning_stop(ctx, gs_note_error(gs_error_rangecheck), NULL, W_PDF_OPINVALIDINTEXT, "pdfi_EI", NULL);
2299
55
    }
2300
2301
/*    pdfi_clearstack(ctx);*/
2302
220k
    return 0;
2303
220k
}
2304
2305
/* see .execgroup */
2306
int pdfi_form_execgroup(pdf_context *ctx, pdf_dict *page_dict, pdf_stream *xobject_obj,
2307
                        gs_gstate *GroupGState, gs_color_space *pcs, gs_client_color *pcc, gs_matrix *matrix)
2308
6.68k
{
2309
6.68k
    int code;
2310
6.68k
    pdfi_int_gstate *igs = (pdfi_int_gstate *)ctx->pgs->client_data;
2311
2312
6.68k
    code = pdfi_gsave(ctx);
2313
6.68k
    if (code < 0)
2314
0
        goto exit;
2315
2316
6.68k
    if (GroupGState) {
2317
1.20k
        code = pdfi_gs_setgstate(ctx->pgs, GroupGState);
2318
1.20k
        if (code < 0)
2319
0
            goto exit2;
2320
1.20k
    }
2321
2322
    /* Override the colorspace if specified */
2323
6.68k
    if (pcs) {
2324
5.48k
        code = pdfi_gs_setcolorspace(ctx, pcs);
2325
5.48k
        if (code < 0)
2326
0
            goto exit2;
2327
5.48k
        code = gs_setcolor(ctx->pgs, (const gs_client_color *)pcc);
2328
5.48k
        if (code < 0)
2329
0
            goto exit2;
2330
5.48k
    }
2331
2332
    /* Disable the SMask */
2333
6.68k
    pdfi_gstate_smask_free(igs);
2334
2335
6.68k
    gs_setblendmode(ctx->pgs, BLEND_MODE_Compatible);
2336
6.68k
    gs_setstrokeconstantalpha(ctx->pgs, 1.0);
2337
6.68k
    gs_setfillconstantalpha(ctx->pgs, 1.0);
2338
2339
6.68k
    if (matrix)
2340
1.20k
        code = gs_concat(ctx->pgs, matrix);
2341
6.68k
    if (code < 0) {
2342
0
        goto exit2;
2343
0
    }
2344
6.68k
    code = pdfi_run_context(ctx, xobject_obj, page_dict, false, "FORM");
2345
2346
6.68k
 exit2:
2347
6.68k
    if (code != 0)
2348
0
        (void)pdfi_grestore(ctx);
2349
6.68k
    else
2350
6.68k
        code = pdfi_grestore(ctx);
2351
6.68k
 exit:
2352
6.68k
    return code;
2353
6.68k
}
2354
2355
/* See zbeginform() */
2356
static int pdfi_form_highlevel_begin(pdf_context *ctx, pdf_dict *form_dict, gs_matrix *CTM,
2357
                                     gs_rect *BBox, gs_matrix *form_matrix)
2358
1.89k
{
2359
1.89k
    int code = 0;
2360
1.89k
    gx_device *cdev = gs_currentdevice_inline(ctx->pgs);
2361
1.89k
    gs_form_template_t template;
2362
1.89k
    gs_point ll, ur;
2363
1.89k
    gs_fixed_rect box;
2364
2365
1.89k
    memset(&template, 0, sizeof(template));
2366
2367
1.89k
    template.CTM = *CTM; /* (structure copy) */
2368
1.89k
    template.BBox = *BBox; /* (structure copy) */
2369
1.89k
    template.form_matrix = *form_matrix; /* (structure copy) */
2370
1.89k
    template.FormID = -1;
2371
1.89k
    template.pcpath = ctx->pgs->clip_path;
2372
1.89k
    template.pgs = ctx->pgs;
2373
2374
1.89k
    code = dev_proc(cdev, dev_spec_op)(cdev, gxdso_form_begin, &template, 0);
2375
    /* return value > 0 means the device sent us back a matrix
2376
     * and wants the CTM set to that.
2377
     * TODO: No idea if we need this nonsense.  See zbeginform()
2378
     */
2379
1.89k
    if (code > 0)
2380
0
    {
2381
0
        gs_setmatrix(ctx->pgs, &template.CTM);
2382
0
        gs_distance_transform(template.BBox.p.x, template.BBox.p.y, &template.CTM, &ll);
2383
0
        gs_distance_transform(template.BBox.q.x, template.BBox.q.y, &template.CTM, &ur);
2384
2385
        /* A form can legitimately have negative co-ordinates in paths
2386
         * because it can be translated. But we always clip paths to the
2387
         * page which (clearly) can't have negative co-ordinates. NB this
2388
         * wouldn't be a problem if we didn't reset the CTM, but that would
2389
         * break the form capture.
2390
         * So here we temporarily set the clip to permit negative values,
2391
         * fortunately this works.....
2392
         */
2393
        /* We choose to permit negative values of the same magnitude as the
2394
         * positive ones.
2395
         */
2396
2397
0
        box.p.x = float2fixed(ll.x);
2398
0
        box.p.y = float2fixed(ll.y);
2399
0
        box.q.x = float2fixed(ur.x);
2400
0
        box.q.y = float2fixed(ur.y);
2401
2402
0
        if (box.p.x < 0) {
2403
0
            if(box.p.x * -1 > box.q.x)
2404
0
                box.q.x = box.p.x * -1;
2405
0
        } else {
2406
0
            if (fabs(ur.x) > fabs(ll.x))
2407
0
                box.p.x = box.q.x * -1;
2408
0
            else {
2409
0
                box.p.x = float2fixed(ll.x * -1);
2410
0
                box.q.x = float2fixed(ll.x);
2411
0
            }
2412
0
        }
2413
0
        if (box.p.y < 0) {
2414
0
            if(box.p.y * -1 > box.q.y)
2415
0
                box.q.y = box.p.y * -1;
2416
0
        } else {
2417
0
            if (fabs(ur.y) > fabs(ll.y))
2418
0
                box.p.y = box.q.y * -1;
2419
0
            else {
2420
0
                box.p.y = float2fixed(ll.y * -1);
2421
0
                box.q.y = float2fixed(ll.y);
2422
0
            }
2423
0
        }
2424
        /* This gets undone when we grestore after the form is executed */
2425
0
        code = gx_clip_to_rectangle(ctx->pgs, &box);
2426
0
    }
2427
2428
1.89k
    return code;
2429
1.89k
}
2430
2431
/* See zendform() */
2432
static int pdfi_form_highlevel_end(pdf_context *ctx)
2433
1.89k
{
2434
1.89k
    int code = 0;
2435
1.89k
    gx_device *cdev = gs_currentdevice_inline(ctx->pgs);
2436
2437
1.89k
    code = dev_proc(cdev, dev_spec_op)(cdev, gxdso_form_end, 0, 0);
2438
1.89k
    return code;
2439
1.89k
}
2440
2441
/* See bug #702560. The original file has a Form XObject which is not a stream. Instead
2442
 * the Form XObject has a /Contents key which points to a stream dictionary. This is plainly
2443
 * illegal but, as always, Acrobat can open it....
2444
 * If PDFSTOPONERROR is true then we just exit. Otherwise we look for a /Contents key in the stream
2445
 * dictionary. If we find one we dereference the object to get a stream dictionary, then merge the
2446
 * two dictionaries, ensuring the stream offset is correct, and proceed as if that's what we'd
2447
 * always had. If we don't have a /Contents key then exit with a typecheck error.
2448
 *
2449
 * Sets *hacked_stream to the /Contents stream if it found one.
2450
 */
2451
static int pdfi_form_stream_hack(pdf_context *ctx, pdf_dict *form_dict, pdf_stream **hacked_stream)
2452
810
{
2453
810
    int code = 0;
2454
810
    pdf_stream *stream_obj = NULL;
2455
810
    pdf_obj *Parent = NULL;
2456
810
    pdf_dict *d = NULL;
2457
810
    pdf_dict *stream_dict = NULL;
2458
2459
810
    *hacked_stream = NULL;
2460
2461
810
    if (pdfi_type_of(form_dict) == PDF_STREAM)
2462
0
        return 0;
2463
2464
810
    if ((code = pdfi_set_error_stop(ctx, gs_note_error(gs_error_typecheck), NULL, E_PDF_BADSTREAMDICT, "pdfi_form_stream_hack", NULL)) < 0) {
2465
0
        goto exit;
2466
0
    }
2467
2468
810
    code = pdfi_dict_knownget_type(ctx, form_dict, "Contents", PDF_STREAM,
2469
810
                                   (pdf_obj **)&stream_obj);
2470
810
    if (code < 0 || stream_obj == NULL) {
2471
793
        pdfi_set_error(ctx, 0, NULL, E_PDF_BADSTREAMDICT, "pdfi_form_stream_hack", NULL);
2472
793
        code = gs_note_error(gs_error_typecheck);
2473
793
        goto exit;
2474
793
    }
2475
2476
17
    d = form_dict;
2477
17
    pdfi_countup(d);
2478
28
    do {
2479
28
        code = pdfi_dict_knownget(ctx, d, "Parent", (pdf_obj **)&Parent);
2480
28
        if (code > 0 && pdfi_type_of(Parent) == PDF_DICT) {
2481
11
            if (Parent->object_num == stream_obj->object_num) {
2482
0
                pdfi_countdown(d);
2483
0
                pdfi_countdown(Parent);
2484
0
                pdfi_set_error(ctx, 0, NULL, E_PDF_BADSTREAMDICT, "pdfi_form_stream_hack", NULL);
2485
0
                code = gs_note_error(gs_error_undefined);
2486
0
                goto exit;
2487
0
            }
2488
11
            pdfi_countdown(d);
2489
11
            d = (pdf_dict *)Parent;
2490
17
        } else {
2491
17
            pdfi_countdown(d);
2492
17
            break;
2493
17
        }
2494
28
    } while (1);
2495
2496
17
    code = pdfi_dict_from_obj(ctx, (pdf_obj *)stream_obj, &stream_dict);
2497
17
    if (code < 0) {
2498
0
        pdfi_set_error(ctx, 0, NULL, E_PDF_BADSTREAMDICT, "pdfi_form_stream_hack", NULL);
2499
0
        goto exit;
2500
0
    }
2501
17
    pdfi_set_warning(ctx, 0, NULL, W_PDF_STREAM_HAS_CONTENTS, "pdfi_form_stream_hack", NULL);
2502
17
    code = pdfi_merge_dicts(ctx, stream_dict, form_dict);
2503
    /* Having merged the dictionaries, we don't want the Contents key in the stream dict.
2504
     * We do want to leave it in the form dictionary, in case we use this form again.
2505
     * Leaving the reference in the stream dicttionary leads to a reference counting problem
2506
     * because stream_dict is contained in stream_obj so stream_obj becomes self-referencing.
2507
     */
2508
17
    pdfi_dict_delete(ctx, stream_dict, "Contents");
2509
2510
17
    if (code == 0) {
2511
17
        *hacked_stream = stream_obj;
2512
17
        pdfi_countup(stream_obj);
2513
17
    }
2514
2515
810
 exit:
2516
810
    pdfi_countdown(stream_obj);
2517
810
    return code;
2518
17
}
2519
2520
static int pdfi_do_form(pdf_context *ctx, pdf_dict *page_dict, pdf_stream *form_obj)
2521
218k
{
2522
218k
    int code, code1 = 0;
2523
218k
    bool group_known = false, known = false;
2524
218k
    bool do_group = false;
2525
218k
    pdf_array *FormMatrix = NULL;
2526
218k
    gs_matrix formmatrix, CTM;
2527
218k
    gs_rect bbox;
2528
218k
    pdf_array *BBox = NULL;
2529
218k
    bool save_PreservePDFForm;
2530
218k
    pdf_stream *form_stream = NULL; /* Alias */
2531
218k
    pdf_stream *hacked_stream = NULL;
2532
218k
    pdf_dict *form_dict;
2533
218k
    gs_color_space *pcs = NULL;
2534
218k
    gs_client_color cc, *pcc;
2535
218k
    path_record *SavedPathRecord = ctx->PathRecord;
2536
2537
#if DEBUG_IMAGES
2538
    dbgmprintf(ctx->memory, "pdfi_do_form BEGIN\n");
2539
#endif
2540
218k
    if (pdfi_type_of(form_obj) != PDF_STREAM) {
2541
810
        code = pdfi_form_stream_hack(ctx, (pdf_dict *)form_obj, &hacked_stream);
2542
810
        if (code < 0)
2543
793
            return code;
2544
17
        form_stream = hacked_stream;
2545
17
    } else
2546
217k
        form_stream = (pdf_stream *)form_obj;
2547
2548
217k
    ctx->PathRecord = NULL;
2549
2550
217k
    code = pdfi_dict_from_obj(ctx, (pdf_obj *)form_stream, &form_dict);
2551
217k
    if (code < 0)
2552
0
        goto exit;
2553
2554
217k
    code = pdfi_dict_known(ctx, form_dict, "Group", &group_known);
2555
217k
    if (code < 0)
2556
0
        goto exit;
2557
217k
    if (group_known && ctx->page.has_transparency)
2558
5.95k
        do_group = true;
2559
2560
    /* Grab the CTM before it gets modified */
2561
217k
    code = gs_currentmatrix(ctx->pgs, &CTM);
2562
217k
    if (code < 0) goto exit1;
2563
2564
217k
    code = pdfi_op_q(ctx);
2565
217k
    if (code < 0) goto exit1;
2566
2567
217k
    code = pdfi_dict_knownget_type(ctx, form_dict, "Matrix", PDF_ARRAY, (pdf_obj **)&FormMatrix);
2568
217k
    if (code < 0) goto exit1;
2569
2570
217k
    code = pdfi_array_to_gs_matrix(ctx, FormMatrix, &formmatrix);
2571
217k
    if (code < 0) goto exit1;
2572
2573
217k
    code = pdfi_dict_known(ctx, form_dict, "BBox", &known);
2574
217k
    if (known) {
2575
215k
        code = pdfi_dict_get_type(ctx, form_dict, "BBox", PDF_ARRAY, (pdf_obj **)&BBox);
2576
215k
        if (code < 0) goto exit1;
2577
215k
    } else {
2578
1.75k
        if ((code = pdfi_set_error_stop(ctx, gs_note_error(gs_error_undefined), NULL, E_PDF_MISSING_BBOX, "pdfi_do_form", NULL)) < 0) {
2579
0
            goto exit;
2580
0
        }
2581
1.75k
    }
2582
2583
217k
    code = pdfi_array_to_gs_rect(ctx, BBox, &bbox);
2584
217k
    if (code < 0) goto exit1;
2585
2586
217k
    if (bbox.q.x - bbox.p.x == 0.0 || bbox.q.y - bbox.p.y == 0.0) {
2587
292
        if ((code = pdfi_set_warning_stop(ctx, gs_note_error(gs_error_rangecheck), NULL, W_PDF_FORM_CLIPPEDOUT, "pdfi_do_form", "")) < 0)
2588
0
            goto exit1;
2589
2590
292
        if (ctx->PreservePDFForm) {
2591
0
            code = pdfi_form_highlevel_begin(ctx, form_dict, &CTM, &bbox, &formmatrix);
2592
0
            if (code >= 0)
2593
0
                code = pdfi_form_highlevel_end(ctx);
2594
0
        }
2595
292
        goto exit1;
2596
292
    }
2597
2598
217k
    code = gs_concat(ctx->pgs, &formmatrix);
2599
217k
    if (code < 0) goto exit1;
2600
2601
217k
    code = gs_rectclip(ctx->pgs, &bbox, 1);
2602
217k
    if (code < 0) goto exit1;
2603
2604
217k
    if (ctx->PreservePDFForm) {
2605
1.89k
        code = pdfi_form_highlevel_begin(ctx, form_dict, &CTM, &bbox, &formmatrix);
2606
1.89k
        if (code < 0) goto exit1;
2607
1.89k
    }
2608
217k
    save_PreservePDFForm = ctx->PreservePDFForm;
2609
217k
    ctx->PreservePDFForm = false; /* Turn off in case there are any sub-forms */
2610
2611
217k
    if (do_group) {
2612
5.93k
        code = pdfi_loop_detector_mark(ctx);
2613
5.93k
        if (code < 0) goto exit1;
2614
2615
        /* Save the current color space in case it gets changed */
2616
5.93k
        pcs = gs_currentcolorspace(ctx->pgs);
2617
5.93k
        rc_increment(pcs);
2618
5.93k
        pcc = (gs_client_color *)gs_currentcolor(ctx->pgs);
2619
5.93k
        cc = *pcc;
2620
2621
5.93k
        code = pdfi_trans_begin_form_group(ctx, page_dict, form_dict);
2622
5.93k
        (void)pdfi_loop_detector_cleartomark(ctx);
2623
5.93k
        if (code < 0) goto exit1;
2624
2625
5.48k
        code = pdfi_form_execgroup(ctx, page_dict, form_stream, NULL, pcs, &cc, NULL);
2626
5.48k
        code1 = pdfi_trans_end_group(ctx);
2627
5.48k
        if (code == 0) code = code1;
2628
211k
    } else {
2629
211k
        bool saved_decrypt_strings = ctx->encryption.decrypt_strings;
2630
2631
        /* We can run a Form even when we aren't running a page content stresm,
2632
         * eg for an annotation, and we need to *not* decrypt strings in that
2633
         * case (the content stream will be decrypted and strings in content
2634
         * streams are not additionally encrypted).
2635
         */
2636
211k
        ctx->encryption.decrypt_strings = false;
2637
211k
        code = pdfi_run_context(ctx, form_stream, page_dict, false, "FORM");
2638
211k
        ctx->encryption.decrypt_strings = saved_decrypt_strings;
2639
211k
    }
2640
2641
216k
    ctx->PreservePDFForm = save_PreservePDFForm;
2642
216k
    if (ctx->PreservePDFForm) {
2643
1.89k
        code = pdfi_form_highlevel_end(ctx);
2644
1.89k
    }
2645
2646
217k
 exit1:
2647
217k
    code1 = pdfi_op_Q(ctx);
2648
217k
    if (code == 0) code = code1;
2649
2650
217k
 exit:
2651
217k
    pdfi_countdown(FormMatrix);
2652
217k
    pdfi_countdown(BBox);
2653
217k
    pdfi_countdown(hacked_stream);
2654
217k
    if (pcs)
2655
5.93k
        rc_decrement_only_cs(pcs, "pdfi_do_form(pcs)");
2656
#if DEBUG_IMAGES
2657
    dbgmprintf(ctx->memory, "pdfi_do_form END\n");
2658
#endif
2659
217k
    if (SavedPathRecord != ctx->PathRecord) {
2660
4.72k
        FreePathRecord(ctx);
2661
4.72k
        ctx->PathRecord = SavedPathRecord;
2662
4.72k
    }
2663
217k
    if (code < 0)
2664
535
        return code;
2665
217k
    return 0;
2666
217k
}
2667
2668
int pdfi_do_highlevel_form(pdf_context *ctx, pdf_dict *page_dict, pdf_stream *form_stream)
2669
1.89k
{
2670
1.89k
    int code = 0;
2671
2672
1.89k
    ctx->PreservePDFForm = true;
2673
1.89k
    code = pdfi_do_form(ctx, page_dict, form_stream);
2674
1.89k
    ctx->PreservePDFForm = false;
2675
2676
1.89k
    return code;
2677
1.89k
}
2678
2679
int pdfi_do_image_or_form(pdf_context *ctx, pdf_dict *stream_dict,
2680
                                 pdf_dict *page_dict, pdf_obj *xobject_obj)
2681
308k
{
2682
308k
    int code;
2683
308k
    pdf_name *n = NULL;
2684
308k
    pdf_dict *xobject_dict;
2685
308k
    bool known = false;
2686
308k
    gs_offset_t savedoffset;
2687
2688
308k
    code = pdfi_dict_from_obj(ctx, xobject_obj, &xobject_dict);
2689
308k
    if (code < 0)
2690
0
        return code;
2691
2692
    /* Check Optional Content status */
2693
308k
    code = pdfi_dict_known(ctx, xobject_dict, "OC", &known);
2694
308k
    if (code < 0)
2695
0
        return code;
2696
2697
308k
    if (known) {
2698
548
        pdf_dict *OCDict = NULL;
2699
548
        bool visible = false;
2700
548
        gx_device *cdev = gs_currentdevice_inline(ctx->pgs);
2701
2702
548
        code = pdfi_dict_get(ctx, xobject_dict, "OC", (pdf_obj **)&OCDict);
2703
548
        if (code < 0)
2704
29
            return code;
2705
2706
519
        if (pdfi_type_of(OCDict) == PDF_DICT) {
2707
508
            char *label = NULL;
2708
2709
508
            if (ctx->device_state.writepdfmarks && ctx->device_state.WantsOptionalContent) {
2710
16
                code = pdfi_pdfmark_dict(ctx, OCDict);
2711
16
                if (code < 0) {
2712
0
                    if ((code = pdfi_set_warning_stop(ctx, code, NULL, W_PDF_DO_OC_FAILED, "pdfi_do_image_or_form", NULL)) < 0) {
2713
0
                        pdfi_countdown(OCDict);
2714
0
                        return code;
2715
0
                    }
2716
0
                }
2717
16
                code = pdfi_obj_get_label(ctx, (pdf_obj *)OCDict, &label);
2718
16
                if (code >= 0) {
2719
16
                    code = dev_proc(cdev, dev_spec_op)(cdev, gxdso_pending_optional_content, label, 0);
2720
16
                    gs_free_object(ctx->memory, label, "");
2721
16
                    if (code < 0) {
2722
0
                        if ((code = pdfi_set_warning_stop(ctx, code, NULL, W_PDF_DO_OC_FAILED, "pdfi_do_image_or_form", NULL)) < 0) {
2723
0
                            pdfi_countdown(OCDict);
2724
0
                            return code;
2725
0
                        }
2726
0
                    }
2727
16
                } else {
2728
0
                    if ((code = pdfi_set_warning_stop(ctx, code, NULL, W_PDF_DO_OC_FAILED, "pdfi_do_image_or_form", NULL)) < 0) {
2729
0
                        pdfi_countdown(OCDict);
2730
0
                        return code;
2731
0
                    }
2732
0
                }
2733
492
            } else {
2734
492
                visible = pdfi_oc_is_ocg_visible(ctx, OCDict);
2735
492
                if (!visible) {
2736
47
                    pdfi_countdown(OCDict);
2737
47
                    return 0;
2738
47
                }
2739
492
            }
2740
508
        } else {
2741
11
            if ((code = pdfi_set_warning_stop(ctx, gs_note_error(gs_error_typecheck), NULL, W_PDF_BAD_OCDICT, "pdfi_do_image_or_form", NULL)) < 0)
2742
0
                return code;
2743
11
        }
2744
472
        pdfi_countdown(OCDict);
2745
472
    }
2746
2747
#if DEBUG_IMAGES
2748
    dbgmprintf1(ctx->memory, "pdfi_do_image_or_form BEGIN (OBJ = %d)\n", xobject_obj->object_num);
2749
#endif
2750
308k
    code = pdfi_trans_set_params(ctx);
2751
308k
    if (code < 0)
2752
80
        return code;
2753
2754
307k
    code = pdfi_dict_get(ctx, xobject_dict, "Subtype", (pdf_obj **)&n);
2755
307k
    if (code < 0) {
2756
2.60k
        if (code == gs_error_undefined) {
2757
2.60k
            int code1 = 0;
2758
            /* This is illegal, because we have no way to tell is an XObject is a Form
2759
             * or Image object. However it seems Acrobat just assumes that it's a Form!
2760
             * See test file /tests_private/pdf/PDFIA1.7_SUBSET/CATX2063.pdf
2761
             */
2762
2.60k
            code1 = pdfi_name_alloc(ctx, (byte *)"Form", 4, (pdf_obj **)&n);
2763
2.60k
            if (code1 == 0) {
2764
2.60k
                pdfi_countup(n);
2765
2.60k
            }
2766
2.60k
            if ((code = pdfi_set_error_stop(ctx, gs_note_error(gs_error_undefined), NULL, E_PDF_NO_SUBTYPE, "pdfi_do_image_or_form", NULL)) < 0) {
2767
0
                goto exit;
2768
0
            }
2769
2.60k
        }
2770
0
        else
2771
0
            goto exit;
2772
2.60k
    }
2773
307k
    if (pdfi_type_of(n) != PDF_NAME) {
2774
15
        code = gs_note_error(gs_error_typecheck);
2775
15
        goto exit;
2776
15
    }
2777
2778
307k
    if (pdfi_name_is(n, "Image")) {
2779
91.4k
try_as_image:
2780
91.4k
        if (pdfi_type_of(xobject_obj) != PDF_STREAM) {
2781
387
            code = gs_note_error(gs_error_typecheck);
2782
387
            goto exit;
2783
387
        }
2784
91.0k
        savedoffset = pdfi_tell(ctx->main_stream);
2785
91.0k
        code = pdfi_do_image(ctx, page_dict, stream_dict, (pdf_stream *)xobject_obj,
2786
91.0k
                             ctx->main_stream, false);
2787
91.0k
        pdfi_seek(ctx, ctx->main_stream, savedoffset, SEEK_SET);
2788
217k
    } else if (pdfi_name_is(n, "Form")) {
2789
        /* In theory a Form must be a stream, but we don't check that here
2790
         * because there is a broken case where it can be a dict.
2791
         * So pdfi_do_form() will handle that crazy case if it's not actually a stream.
2792
         */
2793
216k
        code = pdfi_do_form(ctx, page_dict, (pdf_stream *)xobject_obj);
2794
216k
    } else if (pdfi_name_is(n, "PS")) {
2795
0
        code = pdfi_set_error_stop(ctx, gs_note_error(gs_error_typecheck), NULL, E_PDF_PS_XOBJECT_IGNORED, "pdfi_form_stream_hack", NULL);
2796
772
    } else {
2797
772
        code = pdfi_set_error_stop(ctx, gs_note_error(gs_error_typecheck), NULL, E_PDF_BAD_SUBTYPE, "pdfi_do_image_or_form", NULL);
2798
772
        if (code >= 0)
2799
772
            goto try_as_image;
2800
772
    }
2801
2802
307k
 exit:
2803
307k
    pdfi_countdown(n);
2804
#if DEBUG_IMAGES
2805
    dbgmprintf(ctx->memory, "pdfi_do_image_or_form END\n");
2806
#endif
2807
307k
    return code;
2808
307k
}
2809
2810
int pdfi_Do(pdf_context *ctx, pdf_dict *stream_dict, pdf_dict *page_dict)
2811
242k
{
2812
242k
    int code = 0;
2813
242k
    pdf_name *n = NULL;
2814
242k
    pdf_obj *o = NULL;
2815
242k
    pdf_dict *sdict = NULL;
2816
242k
    bool known = false, AddedParent = false;
2817
2818
242k
    if (pdfi_count_stack(ctx) < 1) {
2819
2.24k
        code = gs_note_error(gs_error_stackunderflow);
2820
2.24k
        goto exit1;
2821
2.24k
    }
2822
240k
    n = (pdf_name *)ctx->stack_top[-1];
2823
240k
    pdfi_countup(n);
2824
240k
    pdfi_pop(ctx, 1);
2825
2826
240k
    if (pdfi_type_of(n) != PDF_NAME) {
2827
2.01k
        code = gs_note_error(gs_error_typecheck);
2828
2.01k
        goto exit1;
2829
2.01k
    }
2830
2831
238k
    if (ctx->text.BlockDepth != 0) {
2832
1.99k
        ctx->text.BlockDepth = 0;
2833
1.99k
        if (ctx->text.TextClip) {
2834
0
            gx_device *dev = gs_currentdevice_inline(ctx->pgs);
2835
2836
0
            ctx->text.TextClip = false;
2837
0
            (void)dev_proc(dev, dev_spec_op)(dev, gxdso_hilevel_text_clip, (void *)0, 1);
2838
0
        }
2839
1.99k
        code = pdfi_set_warning_stop(ctx, gs_note_error(gs_error_syntaxerror), NULL, W_PDF_OPINVALIDINTEXT, "pdfi_Do", NULL);
2840
1.99k
        if (code < 0)
2841
0
            goto exit;
2842
1.99k
    }
2843
2844
238k
    code = pdfi_loop_detector_mark(ctx);
2845
238k
    if (code < 0)
2846
0
        goto exit1;
2847
238k
    code = pdfi_find_resource(ctx, (unsigned char *)"XObject", n, (pdf_dict *)stream_dict, page_dict, &o);
2848
238k
    if (code < 0)
2849
85.9k
        goto exit;
2850
2851
152k
    if (pdfi_type_of(o) != PDF_STREAM && pdfi_type_of(o) != PDF_DICT) {
2852
5.35k
        code = gs_note_error(gs_error_typecheck);
2853
5.35k
        goto exit;
2854
5.35k
    }
2855
2856
    /* This doesn't count up the stream dictionary, so we don't need to count it down later */
2857
147k
    code = pdfi_dict_from_obj(ctx, o, &sdict);
2858
147k
    if (code < 0)
2859
0
        goto exit;
2860
2861
147k
    code = pdfi_dict_known(ctx, sdict, "Parent", &known);
2862
147k
    if (code < 0)
2863
0
        goto exit;
2864
    /* Add a Parent ref, unless it happens to be a circular reference
2865
     * (sample Bug298226.pdf -- has a circular ref and adding the Parent caused memory leak)
2866
     */
2867
147k
    if (!known && sdict->object_num != stream_dict->object_num) {
2868
147k
        code = pdfi_dict_put(ctx, sdict, "Parent", (pdf_obj *)stream_dict);
2869
147k
        if (code < 0)
2870
0
            goto exit;
2871
147k
        pdfi_countup(sdict);
2872
147k
        AddedParent = true;
2873
147k
    }
2874
2875
147k
    (void)pdfi_loop_detector_cleartomark(ctx);
2876
    /* We used to have a pdfi_gsave/pdfi_grestore around this, this is actually done
2877
     * for us within the functions that pdfi_do_image_or_form calls now. */
2878
147k
    code = pdfi_do_image_or_form(ctx, stream_dict, page_dict, o);
2879
147k
    pdfi_countdown(n);
2880
147k
    pdfi_countdown(o);
2881
147k
    if (AddedParent == true) {
2882
147k
        if (code >= 0)
2883
145k
            code = pdfi_dict_delete(ctx, sdict, "Parent");
2884
1.68k
        else
2885
1.68k
            (void)pdfi_dict_delete(ctx, sdict, "Parent");
2886
147k
        pdfi_countdown(sdict);
2887
147k
    }
2888
147k
    return code;
2889
2890
91.3k
exit:
2891
91.3k
    (void)pdfi_loop_detector_cleartomark(ctx);
2892
95.6k
exit1:
2893
95.6k
    pdfi_countdown(n);
2894
95.6k
    pdfi_countdown(o);
2895
95.6k
    return code;
2896
91.3k
}