• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

saitoha / libsixel / 20466639304

23 Dec 2025 04:53PM UTC coverage: 51.46% (-6.3%) from 57.773%
20466639304

push

github

saitoha
build: fix windows find path in images meson build

14511 of 44933 branches covered (32.29%)

21089 of 40981 relevant lines covered (51.46%)

3915123.44 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

59.91
/src/decoder.c
1
/*
2
 * Copyright (c) 2014-2025 Hayaki Saito
3
 *
4
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
5
 * this software and associated documentation files (the "Software"), to deal in
6
 * the Software without restriction, including without limitation the rights to
7
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
8
 * the Software, and to permit persons to whom the Software is furnished to do so,
9
 * subject to the following conditions:
10
 *
11
 * The above copyright notice and this permission notice shall be included in all
12
 * copies or substantial portions of the Software.
13
 *
14
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
16
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
17
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
18
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
19
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
20
 */
21

22
#include "config.h"
23

24
/* STDC_HEADERS */
25
#include <stdio.h>
26
#include <stdlib.h>
27
#include <string.h>
28

29
#if HAVE_MATH_H
30
# include <math.h>
31
#endif  /* HAVE_MATH_H */
32
#if HAVE_LIMITS_H
33
# include <limits.h>
34
#endif  /* HAVE_LIMITS_H */
35
#if HAVE_UNISTD_H
36
# include <unistd.h>
37
#elif HAVE_SYS_UNISTD_H
38
# include <sys/unistd.h>
39
#endif  /* HAVE_UNISTD_H */
40
#if HAVE_FCNTL_H
41
# include <fcntl.h>
42
#endif  /* HAVE_FCNTL_H */
43
#if HAVE_SYS_STAT_H
44
# include <sys/stat.h>
45
#endif  /* HAVE_SYS_STAT_H */
46
#if HAVE_ERRNO_H
47
# include <errno.h>
48
#endif  /* HAVE_ERRNO_H */
49
#if HAVE_IO_H
50
#include <io.h>
51
#endif  /* HAVE_IO_H */
52

53
#include "decoder.h"
54
#include "decoder-parallel.h"
55
#include "clipboard.h"
56
#include "compat_stub.h"
57
#include "options.h"
58

59
static void
60
decoder_clipboard_select_format(char *dest,
4✔
61
                                size_t dest_size,
62
                                char const *format,
63
                                char const *fallback)
64
{
65
    char const *source;
4✔
66
    size_t limit;
4✔
67

68
    if (dest == NULL || dest_size == 0u) {
4!
69
        return;
70
    }
71

72
    source = fallback;
4✔
73
    if (format != NULL && format[0] != '\0') {
4!
74
        source = format;
4✔
75
    }
76

77
    limit = dest_size - 1u;
4✔
78
    if (limit == 0u) {
4!
79
        dest[0] = '\0';
×
80
        return;
×
81
    }
82

83
    (void)snprintf(dest, dest_size, "%.*s", (int)limit, source);
4✔
84
}
1!
85

86

87
static char *
88
decoder_create_temp_template_with_prefix(sixel_allocator_t *allocator,
4✔
89
                                         char const *prefix,
90
                                         size_t *capacity_out)
91
{
92
    char const *tmpdir;
4✔
93
    size_t tmpdir_len;
4✔
94
    size_t prefix_len;
4✔
95
    size_t suffix_len;
4✔
96
    size_t template_len;
4✔
97
    char *template_path;
4✔
98
    int needs_separator;
4✔
99
    size_t maximum_tmpdir_len;
4✔
100

101
    tmpdir = sixel_compat_getenv("TMPDIR");
4✔
102
#if defined(_WIN32)
103
    if (tmpdir == NULL || tmpdir[0] == '\0') {
104
        tmpdir = sixel_compat_getenv("TEMP");
105
    }
106
    if (tmpdir == NULL || tmpdir[0] == '\0') {
107
        tmpdir = sixel_compat_getenv("TMP");
108
    }
109
#endif
110
    if (tmpdir == NULL || tmpdir[0] == '\0') {
4!
111
#if defined(_WIN32)
112
        tmpdir = ".";
113
#else
114
        tmpdir = "/tmp";
4✔
115
#endif
116
    }
117

118
    tmpdir_len = strlen(tmpdir);
4✔
119
    prefix_len = strlen(prefix);
4✔
120
    suffix_len = prefix_len + strlen("-XXXXXX");
4✔
121
    maximum_tmpdir_len = (size_t)INT_MAX;
4✔
122

123
    if (maximum_tmpdir_len <= suffix_len + 2) {
4!
124
        return NULL;
125
    }
126
    if (tmpdir_len > maximum_tmpdir_len - (suffix_len + 2)) {
4!
127
        return NULL;
128
    }
129

130
    needs_separator = 1;
4✔
131
    if (tmpdir_len > 0) {
4!
132
        if (tmpdir[tmpdir_len - 1] == '/' || tmpdir[tmpdir_len - 1] == '\\') {
4!
133
            needs_separator = 0;
4✔
134
        }
135
    }
136

137
    template_len = tmpdir_len + suffix_len + 2;
4✔
138
    template_path = (char *)sixel_allocator_malloc(allocator, template_len);
4✔
139
    if (template_path == NULL) {
4!
140
        return NULL;
141
    }
142

143
    if (needs_separator) {
4!
144
#if defined(_WIN32)
145
        (void)snprintf(template_path, template_len,
146
                       "%s\\%s-XXXXXX", tmpdir, prefix);
147
#else
148
        (void)snprintf(template_path, template_len,
4✔
149
                       "%s/%s-XXXXXX", tmpdir, prefix);
150
#endif
151
    } else {
152
        (void)snprintf(template_path, template_len,
×
153
                       "%s%s-XXXXXX", tmpdir, prefix);
154
    }
155

156
    if (capacity_out != NULL) {
4!
157
        *capacity_out = template_len;
4✔
158
    }
159

160
    return template_path;
161
}
162

163

164
static SIXELSTATUS
165
decoder_clipboard_create_spool(sixel_allocator_t *allocator,
4✔
166
                               char const *prefix,
167
                               char **path_out)
168
{
169
    SIXELSTATUS status;
4✔
170
    char *template_path;
4✔
171
    size_t template_capacity;
4✔
172
    int open_flags;
4✔
173
    int open_mode;
4✔
174
    int fd;
4✔
175
    char *tmpname_result;
4✔
176

177
    status = SIXEL_FALSE;
4✔
178
    template_path = NULL;
4✔
179
    template_capacity = 0u;
4✔
180
    open_flags = 0;
4✔
181
    open_mode = 0;
4✔
182
    fd = (-1);
4✔
183
    tmpname_result = NULL;
4✔
184

185
    template_path = decoder_create_temp_template_with_prefix(allocator,
4✔
186
                                                             prefix,
187
                                                             &template_capacity);
188
    if (template_path == NULL) {
4!
189
        sixel_helper_set_additional_message(
×
190
            "clipboard: failed to allocate spool template.");
191
        status = SIXEL_BAD_ALLOCATION;
×
192
        goto end;
×
193
    }
194

195
    if (sixel_compat_mktemp(template_path, template_capacity) != 0) {
4!
196
        tmpname_result = sixel_compat_tmpnam(template_path,
×
197
                                             template_capacity);
198
        if (tmpname_result == NULL) {
×
199
            sixel_helper_set_additional_message(
×
200
                "clipboard: failed to reserve spool template.");
201
            status = SIXEL_LIBC_ERROR;
×
202
            goto end;
×
203
        }
204
        template_capacity = strlen(template_path) + 1u;
×
205
    }
206

207
    open_flags = O_RDWR | O_CREAT | O_TRUNC;
4✔
208
#if defined(O_EXCL)
209
    open_flags |= O_EXCL;
4✔
210
#endif
211
    open_mode = S_IRUSR | S_IWUSR;
4✔
212
    fd = sixel_compat_open(template_path, open_flags, open_mode);
4✔
213
    if (fd < 0) {
4!
214
        sixel_helper_set_additional_message(
×
215
            "clipboard: failed to open spool file.");
216
        status = SIXEL_LIBC_ERROR;
×
217
        goto end;
×
218
    }
219

220
    *path_out = template_path;
4✔
221
    if (fd >= 0) {
4!
222
        (void)sixel_compat_close(fd);
4✔
223
        fd = (-1);
4✔
224
    }
225

226
    template_path = NULL;
4✔
227
    status = SIXEL_OK;
4✔
228

229
end:
×
230
    if (fd >= 0) {
4!
231
        (void)sixel_compat_close(fd);
232
    }
233
    if (template_path != NULL) {
4!
234
        sixel_allocator_free(allocator, template_path);
×
235
    }
236

237
    return status;
4✔
238
}
239

240

241
static SIXELSTATUS
242
decoder_clipboard_read_file(char const *path,
4✔
243
                            unsigned char **data,
244
                            size_t *size)
245
{
246
    FILE *stream;
4✔
247
    long seek_result;
4✔
248
    long file_size;
4✔
249
    unsigned char *buffer;
4✔
250
    size_t read_size;
4✔
251

252
    if (data == NULL || size == NULL) {
4!
253
        sixel_helper_set_additional_message(
×
254
            "clipboard: read buffer pointers are null.");
255
        return SIXEL_BAD_ARGUMENT;
×
256
    }
257

258
    *data = NULL;
4✔
259
    *size = 0u;
4✔
260

261
    if (path == NULL) {
4!
262
        sixel_helper_set_additional_message(
×
263
            "clipboard: spool path is null.");
264
        return SIXEL_BAD_ARGUMENT;
×
265
    }
266

267
    stream = sixel_compat_fopen(path, "rb");
4✔
268
    if (stream == NULL) {
4!
269
        sixel_helper_set_additional_message(
×
270
            "clipboard: failed to open spool file for read.");
271
        return SIXEL_LIBC_ERROR;
×
272
    }
273

274
    seek_result = fseek(stream, 0L, SEEK_END);
4✔
275
    if (seek_result != 0) {
4!
276
        (void)fclose(stream);
×
277
        sixel_helper_set_additional_message(
×
278
            "clipboard: failed to seek spool file.");
279
        return SIXEL_LIBC_ERROR;
×
280
    }
281

282
    file_size = ftell(stream);
4✔
283
    if (file_size < 0) {
4!
284
        (void)fclose(stream);
×
285
        sixel_helper_set_additional_message(
×
286
            "clipboard: failed to determine spool size.");
287
        return SIXEL_LIBC_ERROR;
×
288
    }
289

290
    seek_result = fseek(stream, 0L, SEEK_SET);
4✔
291
    if (seek_result != 0) {
4!
292
        (void)fclose(stream);
×
293
        sixel_helper_set_additional_message(
×
294
            "clipboard: failed to rewind spool file.");
295
        return SIXEL_LIBC_ERROR;
×
296
    }
297

298
    if (file_size == 0) {
4!
299
        buffer = NULL;
300
        read_size = 0u;
301
    } else {
302
        buffer = (unsigned char *)malloc((size_t)file_size);
4✔
303
        if (buffer == NULL) {
4!
304
            (void)fclose(stream);
×
305
            sixel_helper_set_additional_message(
×
306
                "clipboard: malloc() failed for spool payload.");
307
            return SIXEL_BAD_ALLOCATION;
×
308
        }
309
        read_size = fread(buffer, 1u, (size_t)file_size, stream);
4!
310
        if (read_size != (size_t)file_size) {
4!
311
            free(buffer);
×
312
            (void)fclose(stream);
×
313
            sixel_helper_set_additional_message(
×
314
                "clipboard: failed to read spool payload.");
315
            return SIXEL_LIBC_ERROR;
×
316
        }
317
    }
318

319
    if (fclose(stream) != 0) {
4!
320
        if (buffer != NULL) {
×
321
            free(buffer);
×
322
        }
323
        sixel_helper_set_additional_message(
×
324
            "clipboard: failed to close spool file after read.");
325
        return SIXEL_LIBC_ERROR;
×
326
    }
327

328
    *data = buffer;
4✔
329
    *size = read_size;
4✔
330

331
    return SIXEL_OK;
4✔
332
}
333

334

335
/* original version of strdup(3) with allocator object */
336
static char *
337
strdup_with_allocator(
300✔
338
    char const          /* in */ *s,          /* source buffer */
339
    sixel_allocator_t   /* in */ *allocator)  /* allocator object for
340
                                                 destination buffer */
341
{
342
    char *p;
300✔
343

344
    p = (char *)sixel_allocator_malloc(allocator, (size_t)(strlen(s) + 1));
300✔
345
    if (p) {
300!
346
        (void)sixel_compat_strcpy(p, strlen(s) + 1, s);
300✔
347
    }
348
    return p;
300✔
349
}
350

351

352
/* create decoder object */
353
SIXELAPI SIXELSTATUS
354
sixel_decoder_new(
104✔
355
    sixel_decoder_t    /* out */ **ppdecoder,  /* decoder object to be created */
356
    sixel_allocator_t  /* in */  *allocator)   /* allocator, null if you use
357
                                                  default allocator */
358
{
359
    SIXELSTATUS status = SIXEL_FALSE;
104✔
360

361
    if (allocator == NULL) {
104!
362
        status = sixel_allocator_new(&allocator, NULL, NULL, NULL, NULL);
104✔
363
        if (SIXEL_FAILED(status)) {
104!
364
            goto end;
×
365
        }
366
    } else {
367
        sixel_allocator_ref(allocator);
×
368
    }
369

370
    *ppdecoder = sixel_allocator_malloc(allocator, sizeof(sixel_decoder_t));
104✔
371
    if (*ppdecoder == NULL) {
104!
372
        sixel_allocator_unref(allocator);
×
373
        sixel_helper_set_additional_message(
×
374
            "sixel_decoder_new: sixel_allocator_malloc() failed.");
375
        status = SIXEL_BAD_ALLOCATION;
×
376
        goto end;
×
377
    }
378

379
    (*ppdecoder)->ref          = 1;
104✔
380
    (*ppdecoder)->output       = strdup_with_allocator("-", allocator);
104✔
381
    (*ppdecoder)->input        = strdup_with_allocator("-", allocator);
104✔
382
    (*ppdecoder)->allocator    = allocator;
104✔
383
    (*ppdecoder)->dequantize_method = SIXEL_DEQUANTIZE_NONE;
104✔
384
    (*ppdecoder)->dequantize_similarity_bias = 100;
104✔
385
    (*ppdecoder)->dequantize_edge_strength = 0;
104✔
386
    (*ppdecoder)->thumbnail_size = 0;
104✔
387
    (*ppdecoder)->direct_color = 0;
104✔
388
    (*ppdecoder)->clipboard_input_active = 0;
104✔
389
    (*ppdecoder)->clipboard_output_active = 0;
104✔
390
    (*ppdecoder)->clipboard_input_format[0] = '\0';
104✔
391
    (*ppdecoder)->clipboard_output_format[0] = '\0';
104✔
392

393
    if ((*ppdecoder)->output == NULL || (*ppdecoder)->input == NULL) {
104!
394
        sixel_decoder_unref(*ppdecoder);
×
395
        *ppdecoder = NULL;
×
396
        sixel_helper_set_additional_message(
×
397
            "sixel_decoder_new: strdup_with_allocator() failed.");
398
        status = SIXEL_BAD_ALLOCATION;
×
399
        sixel_allocator_unref(allocator);
×
400
        goto end;
×
401
    }
402

403
    status = SIXEL_OK;
404

405
end:
104✔
406
    return status;
104✔
407
}
408

409

410
/* deprecated version of sixel_decoder_new() */
411
SIXELAPI /* deprecated */ sixel_decoder_t *
412
sixel_decoder_create(void)
×
413
{
414
    SIXELSTATUS status = SIXEL_FALSE;
×
415
    sixel_decoder_t *decoder = NULL;
×
416

417
    status = sixel_decoder_new(&decoder, NULL);
×
418
    if (SIXEL_FAILED(status)) {
×
419
        goto end;
420
    }
421

422
end:
×
423
    return decoder;
×
424
}
425

426

427
/* destroy a decoder object */
428
static void
429
sixel_decoder_destroy(sixel_decoder_t *decoder)
100✔
430
{
431
    sixel_allocator_t *allocator;
100✔
432

433
    if (decoder) {
100!
434
        allocator = decoder->allocator;
100✔
435
        sixel_allocator_free(allocator, decoder->input);
100✔
436
        sixel_allocator_free(allocator, decoder->output);
100✔
437
        sixel_allocator_free(allocator, decoder);
100✔
438
        sixel_allocator_unref(allocator);
100✔
439
    }
440
}
100✔
441

442

443
/* increase reference count of decoder object (thread-unsafe) */
444
SIXELAPI void
445
sixel_decoder_ref(sixel_decoder_t *decoder)
216✔
446
{
447
    /* TODO: be thread safe */
448
    ++decoder->ref;
216✔
449
}
174✔
450

451

452
/* decrease reference count of decoder object (thread-unsafe) */
453
SIXELAPI void
454
sixel_decoder_unref(sixel_decoder_t *decoder)
316✔
455
{
456
    /* TODO: be thread safe */
457
    if (decoder != NULL && --decoder->ref == 0) {
316!
458
        sixel_decoder_destroy(decoder);
100✔
459
    }
460
}
316✔
461

462

463
typedef struct sixel_similarity {
464
    const unsigned char *palette;
465
    int ncolors;
466
    int stride;
467
    signed char *cache;
468
    int bias;
469
} sixel_similarity_t;
470

471
static SIXELSTATUS
472
sixel_similarity_init(sixel_similarity_t *similarity,
4✔
473
                      const unsigned char *palette,
474
                      int ncolors,
475
                      int bias,
476
                      sixel_allocator_t *allocator)
477
{
478
    size_t cache_size;
4✔
479
    int i;
4✔
480

481
    if (bias < 1) {
4!
482
        bias = 1;
483
    }
484

485
    similarity->palette = palette;
4✔
486
    similarity->ncolors = ncolors;
4✔
487
    similarity->stride = ncolors;
4✔
488
    similarity->bias = bias;
4✔
489

490
    cache_size = (size_t)ncolors * (size_t)ncolors;
4✔
491
    if (cache_size == 0) {
4!
492
        similarity->cache = NULL;
×
493
        return SIXEL_OK;
×
494
    }
495

496
    similarity->cache = (signed char *)sixel_allocator_malloc(
4✔
497
        allocator,
498
        cache_size);
499
    if (similarity->cache == NULL) {
4!
500
        sixel_helper_set_additional_message(
×
501
            "sixel_similarity_init: sixel_allocator_malloc() failed.");
502
        return SIXEL_BAD_ALLOCATION;
×
503
    }
504
    memset(similarity->cache, -1, cache_size);
4✔
505
    for (i = 0; i < ncolors; ++i) {
672✔
506
        similarity->cache[i * similarity->stride + i] = 7;
668✔
507
    }
508

509
    return SIXEL_OK;
510
}
511

512
static void
513
sixel_similarity_destroy(sixel_similarity_t *similarity,
4✔
514
                         sixel_allocator_t *allocator)
515
{
516
    if (similarity->cache != NULL) {
4!
517
        sixel_allocator_free(allocator, similarity->cache);
4✔
518
        similarity->cache = NULL;
4✔
519
    }
520
}
521

522
static inline unsigned int
523
sixel_similarity_diff(const unsigned char *a, const unsigned char *b)
2,142,728✔
524
{
525
    int dr = (int)a[0] - (int)b[0];
2,142,728✔
526
    int dg = (int)a[1] - (int)b[1];
2,142,728✔
527
    int db = (int)a[2] - (int)b[2];
2,142,728✔
528
    return (unsigned int)(dr * dr + dg * dg + db * db);
2,142,728✔
529
}
530

531
static unsigned int
532
sixel_similarity_compare(sixel_similarity_t *similarity,
8,614,816✔
533
                         int index1,
534
                         int index2,
535
                         int numerator,
536
                         int denominator)
537
{
538
    int min_index;
8,614,816✔
539
    int max_index;
8,614,816✔
540
    size_t cache_pos;
8,614,816✔
541
    signed char cached;
8,614,816✔
542
    const unsigned char *palette;
8,614,816✔
543
    const unsigned char *p1;
8,614,816✔
544
    const unsigned char *p2;
8,614,816✔
545
    unsigned char avg_color[3];
8,614,816✔
546
    unsigned int distance;
8,614,816✔
547
    unsigned int base_distance;
8,614,816✔
548
    unsigned long long scaled_distance;
8,614,816✔
549
    int bias;
8,614,816✔
550
    unsigned int min_diff = UINT_MAX;
8,614,816✔
551
    int i;
8,614,816✔
552
    unsigned int result;
8,614,816✔
553
    const unsigned char *pk;
8,614,816✔
554
    unsigned int diff;
8,614,816✔
555

556
    if (similarity->cache == NULL) {
8,614,816!
557
        return 0;
558
    }
559

560
    if (index1 < 0 || index1 >= similarity->ncolors ||
8,614,816!
561
        index2 < 0 || index2 >= similarity->ncolors) {
8,614,816!
562
        return 0;
563
    }
564

565
    if (index1 <= index2) {
8,614,816✔
566
        min_index = index1;
567
        max_index = index2;
568
    } else {
569
        min_index = index2;
2,595,860✔
570
        max_index = index1;
2,595,860✔
571
    }
572

573
    cache_pos = (size_t)min_index * (size_t)similarity->stride
8,614,816✔
574
              + (size_t)max_index;
8,614,816✔
575
    cached = similarity->cache[cache_pos];
8,614,816✔
576
    if (cached >= 0) {
8,614,816✔
577
        return (unsigned int)cached;
8,601,908✔
578
    }
579

580
    palette = similarity->palette;
12,908✔
581
    p1 = palette + index1 * 3;
12,908✔
582
    p2 = palette + index2 * 3;
12,908✔
583

584
#if 1
585
   /*    original: n = (p1 + p2) / 2
586
    */
587
    avg_color[0] = (unsigned char)(((unsigned int)p1[0]
12,908✔
588
                                    + (unsigned int)p2[0]) >> 1);
12,908✔
589
    avg_color[1] = (unsigned char)(((unsigned int)p1[1]
12,908✔
590
                                    + (unsigned int)p2[1]) >> 1);
12,908✔
591
    avg_color[2] = (unsigned char)(((unsigned int)p1[2]
12,908✔
592
                                    + (unsigned int)p2[2]) >> 1);
12,908✔
593
    (void) numerator;
12,908✔
594
    (void) denominator;
12,908✔
595
#else
596
   /*
597
    *    diffuse(pos_a, n1) -> p1
598
    *    diffuse(pos_b, n2) -> p2
599
    *
600
    *    when n1 == n2 == n:
601
    *
602
    *    p2 = n + (n - p1) * numerator / denominator
603
    * => p2 * denominator = n * denominator + (n - p1) * numerator
604
    * => p2 * denominator = n * denominator + n * numerator - p1 * numerator
605
    * => n * (denominator + numerator) = p1 * numerator + p2 * denominator
606
    * => n = (p1 * numerator + p2 * denominator) / (denominator + numerator)
607
    *
608
    */
609
    avg_color[0] = (p1[0] * numerator + p2[0] * denominator + (numerator + denominator + 0.5) / 2)
610
                 / (numerator + denominator);
611
    avg_color[1] = (p1[1] * numerator + p2[1] * denominator + (numerator + denominator + 0.5) / 2)
612
                 / (numerator + denominator);
613
    avg_color[2] = (p1[2] * numerator + p2[2] * denominator + (numerator + denominator + 0.5) / 2)
614
                 / (numerator + denominator);
615
#endif
616

617
    distance = sixel_similarity_diff(avg_color, p1);
12,908✔
618
    bias = similarity->bias;
12,908✔
619
    if (bias < 1) {
12,908!
620
        bias = 1;
621
    }
622
    scaled_distance = (unsigned long long)distance
12,908✔
623
                    * (unsigned long long)bias
12,908✔
624
                    + 50ULL;
625
    base_distance = (unsigned int)(scaled_distance / 100ULL);
12,908✔
626
    if (base_distance == 0U) {
12,908!
627
        base_distance = 1U;
628
    }
629

630
    for (i = 0; i < similarity->ncolors; ++i) {
2,168,544✔
631
        if (i == index1 || i == index2) {
2,155,636✔
632
            continue;
25,816✔
633
        }
634
        pk = palette + i * 3;
2,129,820✔
635
        diff = sixel_similarity_diff(avg_color, pk);
2,129,820✔
636
        if (diff < min_diff) {
2,129,820✔
637
            min_diff = diff;
2,155,636✔
638
        }
639
    }
640

641
    if (min_diff == UINT_MAX) {
12,908!
642
        min_diff = base_distance * 2U;
×
643
    }
644

645
    if (min_diff >= base_distance * 2U) {
12,908✔
646
        result = 5U;
647
    } else if (min_diff >= base_distance) {
12,220✔
648
        result = 8U;
649
    } else if ((unsigned long long)min_diff * 6ULL
11,392✔
650
               >= (unsigned long long)base_distance * 5ULL) {
11,392✔
651
        result = 7U;
652
    } else if ((unsigned long long)min_diff * 4ULL
11,096✔
653
               >= (unsigned long long)base_distance * 3ULL) {
11,096✔
654
        result = 7U;
655
    } else if ((unsigned long long)min_diff * 3ULL
10,896✔
656
               >= (unsigned long long)base_distance * 2ULL) {
10,896✔
657
        result = 5U;
658
    } else if ((unsigned long long)min_diff * 5ULL
10,640✔
659
               >= (unsigned long long)base_distance * 3ULL) {
660
        result = 7U;
661
    } else if ((unsigned long long)min_diff * 2ULL
10,388✔
662
               >= (unsigned long long)base_distance * 1ULL) {
663
        result = 4U;
664
    } else if ((unsigned long long)min_diff * 3ULL
9,916✔
665
               >= (unsigned long long)base_distance * 1ULL) {
666
        result = 2U;
667
    } else {
668
        result = 0U;
8,616✔
669
    }
670

671
    similarity->cache[cache_pos] = (signed char)result;
12,908✔
672

673
    return result;
12,908✔
674
}
675

676
static inline int
677
sixel_clamp(int value, int min_value, int max_value)
×
678
{
679
    if (value < min_value) {
×
680
        return min_value;
681
    }
682
    if (value > max_value) {
×
683
        return max_value;
684
    }
685
    return value;
686
}
687

688
static inline int
689
sixel_get_gray(const int *gray, int width, int height, int x, int y)
×
690
{
691
    int cx = sixel_clamp(x, 0, width - 1);
×
692
    int cy = sixel_clamp(y, 0, height - 1);
×
693
    return gray[cy * width + cx];
×
694
}
695

696
static unsigned short
697
sixel_prewitt_value(const int *gray, int width, int height, int x, int y)
×
698
{
699
    int top_prev = sixel_get_gray(gray, width, height, x - 1, y - 1);
×
700
    int top_curr = sixel_get_gray(gray, width, height, x, y - 1);
×
701
    int top_next = sixel_get_gray(gray, width, height, x + 1, y - 1);
×
702
    int mid_prev = sixel_get_gray(gray, width, height, x - 1, y);
×
703
    int mid_next = sixel_get_gray(gray, width, height, x + 1, y);
×
704
    int bot_prev = sixel_get_gray(gray, width, height, x - 1, y + 1);
×
705
    int bot_curr = sixel_get_gray(gray, width, height, x, y + 1);
×
706
    int bot_next = sixel_get_gray(gray, width, height, x + 1, y + 1);
×
707
    long gx = (long)top_next - (long)top_prev +
×
708
              (long)mid_next - (long)mid_prev +
×
709
              (long)bot_next - (long)bot_prev;
×
710
    long gy = (long)bot_prev + (long)bot_curr + (long)bot_next -
×
711
              (long)top_prev - (long)top_curr - (long)top_next;
×
712
    unsigned long long magnitude = (unsigned long long)gx
×
713
                                 * (unsigned long long)gx
×
714
                                 + (unsigned long long)gy
×
715
                                 * (unsigned long long)gy;
×
716
    magnitude /= 256ULL;
×
717
    if (magnitude > 65535ULL) {
×
718
        magnitude = 65535ULL;
×
719
    }
720
    return (unsigned short)magnitude;
×
721
}
722

723
static unsigned short
724
sixel_scale_threshold(unsigned short base, int percent)
8✔
725
{
726
    unsigned long long numerator;
8✔
727
    unsigned long long scaled;
8✔
728

729
    if (percent <= 0) {
8!
730
        percent = 1;
731
    }
732

733
    numerator = (unsigned long long)base * 100ULL
8✔
734
              + (unsigned long long)percent / 2ULL;
4✔
735
    scaled = numerator / (unsigned long long)percent;
8✔
736
    if (scaled == 0ULL) {
8!
737
        scaled = 1ULL;
738
    }
739
    if (scaled > USHRT_MAX) {
8!
740
        scaled = USHRT_MAX;
741
    }
742

743
    return (unsigned short)scaled;
8✔
744
}
745

746
static SIXELSTATUS
747
sixel_dequantize_k_undither(unsigned char *indexed_pixels,
4✔
748
                            int width,
749
                            int height,
750
                            unsigned char *palette,
751
                            int ncolors,
752
                            int similarity_bias,
753
                            int edge_strength,
754
                            sixel_allocator_t *allocator,
755
                            unsigned char **output)
756
{
757
    SIXELSTATUS status = SIXEL_FALSE;
4✔
758
    unsigned char *rgb = NULL;
4✔
759
    int *gray = NULL;
4✔
760
    unsigned short *prewitt = NULL;
4✔
761
    sixel_similarity_t similarity;
4✔
762
    size_t num_pixels;
4✔
763
    int x;
4✔
764
    int y;
4✔
765
    unsigned short strong_threshold;
4✔
766
    unsigned short detail_threshold;
4✔
767
    static const int neighbor_offsets[8][4] = {
4✔
768
        {-1, -1,  10, 16}, {0, -1, 16, 16}, {1, -1,   6, 16},
769
        {-1,  0,  11, 16},                  {1,  0,  11, 16},
770
        {-1,  1,   6, 16}, {0,  1, 16, 16}, {1,  1,  10, 16}
771
    };
772
    const unsigned char *color;
4✔
773
    size_t out_index;
4✔
774
    int palette_index;
4✔
775
    unsigned int center_weight;
4✔
776
    unsigned int total_weight = 0;
4✔
777
    unsigned int accum_r;
4✔
778
    unsigned int accum_g;
4✔
779
    unsigned int accum_b;
4✔
780
    unsigned short gradient;
4✔
781
    int neighbor;
4✔
782
    int nx;
4✔
783
    int ny;
4✔
784
    int numerator;
4✔
785
    int denominator;
4✔
786
    unsigned int weight;
4✔
787
    const unsigned char *neighbor_color;
4✔
788
    int neighbor_index;
4✔
789

790
    if (width <= 0 || height <= 0 || palette == NULL || ncolors <= 0) {
4!
791
        return SIXEL_BAD_INPUT;
792
    }
793

794
    num_pixels = (size_t)width * (size_t)height;
4✔
795

796
    memset(&similarity, 0, sizeof(sixel_similarity_t));
4!
797

798
    strong_threshold = sixel_scale_threshold(256U, edge_strength);
4!
799
    detail_threshold = sixel_scale_threshold(160U, edge_strength);
4!
800
    if (strong_threshold < detail_threshold) {
4!
801
        strong_threshold = detail_threshold;
802
    }
803

804
    /*
805
     * Build RGB and luminance buffers so we can reuse the similarity cache
806
     * and gradient analysis across the reconstructed image.
807
     */
808
    rgb = (unsigned char *)sixel_allocator_malloc(
4✔
809
        allocator,
810
        num_pixels * 3);
811
    if (rgb == NULL) {
4!
812
        sixel_helper_set_additional_message(
×
813
            "sixel_dequantize_k_undither: "
814
            "sixel_allocator_malloc() failed.");
815
        status = SIXEL_BAD_ALLOCATION;
×
816
        goto end;
×
817
    }
818

819
    gray = (int *)sixel_allocator_malloc(
4✔
820
        allocator,
821
        num_pixels * sizeof(int));
822
    if (gray == NULL) {
4!
823
        sixel_helper_set_additional_message(
×
824
            "sixel_dequantize_k_undither: "
825
            "sixel_allocator_malloc() failed.");
826
        status = SIXEL_BAD_ALLOCATION;
×
827
        goto end;
×
828
    }
829

830
    prewitt = (unsigned short *)sixel_allocator_malloc(
4✔
831
        allocator,
832
        num_pixels * sizeof(unsigned short));
833
    if (prewitt == NULL) {
4!
834
        sixel_helper_set_additional_message(
×
835
            "sixel_dequantize_k_undither: "
836
            "sixel_allocator_malloc() failed.");
837
        status = SIXEL_BAD_ALLOCATION;
×
838
        goto end;
×
839
    }
840

841
    /*
842
     * Pre-compute palette distance heuristics so each neighbour lookup reuses
843
     * the k_undither-style similarity table.
844
     */
845
    status = sixel_similarity_init(
4✔
846
        &similarity,
847
        palette,
848
        ncolors,
849
        similarity_bias,
850
        allocator);
851
    if (SIXEL_FAILED(status)) {
4!
852
        goto end;
×
853
    }
854

855
    for (y = 0; y < height; ++y) {
1,804✔
856
        for (x = 0; x < width; ++x) {
1,081,800✔
857
            palette_index = indexed_pixels[y * width + x];
1,080,000✔
858
            if (palette_index < 0 || palette_index >= ncolors) {
1,080,000!
859
                palette_index = 0;
×
860
            }
861

862
            color = palette + palette_index * 3;
1,080,000✔
863
            out_index = (size_t)(y * width + x) * 3;
1,080,000✔
864
            rgb[out_index + 0] = color[0];
1,080,000✔
865
            rgb[out_index + 1] = color[1];
1,080,000✔
866
            rgb[out_index + 2] = color[2];
1,080,000✔
867

868
            if (edge_strength > 0) {
1,080,000!
869
                gray[y * width + x] = (int)color[0]
×
870
                                    + (int)color[1] * 2
×
871
                                    + (int)color[2];
×
872
                /*
873
                 * Edge detection keeps high-frequency content intact while we
874
                 * smooth dithering noise in flatter regions.
875
                 */
876
                prewitt[y * width + x] = sixel_prewitt_value(
×
877
                    gray,
878
                    width,
879
                    height,
880
                    x,
881
                    y);
882

883
                gradient = prewitt[y * width + x];
×
884
                if (gradient > strong_threshold) {
×
885
                    continue;
×
886
                }
887

888
                if (gradient > detail_threshold) {
×
889
                    center_weight = 24U;
890
                } else {
891
                    center_weight = 8U;
1,080,000✔
892
                }
893
            } else {
894
                center_weight = 8U;
895
            }
896

897
            out_index = (size_t)(y * width + x) * 3;
1,080,000✔
898
            accum_r = (unsigned int)rgb[out_index + 0] * center_weight;
1,080,000✔
899
            accum_g = (unsigned int)rgb[out_index + 1] * center_weight;
1,080,000✔
900
            accum_b = (unsigned int)rgb[out_index + 2] * center_weight;
1,080,000✔
901
            total_weight = center_weight;
1,080,000✔
902

903
            /*
904
             * Blend neighbours that stay within the palette similarity
905
             * threshold so Floyd-Steinberg noise is averaged away without
906
             * bleeding across pronounced edges.
907
             */
908
            for (neighbor = 0; neighbor < 8; ++neighbor) {
9,720,000✔
909
                nx = x + neighbor_offsets[neighbor][0];
8,640,000✔
910
                ny = y + neighbor_offsets[neighbor][1];
8,640,000✔
911
                numerator = neighbor_offsets[neighbor][2];
8,640,000✔
912
                denominator = neighbor_offsets[neighbor][3];
8,640,000✔
913

914
                if (nx < 0 || nx >= width || ny < 0 || ny >= height) {
8,640,000✔
915
                    continue;
25,184✔
916
                }
917

918
                neighbor_index = indexed_pixels[ny * width + nx];
8,614,816✔
919
                if (neighbor_index < 0 || neighbor_index >= ncolors) {
8,614,816!
920
                    continue;
×
921
                }
922

923
                if (numerator) {
8,614,816!
924
                    weight = sixel_similarity_compare(
8,614,816✔
925
                        &similarity,
926
                        palette_index,
927
                        neighbor_index,
928
                        numerator,
929
                        denominator);
930
                    if (weight == 0) {
8,614,816✔
931
                        continue;
468,200✔
932
                    }
933

934
                    neighbor_color = palette + neighbor_index * 3;
8,146,616✔
935
                    accum_r += (unsigned int)neighbor_color[0] * weight;
8,146,616✔
936
                    accum_g += (unsigned int)neighbor_color[1] * weight;
8,146,616✔
937
                    accum_b += (unsigned int)neighbor_color[2] * weight;
8,146,616✔
938
                    total_weight += weight;
8,146,616✔
939
                }
940
            }
941

942
            if (total_weight > 0U) {
1,080,000!
943
                rgb[out_index + 0] = (unsigned char)(accum_r / total_weight);
1,080,000✔
944
                rgb[out_index + 1] = (unsigned char)(accum_g / total_weight);
1,080,000✔
945
                rgb[out_index + 2] = (unsigned char)(accum_b / total_weight);
1,080,000✔
946
            }
947
        }
948
    }
949

950

951
    *output = rgb;
4✔
952
    rgb = NULL;
4✔
953
    status = SIXEL_OK;
4✔
954

955
end:
4✔
956
    sixel_similarity_destroy(&similarity, allocator);
4!
957
    sixel_allocator_free(allocator, rgb);
4✔
958
    sixel_allocator_free(allocator, gray);
4✔
959
    sixel_allocator_free(allocator, prewitt);
4✔
960
    return status;
4✔
961
}
962
/*
963
 * The dequantizer accepts a method supplied by the shared option helper. The
964
 * decoder keeps a parallel lookup table that translates the matched index
965
 * into the execution constant.
966
 */
967
static int const g_decoder_dequant_methods[] = {
968
    SIXEL_DEQUANTIZE_NONE,
969
    SIXEL_DEQUANTIZE_K_UNDITHER
970
};
971

972
static sixel_option_choice_t const g_decoder_dequant_choices[] = {
973
    { "none", 0 },
974
    { "k_undither", 1 }
975
};
976

977
static void
978
decoder_normalise_windows_drive_path(char *path)
979
{
980
#if defined(_WIN32)
981
    size_t length;
982

983
    length = 0u;
984

985
    if (path == NULL) {
986
        return;
987
    }
988

989
    length = strlen(path);
990
    if (length >= 3u
991
            && path[0] == '/'
992
            && ((path[1] >= 'A' && path[1] <= 'Z')
993
                || (path[1] >= 'a' && path[1] <= 'z'))
994
            && path[2] == '/') {
995
        path[0] = path[1];
996
        path[1] = ':';
997
    }
998
#else
999
    (void)path;
1000
#endif
1001
}
1002

1003
/* set an option flag to decoder object */
1004
SIXELAPI SIXELSTATUS
1005
sixel_decoder_setopt(
132✔
1006
    sixel_decoder_t /* in */ *decoder,
1007
    int             /* in */ arg,
1008
    char const      /* in */ *value
1009
)
1010
{
1011
    SIXELSTATUS status = SIXEL_FALSE;
132✔
1012
    unsigned int path_flags;
132✔
1013
    int path_check;
132✔
1014
    char const *payload = NULL;
132✔
1015
    size_t length;
132✔
1016
    sixel_clipboard_spec_t clipboard_spec;
132✔
1017
    int match_index;
132✔
1018
    sixel_option_choice_result_t match_result;
132✔
1019
    char match_detail[128];
132✔
1020
    char match_message[256];
132✔
1021
    char const *filename = NULL;
132✔
1022
    char *p = NULL;
132✔
1023

1024
    sixel_decoder_ref(decoder);
132✔
1025
    path_flags = 0u;
132✔
1026
    path_check = 0;
132✔
1027

1028
    switch(arg) {
132!
1029
    case SIXEL_OPTFLAG_INPUT:  /* i */
52✔
1030
        path_flags = SIXEL_OPTION_PATH_ALLOW_STDIN |
52✔
1031
            SIXEL_OPTION_PATH_ALLOW_CLIPBOARD |
1032
            SIXEL_OPTION_PATH_ALLOW_REMOTE;
1033
        if (value != NULL) {
52!
1034
            path_check = sixel_option_validate_filesystem_path(
52✔
1035
                value,
1036
                value,
1037
                path_flags);
1038
            if (path_check != 0) {
52✔
1039
                status = SIXEL_BAD_ARGUMENT;
4✔
1040
                goto end;
4✔
1041
            }
1042
        }
1043
        decoder->clipboard_input_active = 0;
48✔
1044
        decoder->clipboard_input_format[0] = '\0';
48✔
1045
        if (value != NULL) {
48!
1046
            clipboard_spec.is_clipboard = 0;
48✔
1047
            clipboard_spec.format[0] = '\0';
48✔
1048
            if (sixel_clipboard_parse_spec(value, &clipboard_spec)
48!
1049
                    && clipboard_spec.is_clipboard) {
×
1050
                decoder_clipboard_select_format(
×
1051
                    decoder->clipboard_input_format,
×
1052
                    sizeof(decoder->clipboard_input_format),
1053
                    clipboard_spec.format,
1054
                    "sixel");
1055
                decoder->clipboard_input_active = 1;
×
1056
            }
1057
        }
1058
        free(decoder->input);
48✔
1059
        decoder->input = strdup_with_allocator(value, decoder->allocator);
48✔
1060
        if (decoder->input == NULL) {
48!
1061
            sixel_helper_set_additional_message(
×
1062
                "sixel_decoder_setopt: strdup_with_allocator() failed.");
1063
            status = SIXEL_BAD_ALLOCATION;
×
1064
            goto end;
×
1065
        }
1066
        break;
1067
    case SIXEL_OPTFLAG_OUTPUT:  /* o */
48✔
1068
        decoder->clipboard_output_active = 0;
48✔
1069
        decoder->clipboard_output_format[0] = '\0';
48✔
1070

1071
        payload = value;
48✔
1072
        if (strncmp(value, "png:", 4) == 0) {
48✔
1073
            payload = value + 4;
16✔
1074
            if (payload[0] == '\0') {
16✔
1075
                sixel_helper_set_additional_message(
4✔
1076
                    "missing target after the \"png:\" prefix.");
1077
                return SIXEL_BAD_ARGUMENT;
4✔
1078
            }
1079
            length = strlen(payload);
12✔
1080
            filename = p = malloc(length + 1U);
12✔
1081
            if (p == NULL) {
12!
1082
                sixel_helper_set_additional_message(
×
1083
                    "sixel_decoder_setopt: malloc() failed for png path filename.");
1084
                return SIXEL_BAD_ALLOCATION;
×
1085
            }
1086
            memcpy(p, payload, length + 1U);
12✔
1087
            decoder_normalise_windows_drive_path(p);
12✔
1088
        } else {
1089
            filename = value;
1090
        }
1091

1092
        if (filename != NULL) {
12!
1093
            clipboard_spec.is_clipboard = 0;
44✔
1094
            clipboard_spec.format[0] = '\0';
44✔
1095
            if (sixel_clipboard_parse_spec(filename, &clipboard_spec)
44!
1096
                    && clipboard_spec.is_clipboard) {
4!
1097
                decoder_clipboard_select_format(
4✔
1098
                    decoder->clipboard_output_format,
4✔
1099
                    sizeof(decoder->clipboard_output_format),
1100
                    clipboard_spec.format,
1101
                    "png");
1102
                decoder->clipboard_output_active = 1;
4✔
1103
            }
1104
        }
1105
        free(decoder->output);
44✔
1106
        decoder->output = strdup_with_allocator(filename, decoder->allocator);
44✔
1107
        free(p);
44✔
1108
        if (decoder->output == NULL) {
44!
1109
            sixel_helper_set_additional_message(
×
1110
                "sixel_decoder_setopt: strdup_with_allocator() failed.");
1111
            status = SIXEL_BAD_ALLOCATION;
×
1112
            goto end;
×
1113
        }
1114
        break;
1115
    case SIXEL_OPTFLAG_DEQUANTIZE:  /* d */
8✔
1116
        if (value == NULL) {
8!
1117
            sixel_helper_set_additional_message(
×
1118
                "sixel_decoder_setopt: -d/--dequantize requires an argument.");
1119
            status = SIXEL_BAD_ALLOCATION;
×
1120
            goto end;
×
1121
        }
1122

1123
        match_index = 0;
8✔
1124
        memset(match_detail, 0, sizeof(match_detail));
8✔
1125
        memset(match_message, 0, sizeof(match_message));
8✔
1126

1127
        match_result = sixel_option_match_choice(
8✔
1128
            value,
1129
            g_decoder_dequant_choices,
1130
            sizeof(g_decoder_dequant_choices) /
1131
            sizeof(g_decoder_dequant_choices[0]),
1132
            &match_index,
1133
            match_detail,
1134
            sizeof(match_detail));
1135
        if (match_result == SIXEL_OPTION_CHOICE_MATCH) {
8!
1136
            decoder->dequantize_method =
8✔
1137
                g_decoder_dequant_methods[match_index];
8✔
1138
        } else {
1139
            if (match_result == SIXEL_OPTION_CHOICE_AMBIGUOUS) {
×
1140
                sixel_option_report_ambiguous_prefix(
×
1141
                    value,
1142
                    match_detail,
1143
                    match_message,
1144
                    sizeof(match_message));
1145
            } else {
1146
                sixel_option_report_invalid_choice(
×
1147
                    "unsupported dequantize method.",
1148
                    match_detail,
1149
                    match_message,
1150
                    sizeof(match_message));
1151
            }
1152
            status = SIXEL_BAD_ARGUMENT;
×
1153
            goto end;
×
1154
        }
1155
        break;
8✔
1156

1157
    case SIXEL_OPTFLAG_SIMILARITY:  /* S */
1158
        decoder->dequantize_similarity_bias = atoi(value);
×
1159
        if (decoder->dequantize_similarity_bias < 0 ||
×
1160
            decoder->dequantize_similarity_bias > 1000) {
1161
            sixel_helper_set_additional_message(
×
1162
                "similarity must be between 1 and 1000.");
1163
            status = SIXEL_BAD_ARGUMENT;
×
1164
            goto end;
×
1165
        }
1166
        break;
1167

1168
    case SIXEL_OPTFLAG_SIZE:  /* s */
1169
        decoder->thumbnail_size = atoi(value);
×
1170
        if (decoder->thumbnail_size <= 0) {
×
1171
            sixel_helper_set_additional_message(
×
1172
                "size must be greater than zero.");
1173
            status = SIXEL_BAD_ARGUMENT;
×
1174
            goto end;
×
1175
        }
1176
        break;
1177

1178
    case SIXEL_OPTFLAG_EDGE:  /* e */
1179
        decoder->dequantize_edge_strength = atoi(value);
×
1180
        if (decoder->dequantize_edge_strength < 0 ||
×
1181
            decoder->dequantize_edge_strength > 1000) {
1182
            sixel_helper_set_additional_message(
×
1183
                "edge bias must be between 1 and 1000.");
1184
            status = SIXEL_BAD_ARGUMENT;
×
1185
            goto end;
×
1186
        }
1187
        break;
1188

1189
    case SIXEL_OPTFLAG_DIRECT:  /* D */
20✔
1190
        decoder->direct_color = 1;
20✔
1191
        break;
20✔
1192

1193
    case SIXEL_OPTFLAG_THREADS:  /* = */
4✔
1194
        status = sixel_decoder_parallel_override_threads(value);
4✔
1195
        if (SIXEL_FAILED(status)) {
4!
1196
            goto end;
4✔
1197
        }
1198
        break;
1199

1200
    case '?':
×
1201
    default:
1202
        status = SIXEL_BAD_ARGUMENT;
×
1203
        goto end;
×
1204
    }
1205

1206
    status = SIXEL_OK;
1207

1208
end:
128✔
1209
    sixel_decoder_unref(decoder);
128✔
1210

1211
    return status;
128✔
1212
}
1213

1214

1215
/* load source data from stdin or the file specified with
1216
   SIXEL_OPTFLAG_INPUT flag, and decode it */
1217
SIXELAPI SIXELSTATUS
1218
sixel_decoder_decode(
84✔
1219
    sixel_decoder_t /* in */ *decoder)
1220
{
1221
    SIXELSTATUS status = SIXEL_FALSE;
84✔
1222
    unsigned char *raw_data = NULL;
84✔
1223
    int sx;
84✔
1224
    int sy;
84✔
1225
    int raw_len;
84✔
1226
    int max;
84✔
1227
    int n;
84✔
1228
    FILE *input_fp = NULL;
84✔
1229
    char message[2048];
84✔
1230
    unsigned char *indexed_pixels = NULL;
84✔
1231
    unsigned char *palette = NULL;
84✔
1232
    unsigned char *rgb_pixels = NULL;
84✔
1233
    unsigned char *direct_pixels = NULL;
84✔
1234
    unsigned char *output_pixels;
84✔
1235
    unsigned char *output_palette;
84✔
1236
    int output_pixelformat;
84✔
1237
    int ncolors;
84✔
1238
    sixel_frame_t *frame;
84✔
1239
    int new_width;
84✔
1240
    int new_height;
84✔
1241
    double scaled_width;
84✔
1242
    double scaled_height;
84✔
1243
    int max_dimension;
84✔
1244
    int thumbnail_size;
84✔
1245
    int frame_ncolors;
84✔
1246
    unsigned char *clipboard_blob;
84✔
1247
    size_t clipboard_blob_size;
84✔
1248
    SIXELSTATUS clipboard_status;
84✔
1249
    char *clipboard_output_path;
84✔
1250
    unsigned char *clipboard_output_data;
84✔
1251
    size_t clipboard_output_size;
84✔
1252
    SIXELSTATUS clipboard_output_status;
84✔
1253
    sixel_logger_t logger;
84✔
1254
    int logger_prepared;
84✔
1255

1256
    sixel_decoder_ref(decoder);
84✔
1257

1258
    frame = NULL;
84✔
1259
    new_width = 0;
84✔
1260
    new_height = 0;
84✔
1261
    scaled_width = 0.0;
84✔
1262
    scaled_height = 0.0;
84✔
1263
    max_dimension = 0;
84✔
1264
    thumbnail_size = decoder->thumbnail_size;
84✔
1265
    frame_ncolors = -1;
84✔
1266
    clipboard_blob = NULL;
84✔
1267
    clipboard_blob_size = 0u;
84✔
1268
    clipboard_status = SIXEL_OK;
84✔
1269
    clipboard_output_path = NULL;
84✔
1270
    clipboard_output_data = NULL;
84✔
1271
    clipboard_output_size = 0u;
84✔
1272
    clipboard_output_status = SIXEL_OK;
84✔
1273
    input_fp = NULL;
84✔
1274
    sixel_logger_init(&logger);
84✔
1275
    (void)sixel_logger_prepare_env(&logger);
84✔
1276
    logger_prepared = logger.active;
84✔
1277

1278
    raw_len = 0;
84✔
1279
    max = 0;
84✔
1280
    if (decoder->clipboard_input_active) {
84!
1281
        clipboard_status = sixel_clipboard_read(
×
1282
            decoder->clipboard_input_format,
×
1283
            &clipboard_blob,
1284
            &clipboard_blob_size,
1285
            decoder->allocator);
1286
        if (SIXEL_FAILED(clipboard_status)) {
×
1287
            status = clipboard_status;
×
1288
            goto end;
×
1289
        }
1290
        max = (int)((clipboard_blob_size > 0u)
×
1291
                    ? clipboard_blob_size
1292
                    : 1u);
1293
        raw_data = (unsigned char *)sixel_allocator_malloc(
×
1294
            decoder->allocator,
1295
            (size_t)max);
1296
        if (raw_data == NULL) {
×
1297
            sixel_helper_set_additional_message(
×
1298
                "sixel_decoder_decode: sixel_allocator_malloc() failed.");
1299
            status = SIXEL_BAD_ALLOCATION;
×
1300
            goto end;
×
1301
        }
1302
        if (clipboard_blob_size > 0u && clipboard_blob != NULL) {
×
1303
            memcpy(raw_data, clipboard_blob, clipboard_blob_size);
×
1304
        }
1305
        raw_len = (int)clipboard_blob_size;
×
1306
        if (clipboard_blob != NULL) {
×
1307
            free(clipboard_blob);
×
1308
            clipboard_blob = NULL;
×
1309
        }
1310
    } else {
1311
        if (strcmp(decoder->input, "-") == 0) {
84✔
1312
            /* for windows */
1313
#if defined(O_BINARY)
1314
            (void)sixel_compat_set_binary(STDIN_FILENO);
1315
#endif  /* defined(O_BINARY) */
1316
            input_fp = stdin;
52✔
1317
        } else {
1318
            input_fp = sixel_compat_fopen(decoder->input, "rb");
32✔
1319
            if (! input_fp) {
32!
1320
                (void)snprintf(
×
1321
                    message,
1322
                    sizeof(message) - 1,
1323
                    "sixel_decoder_decode: failed to open input file: %s.",
1324
                    decoder->input);
1325
                sixel_helper_set_additional_message(message);
×
1326
                status = (SIXEL_LIBC_ERROR | (errno & 0xff));
×
1327
                goto end;
×
1328
            }
1329
        }
1330

1331
        raw_len = 0;
84✔
1332
        max = 64 * 1024;
84✔
1333

1334
        raw_data = (unsigned char *)sixel_allocator_malloc(
84✔
1335
            decoder->allocator,
1336
            (size_t)max);
1337
        if (raw_data == NULL) {
84!
1338
            sixel_helper_set_additional_message(
×
1339
                "sixel_decoder_decode: sixel_allocator_malloc() failed.");
1340
            status = SIXEL_BAD_ALLOCATION;
×
1341
            goto end;
×
1342
        }
1343

1344
        for (;;) {
18,806✔
1345
            if ((max - raw_len) < 4096) {
9,445✔
1346
                max *= 2;
164✔
1347
                raw_data = (unsigned char *)sixel_allocator_realloc(
164✔
1348
                    decoder->allocator,
1349
                    raw_data,
1350
                    (size_t)max);
1351
                if (raw_data == NULL) {
164!
1352
                    sixel_helper_set_additional_message(
×
1353
                        "sixel_decoder_decode: sixel_allocator_realloc() failed.");
1354
                    status = SIXEL_BAD_ALLOCATION;
×
1355
                    goto end;
×
1356
                }
1357
            }
1358
            if ((n = (int)fread(raw_data + raw_len, 1, 4096, input_fp)) <= 0) {
18,890!
1359
                break;
1360
            }
1361
            raw_len += n;
9,361✔
1362
        }
1363

1364
        if (input_fp != NULL && input_fp != stdin) {
84!
1365
            fclose(input_fp);
32✔
1366
        }
1367
    }
1368

1369
    if (decoder->direct_color != 0 &&
84✔
1370
            decoder->dequantize_method != SIXEL_DEQUANTIZE_NONE) {
20✔
1371
        sixel_helper_set_additional_message(
4✔
1372
            "sixel_decoder_decode: direct option "
1373
            "cannot be combined with dequantize option.");
1374
        status = SIXEL_BAD_ARGUMENT;
4✔
1375
        goto end;
4✔
1376
    }
1377

1378
    ncolors = 0;
80✔
1379

1380
    if (decoder->direct_color != 0) {
80✔
1381
        status = sixel_decode_direct(
16✔
1382
            raw_data,
1383
            raw_len,
1384
            &direct_pixels,
1385
            &sx,
1386
            &sy,
1387
            decoder->allocator);
1388
    } else {
1389
        status = sixel_decode_raw(
64✔
1390
            raw_data,
1391
            raw_len,
1392
            &indexed_pixels,
1393
            &sx,
1394
            &sy,
1395
            &palette,
1396
            &ncolors,
1397
            decoder->allocator);
1398
    }
1399
    if (SIXEL_FAILED(status)) {
80!
1400
        goto end;
×
1401
    }
1402

1403
    if (sx > SIXEL_WIDTH_LIMIT || sy > SIXEL_HEIGHT_LIMIT) {
80!
1404
        status = SIXEL_BAD_INPUT;
×
1405
        goto end;
×
1406
    }
1407

1408
    if (decoder->direct_color != 0) {
80✔
1409
        output_pixels = direct_pixels;
16✔
1410
        output_palette = NULL;
16✔
1411
        output_pixelformat = SIXEL_PIXELFORMAT_RGBA8888;
16✔
1412
        frame_ncolors = 0;
16✔
1413
    } else {
1414
        output_pixels = indexed_pixels;
64✔
1415
        output_palette = palette;
64✔
1416
        output_pixelformat = SIXEL_PIXELFORMAT_PAL8;
64✔
1417

1418
        if (decoder->dequantize_method == SIXEL_DEQUANTIZE_K_UNDITHER) {
64✔
1419
            if (logger_prepared) {
4!
1420
                sixel_logger_logf(&logger,
×
1421
                                  "decoder",
1422
                                  "undither",
1423
                                  "start",
1424
                                  0,
1425
                                  0,
1426
                                  0,
1427
                                  sy,
1428
                                  0,
1429
                                  sx,
1430
                                  "k_undither begin %dx%d palette=%d",
1431
                                  sx,
1432
                                  sy,
1433
                                  ncolors);
1434
            }
1435
            status = sixel_dequantize_k_undither(
4✔
1436
                indexed_pixels,
1437
                sx,
1438
                sy,
1439
                palette,
1440
                ncolors,
1441
                decoder->dequantize_similarity_bias,
1442
                decoder->dequantize_edge_strength,
1443
                decoder->allocator,
1444
                &rgb_pixels);
1445
            if (SIXEL_FAILED(status)) {
4!
1446
                if (logger_prepared) {
×
1447
                    sixel_logger_logf(
×
1448
                        &logger,
1449
                        "decoder",
1450
                        "undither",
1451
                        "abort",
1452
                        0,
1453
                        0,
1454
                        0,
1455
                        sy,
1456
                        0,
1457
                        sx,
1458
                        "k_undither failed status=%d",
1459
                        status);
1460
                }
1461
                goto end;
×
1462
            }
1463
            if (logger_prepared) {
4!
1464
                sixel_logger_logf(&logger,
×
1465
                                  "decoder",
1466
                                  "undither",
1467
                                  "finish",
1468
                                  0,
1469
                                  0,
1470
                                  0,
1471
                                  sy,
1472
                                  0,
1473
                                  sx,
1474
                                  "k_undither complete %dx%d",
1475
                                  sx,
1476
                                  sy);
1477
            }
1478
            output_pixels = rgb_pixels;
4✔
1479
            output_palette = NULL;
4✔
1480
            output_pixelformat = SIXEL_PIXELFORMAT_RGB888;
4✔
1481
        }
1482

1483
        if (output_pixelformat == SIXEL_PIXELFORMAT_PAL8) {
4✔
1484
            frame_ncolors = ncolors;
60✔
1485
        } else {
1486
            frame_ncolors = 0;
1487
        }
1488
    }
1489

1490
    if (thumbnail_size > 0) {
80!
1491
        /*
1492
         * When the caller requests a thumbnail, compute the new geometry
1493
         * while preserving the original aspect ratio. We only allocate a
1494
         * frame when the dimensions actually change, so the fast path for
1495
         * matching sizes still avoids any additional allocations.
1496
         */
1497
        max_dimension = sx;
×
1498
        if (sy > max_dimension) {
×
1499
            max_dimension = sy;
1500
        }
1501
        if (max_dimension > 0) {
×
1502
            if (sx >= sy) {
×
1503
                new_width = thumbnail_size;
×
1504
                scaled_height = (double)sy * (double)thumbnail_size /
×
1505
                    (double)sx;
×
1506
                new_height = (int)(scaled_height + 0.5);
×
1507
            } else {
1508
                new_height = thumbnail_size;
×
1509
                scaled_width = (double)sx * (double)thumbnail_size /
×
1510
                    (double)sy;
×
1511
                new_width = (int)(scaled_width + 0.5);
×
1512
            }
1513
            if (new_width < 1) {
×
1514
                new_width = 1;
1515
            }
1516
            if (new_height < 1) {
×
1517
                new_height = 1;
1518
            }
1519
            if (new_width != sx || new_height != sy) {
×
1520
                /*
1521
                 * Wrap the decoded pixels in a frame so we can reuse the
1522
                 * central scaling helper. Ownership transfers to the frame,
1523
                 * which keeps the lifetime rules identical on both paths.
1524
                 */
1525
                status = sixel_frame_new(&frame, decoder->allocator);
×
1526
                if (SIXEL_FAILED(status)) {
×
1527
                    goto end;
×
1528
                }
1529
                status = sixel_frame_init(
×
1530
                    frame,
1531
                    output_pixels,
1532
                    sx,
1533
                    sy,
1534
                    output_pixelformat,
1535
                    output_palette,
1536
                    frame_ncolors);
1537
                if (SIXEL_FAILED(status)) {
×
1538
                    goto end;
×
1539
                }
1540
                if (output_pixels == indexed_pixels) {
×
1541
                    indexed_pixels = NULL;
×
1542
                }
1543
                if (output_pixels == rgb_pixels) {
×
1544
                    rgb_pixels = NULL;
×
1545
                }
1546
                if (output_palette == palette) {
×
1547
                    palette = NULL;
×
1548
                }
1549
                status = sixel_frame_resize(
×
1550
                    frame,
1551
                    new_width,
1552
                    new_height,
1553
                    SIXEL_RES_BILINEAR);
1554
                if (SIXEL_FAILED(status)) {
×
1555
                    goto end;
×
1556
                }
1557
                /*
1558
                 * The resized frame already exposes a tightly packed RGB
1559
                 * buffer, so write the updated dimensions and references
1560
                 * back to the main encoder path.
1561
                 */
1562
                sx = sixel_frame_get_width(frame);
×
1563
                sy = sixel_frame_get_height(frame);
×
1564
                output_pixels = sixel_frame_get_pixels(frame);
×
1565
                output_palette = NULL;
×
1566
                output_pixelformat = sixel_frame_get_pixelformat(frame);
×
1567
            }
1568
        }
1569
    }
1570

1571
    if (decoder->clipboard_output_active) {
80✔
1572
        clipboard_output_status = decoder_clipboard_create_spool(
4✔
1573
            decoder->allocator,
1574
            "clipboard-out",
1575
            &clipboard_output_path);
1576
        if (SIXEL_FAILED(clipboard_output_status)) {
4!
1577
            status = clipboard_output_status;
×
1578
            goto end;
×
1579
        }
1580
    }
1581

1582
    if (logger_prepared) {
80!
1583
        sixel_logger_logf(&logger,
×
1584
                          "io",
1585
                          "png",
1586
                          "start",
1587
                          0,
1588
                          0,
1589
                          0,
1590
                          sy,
1591
                          0,
1592
                          sx,
1593
                          "png output begin %dx%d format=%d",
1594
                          sx,
1595
                          sy,
1596
                          output_pixelformat);
1597
    }
1598
    status = sixel_helper_write_image_file(
80✔
1599
        output_pixels,
1600
        sx,
1601
        sy,
1602
        output_palette,
1603
        output_pixelformat,
1604
        decoder->clipboard_output_active
80✔
1605
            ? clipboard_output_path
1606
            : decoder->output,
1607
        SIXEL_FORMAT_PNG,
1608
        decoder->allocator);
1609
    if (SIXEL_FAILED(status)) {
80!
1610
        if (logger_prepared) {
×
1611
            sixel_logger_logf(&logger,
×
1612
                              "io",
1613
                              "png",
1614
                              "abort",
1615
                              0,
1616
                              0,
1617
                              0,
1618
                              sy,
1619
                              0,
1620
                              sx,
1621
                              "png output failed status=%d",
1622
                              status);
1623
        }
1624
        goto end;
×
1625
    }
1626
    if (logger_prepared) {
80!
1627
        sixel_logger_logf(&logger,
×
1628
                          "io",
1629
                          "png",
1630
                          "finish",
1631
                          0,
1632
                          0,
1633
                          0,
1634
                          sy,
1635
                          0,
1636
                          sx,
1637
                          "png output complete %dx%d",
1638
                          sx,
1639
                          sy);
1640
    }
1641

1642
    if (decoder->clipboard_output_active) {
80✔
1643
        clipboard_output_status = decoder_clipboard_read_file(
4✔
1644
            clipboard_output_path,
1645
            &clipboard_output_data,
1646
            &clipboard_output_size);
1647
        if (SIXEL_SUCCEEDED(clipboard_output_status)) {
4!
1648
            clipboard_output_status = sixel_clipboard_write(
4✔
1649
                decoder->clipboard_output_format,
4✔
1650
                clipboard_output_data,
1651
                clipboard_output_size);
1652
        }
1653
        if (clipboard_output_data != NULL) {
4!
1654
            free(clipboard_output_data);
4✔
1655
            clipboard_output_data = NULL;
4✔
1656
        }
1657
        if (SIXEL_FAILED(clipboard_output_status)) {
4!
1658
            status = clipboard_output_status;
4✔
1659
            goto end;
4✔
1660
        }
1661
    }
1662

1663
end:
76✔
1664
    sixel_frame_unref(frame);
84✔
1665
    sixel_allocator_free(decoder->allocator, raw_data);
84✔
1666
    sixel_allocator_free(decoder->allocator, indexed_pixels);
84✔
1667
    sixel_allocator_free(decoder->allocator, palette);
84✔
1668
    sixel_allocator_free(decoder->allocator, direct_pixels);
84✔
1669
    sixel_allocator_free(decoder->allocator, rgb_pixels);
84✔
1670
    if (clipboard_blob != NULL) {
84!
1671
        free(clipboard_blob);
×
1672
    }
1673
    if (clipboard_output_path != NULL) {
84✔
1674
        (void)sixel_compat_unlink(clipboard_output_path);
4✔
1675
        sixel_allocator_free(decoder->allocator, clipboard_output_path);
4✔
1676
    }
1677

1678
    sixel_decoder_unref(decoder);
84✔
1679
    if (logger_prepared) {
84!
1680
        sixel_logger_close(&logger);
×
1681
    }
1682

1683
    return status;
84✔
1684
}
1685

1686

1687
/* Exercise legacy constructor and refcounting for the decoder. */
1688
#if HAVE_TESTS
1689
static int
1690
decoder_test_create_legacy(void)
×
1691
{
1692
    int nret = EXIT_FAILURE;
×
1693
    sixel_decoder_t *decoder = NULL;
×
1694

1695
#if HAVE_DIAGNOSTIC_DEPRECATED_DECLARATIONS
1696
#  pragma GCC diagnostic push
1697
#  pragma GCC diagnostic ignored "-Wdeprecated-declarations"
1698
#endif
1699
    decoder = sixel_decoder_create();
×
1700
#if HAVE_DIAGNOSTIC_DEPRECATED_DECLARATIONS
1701
#  pragma GCC diagnostic pop
1702
#endif
1703
    if (decoder == NULL) {
×
1704
        goto error;
×
1705
    }
1706
    sixel_decoder_ref(decoder);
×
1707
    sixel_decoder_unref(decoder);
×
1708
    nret = EXIT_SUCCESS;
×
1709

1710
error:
×
1711
    sixel_decoder_unref(decoder);
×
1712
    return nret;
×
1713
}
1714

1715

1716
/* Build a decoder with the default allocator and ensure cleanup paths work. */
1717
static int
1718
decoder_test_new_with_default_allocator(void)
×
1719
{
1720
    int nret = EXIT_FAILURE;
×
1721
    sixel_decoder_t *decoder = NULL;
×
1722
    SIXELSTATUS status;
×
1723

1724
    status = sixel_decoder_new(&decoder, NULL);
×
1725
    if (SIXEL_FAILED(status)) {
×
1726
        goto error;
×
1727
    }
1728

1729
    sixel_decoder_ref(decoder);
×
1730
    sixel_decoder_unref(decoder);
×
1731
    nret = EXIT_SUCCESS;
×
1732

1733
error:
×
1734
    sixel_decoder_unref(decoder);
×
1735
    return nret;
×
1736
}
1737

1738

1739
/* Verify allocation failure during construction bubbles up. */
1740
static int
1741
decoder_test_allocator_failure_on_new(void)
×
1742
{
1743
    int nret = EXIT_FAILURE;
×
1744
    sixel_decoder_t *decoder = NULL;
×
1745
    sixel_allocator_t *allocator = NULL;
×
1746
    SIXELSTATUS status;
×
1747

1748
    sixel_debug_malloc_counter = 1;
×
1749

1750
    status = sixel_allocator_new(
×
1751
        &allocator,
1752
        sixel_bad_malloc,
1753
        NULL,
1754
        NULL,
1755
        NULL);
1756
    if (SIXEL_FAILED(status)) {
×
1757
        goto error;
×
1758
    }
1759

1760
    status = sixel_decoder_new(&decoder, allocator);
×
1761
    if (status != SIXEL_BAD_ALLOCATION) {
×
1762
        goto error;
×
1763
    }
1764

1765
    nret = EXIT_SUCCESS;
1766

1767
error:
×
1768
    return nret;
×
1769
}
1770

1771

1772
/* Trigger allocation failure on the second allocation path in new(). */
1773
static int
1774
decoder_test_allocator_failure_on_new_second(void)
×
1775
{
1776
    int nret = EXIT_FAILURE;
×
1777
    sixel_decoder_t *decoder = NULL;
×
1778
    sixel_allocator_t *allocator = NULL;
×
1779
    SIXELSTATUS status;
×
1780

1781
    sixel_debug_malloc_counter = 2;
×
1782

1783
    status = sixel_allocator_new(
×
1784
        &allocator,
1785
        sixel_bad_malloc,
1786
        NULL,
1787
        NULL,
1788
        NULL);
1789
    if (SIXEL_FAILED(status)) {
×
1790
        goto error;
×
1791
    }
1792

1793
    status = sixel_decoder_new(&decoder, allocator);
×
1794
    if (status != SIXEL_BAD_ALLOCATION) {
×
1795
        goto error;
×
1796
    }
1797

1798
    nret = EXIT_SUCCESS;
1799

1800
error:
×
1801
    return nret;
×
1802
}
1803

1804

1805
/*
1806
 * Force allocation failure when setting the input path on a decoder created
1807
 * with failing allocator hooks.
1808
 */
1809
static int
1810
decoder_test_setopt_input_allocation_failure(void)
×
1811
{
1812
    int nret = EXIT_FAILURE;
×
1813
    sixel_decoder_t *decoder = NULL;
×
1814
    sixel_allocator_t *allocator = NULL;
×
1815
    SIXELSTATUS status;
×
1816

1817
    sixel_debug_malloc_counter = 4;
×
1818

1819
    status = sixel_allocator_new(
×
1820
        &allocator,
1821
        sixel_bad_malloc,
1822
        NULL,
1823
        NULL,
1824
        NULL);
1825
    if (SIXEL_FAILED(status)) {
×
1826
        goto error;
×
1827
    }
1828
    status = sixel_decoder_new(&decoder, allocator);
×
1829
    if (SIXEL_FAILED(status)) {
×
1830
        goto error;
×
1831
    }
1832

1833
    status = sixel_decoder_setopt(
×
1834
        decoder,
1835
        SIXEL_OPTFLAG_INPUT,
1836
        "/");
1837
    if (status != SIXEL_BAD_ALLOCATION) {
×
1838
        goto error;
×
1839
    }
1840

1841
    nret = EXIT_SUCCESS;
1842

1843
error:
×
1844
    return nret;
×
1845
}
1846

1847

1848
/*
1849
 * Force allocation failure when setting the output path on a decoder created
1850
 * with failing allocator hooks.
1851
 */
1852
static int
1853
decoder_test_setopt_output_allocation_failure(void)
×
1854
{
1855
    int nret = EXIT_FAILURE;
×
1856
    sixel_decoder_t *decoder = NULL;
×
1857
    sixel_allocator_t *allocator = NULL;
×
1858
    SIXELSTATUS status;
×
1859

1860
    sixel_debug_malloc_counter = 4;
×
1861

1862
    status = sixel_allocator_new(
×
1863
        &allocator,
1864
        sixel_bad_malloc,
1865
        NULL,
1866
        NULL,
1867
        NULL);
1868
    if (SIXEL_FAILED(status)) {
×
1869
        goto error;
×
1870
    }
1871

1872
    status = sixel_decoder_new(&decoder, allocator);
×
1873
    if (SIXEL_FAILED(status)) {
×
1874
        goto error;
×
1875
    }
1876

1877
    status = sixel_decoder_setopt(
×
1878
        decoder,
1879
        SIXEL_OPTFLAG_OUTPUT,
1880
        "/");
1881
    if (status != SIXEL_BAD_ALLOCATION) {
×
1882
        goto error;
×
1883
    }
1884

1885
    nret = EXIT_SUCCESS;
1886

1887
error:
×
1888
    return nret;
×
1889
}
1890

1891

1892
/* Verify decode reports libc error when input path is invalid. */
1893
static int
1894
decoder_test_decode_missing_file(void)
×
1895
{
1896
    int nret = EXIT_FAILURE;
×
1897
    sixel_decoder_t *decoder = NULL;
×
1898
    sixel_allocator_t *allocator = NULL;
×
1899
    SIXELSTATUS status;
×
1900

1901
    status = sixel_allocator_new(
×
1902
        &allocator,
1903
        NULL,
1904
        NULL,
1905
        NULL,
1906
        NULL);
1907
    if (SIXEL_FAILED(status)) {
×
1908
        goto error;
×
1909
    }
1910

1911
    status = sixel_decoder_new(&decoder, allocator);
×
1912
    if (SIXEL_FAILED(status)) {
×
1913
        goto error;
×
1914
    }
1915

1916
    status = sixel_decoder_setopt(
×
1917
        decoder,
1918
        SIXEL_OPTFLAG_INPUT,
1919
        "../images/file");
1920
    if (SIXEL_FAILED(status)) {
×
1921
        goto error;
×
1922
    }
1923

1924
    status = sixel_decoder_decode(decoder);
×
1925
    if ((status >> 8) != (SIXEL_LIBC_ERROR >> 8)) {
×
1926
        goto error;
×
1927
    }
1928

1929
    nret = EXIT_SUCCESS;
1930

1931
error:
×
1932
    return nret;
×
1933
}
1934

1935

1936
/* Ensure decode surfaces allocator failures when reading a real file. */
1937
static int
1938
decoder_test_decode_allocation_failure(void)
×
1939
{
1940
    int nret = EXIT_FAILURE;
×
1941
    sixel_decoder_t *decoder = NULL;
×
1942
    sixel_allocator_t *allocator = NULL;
×
1943
    SIXELSTATUS status;
×
1944

1945
    sixel_debug_malloc_counter = 5;
×
1946

1947
    status = sixel_allocator_new(
×
1948
        &allocator,
1949
        sixel_bad_malloc,
1950
        NULL,
1951
        NULL,
1952
        NULL);
1953
    if (SIXEL_FAILED(status)) {
×
1954
        goto error;
×
1955
    }
1956

1957
    status = sixel_decoder_new(&decoder, allocator);
×
1958
    if (SIXEL_FAILED(status)) {
×
1959
        goto error;
×
1960
    }
1961

1962
    status = sixel_decoder_setopt(
×
1963
        decoder,
1964
        SIXEL_OPTFLAG_INPUT,
1965
        "../images/map8.six");
1966
    if (SIXEL_FAILED(status)) {
×
1967
        goto error;
×
1968
    }
1969

1970
    status = sixel_decoder_decode(decoder);
×
1971
    if (status != SIXEL_BAD_ALLOCATION) {
×
1972
        goto error;
×
1973
    }
1974

1975
    nret = EXIT_SUCCESS;
1976

1977
error:
×
1978
    return nret;
×
1979
}
1980

1981

1982
SIXELAPI int
1983
sixel_decoder_tests_main(void)
×
1984
{
1985
    int nret = EXIT_FAILURE;
×
1986
    size_t i;
×
1987
    typedef int (* testcase)(void);
×
1988

1989
    static testcase const testcases[] = {
×
1990
        decoder_test_create_legacy,
1991
        decoder_test_new_with_default_allocator,
1992
        decoder_test_allocator_failure_on_new,
1993
        decoder_test_allocator_failure_on_new_second,
1994
        decoder_test_setopt_input_allocation_failure,
1995
        decoder_test_setopt_output_allocation_failure,
1996
        decoder_test_decode_missing_file,
1997
        decoder_test_decode_allocation_failure
1998
    };
1999

2000
    for (i = 0; i < sizeof(testcases) / sizeof(testcase); ++i) {
×
2001
        nret = testcases[i]();
×
2002
        if (nret != EXIT_SUCCESS) {
×
2003
            goto error;
×
2004
        }
2005
    }
2006

2007
    nret = EXIT_SUCCESS;
2008

2009
error:
×
2010
    return nret;
×
2011
}
2012
#endif  /* HAVE_TESTS */
2013

2014
/* emacs Local Variables:      */
2015
/* emacs mode: c               */
2016
/* emacs tab-width: 4          */
2017
/* emacs indent-tabs-mode: nil */
2018
/* emacs c-basic-offset: 4     */
2019
/* emacs End:                  */
2020
/* vim: set expandtab ts=4 sts=4 sw=4 : */
2021
/* EOF */
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc