-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathfastchart_encoder.c
More file actions
772 lines (695 loc) · 24 KB
/
Copy pathfastchart_encoder.c
File metadata and controls
772 lines (695 loc) · 24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
/*
+----------------------------------------------------------------------+
| Copyright (c) 2025-2026, Ilia Alshanetsky |
| Copyright (c) 2025-2026, Advanced Internet Designs Inc. |
+----------------------------------------------------------------------+
| This source file is subject to the BSD 3-Clause license that is |
| bundled with this package in the file LICENSE. |
+----------------------------------------------------------------------+
| Author: Ilia Alshanetsky <ilia@ilia.ws> |
+----------------------------------------------------------------------+
Raster encoders: RGBA pixel buffer -> PNG / JPEG / WebP, written to
a caller-owned sink.
libpng: the high-level API (png_set_compression_level default
6, RGBA streamed row by row).
libjpeg-turbo: optimize_coding TRUE, 4:2:0 subsampling, non-progressive.
Matches the q88 reference established in the plutovg
quality-eval; RGB ingest, alpha is flattened over white
since JPEG has no alpha channel.
libwebp: WebPEncodeRGBA simple API for lossy at quality q;
alpha preserved.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "fastchart_encoder.h"
#include "zend_smart_str.h"
#ifdef HAVE_LIBPNG
#include <png.h>
#endif
#ifdef HAVE_LIBJPEG
#include <jpeglib.h>
#include <jerror.h>
#endif
#ifdef HAVE_LIBWEBP
#include <webp/encode.h>
#endif
#include <setjmp.h>
#include <string.h>
#include <stdlib.h>
/* EG(timed_out) became zend_atomic_bool in 8.2 (php/php-src#8327);
* on 8.1 it is sig_atomic_t, so read it directly. */
#if PHP_VERSION_ID >= 80200
#define FC_TIMED_OUT() zend_atomic_bool_load_ex(&EG(timed_out))
#else
#define FC_TIMED_OUT() EG(timed_out)
#endif
/* Same SIMD gates as fastchart_rasterize.c: x86 uses SSSE3 runtime
* dispatch via raw CPUID (see the rationale there — __builtin_cpu_supports
* drags in libgcc's __cpu_model and breaks static/musl/zig dlopen);
* AArch64 uses baseline NEON. */
#if (defined(__x86_64__) || defined(_M_X64)) && defined(__GNUC__)
# define FC_ENC_HAVE_X86_SIMD 1
# include <immintrin.h>
# include <cpuid.h>
#endif
#if defined(__aarch64__) && (defined(__ARM_NEON) || defined(__ARM_NEON__))
# define FC_ENC_HAVE_ARM_NEON 1
# include <arm_neon.h>
#endif
#ifdef FC_ENC_HAVE_X86_SIMD
static int fc_enc_cpu_has_ssse3(void)
{
static int cached = -1;
if (cached < 0) {
unsigned int eax, ebx, ecx, edx;
cached = (__get_cpuid(1, &eax, &ebx, &ecx, &edx)
&& (ecx & bit_SSSE3)) ? 1 : 0;
}
return cached;
}
#ifdef HAVE_LIBJPEG
/* Pack `n_pixels` opaque RGBA pixels at src into RGB at dst via SSSE3
* _mm_shuffle_epi8 (4 pixels per instruction). Returns the count of
* pixels processed (always a multiple of 4); the caller handles the
* remainder with scalar copies. dst must have at least 16 bytes of
* trailing slack so the 16-byte store on the final chunk can overrun
* its 12 valid bytes without touching unowned memory. */
__attribute__((target("ssse3")))
static int fc_enc_pack_rgba_to_rgb_ssse3(const uint8_t *src, uint8_t *dst,
int n_pixels)
{
static const int8_t shuf_bytes[16] = {
0, 1, 2,
4, 5, 6,
8, 9, 10,
12, 13, 14,
-1, -1, -1, -1 /* upper 4 lanes are don't-care */
};
__m128i shuf = _mm_loadu_si128((const __m128i *)shuf_bytes);
int simd_end = n_pixels & ~3;
for (int x = 0; x < simd_end; x += 4) {
__m128i rgba = _mm_loadu_si128(
(const __m128i *)(src + (size_t)x * 4));
__m128i rgb = _mm_shuffle_epi8(rgba, shuf);
_mm_storeu_si128((__m128i *)(dst + (size_t)x * 3), rgb);
}
return simd_end;
}
#endif
#endif
#if defined(HAVE_LIBJPEG) && defined(FC_ENC_HAVE_ARM_NEON)
/* Keep the NEON helper outside libjpeg's setjmp frame; AArch64 GCC can
* otherwise warn about clobbered vector temporaries when it inlines this. */
__attribute__((noinline))
static int fc_enc_pack_rgba_to_rgb_neon(const uint8_t *src, uint8_t *dst,
int n_pixels)
{
int simd_end = n_pixels & ~15; /* 16 RGBA pixels -> 48 RGB bytes */
for (int x = 0; x < simd_end; x += 16) {
uint8x16x4_t rgba = vld4q_u8(src + (size_t)x * 4);
uint8x16x3_t rgb;
rgb.val[0] = rgba.val[0];
rgb.val[1] = rgba.val[1];
rgb.val[2] = rgba.val[2];
vst3q_u8(dst + (size_t)x * 3, rgb);
}
return simd_end;
}
#endif
/* Prewarm the SSSE3 capability cache and format the libwebp version
* string at module load so neither lazy first-call path can race
* under ZTS. */
#ifdef HAVE_LIBWEBP
static void fc_webp_version_init(void);
#endif
void fastchart_encoder_init(void)
{
#ifdef FC_ENC_HAVE_X86_SIMD
(void)fc_enc_cpu_has_ssse3();
#endif
#ifdef HAVE_LIBWEBP
fc_webp_version_init();
#endif
}
void fastchart_pixels_init(fastchart_pixels_t *pix, int w, int h)
{
pix->rgba = NULL;
pix->w = w;
pix->h = h;
pix->has_alpha = 0;
pix->dpi = 0;
pix->png_level = -1;
}
void fastchart_pixels_release(fastchart_pixels_t *pix)
{
if (pix->rgba) {
efree(pix->rgba);
pix->rgba = NULL;
}
pix->w = pix->h = 0;
}
/* --------------------------- sinks --------------------------------- */
static int fc_smart_str_sink_write(void *context, const uint8_t *data,
size_t length)
{
smart_str_appendl((smart_str *)context, (const char *)data, length);
return 0;
}
static int fc_stream_sink_write(void *context, const uint8_t *data,
size_t length)
{
php_stream *stream = (php_stream *)context;
size_t offset = 0;
while (offset < length) {
ssize_t written = php_stream_write(stream,
(const char *)data + offset, length - offset);
if (written <= 0 || (size_t)written > length - offset) {
return -1;
}
offset += (size_t)written;
}
return 0;
}
#if defined(HAVE_LIBPNG) || defined(HAVE_LIBJPEG) || defined(HAVE_LIBWEBP)
static int fc_sink_write(fastchart_sink_t *sink, const uint8_t *data,
size_t length)
{
if (sink == NULL || sink->write == NULL || sink->failed) {
return -1;
}
if (length == 0) {
return 0;
}
if (length > SIZE_MAX - sink->bytes_written) {
sink->failed = 1;
return -1;
}
if (sink->write(sink->context, data, length) != 0) {
sink->failed = 1;
return -1;
}
sink->bytes_written += length;
return 0;
}
#endif
void fastchart_sink_init_smart_str(fastchart_sink_t *sink, smart_str *out)
{
sink->write = fc_smart_str_sink_write;
sink->context = out;
sink->bytes_written = 0;
sink->failed = 0;
}
void fastchart_sink_init_stream(fastchart_sink_t *sink, php_stream *stream)
{
sink->write = fc_stream_sink_write;
sink->context = stream;
sink->bytes_written = 0;
sink->failed = 0;
}
/* --------------------------- PNG ----------------------------------- */
#ifdef HAVE_LIBPNG
static void png_sink_write(png_structp png, png_bytep data, png_size_t len)
{
fastchart_sink_t *sink = (fastchart_sink_t *)png_get_io_ptr(png);
if (fc_sink_write(sink, data, len) != 0) {
png_error(png, "write failed");
}
}
static void png_sink_flush(png_structp png)
{
(void)png;
}
/* Stash for the libpng error text, wired as the error_ptr so the
* setjmp recovery below can throw it as the PHP exception instead of
* a generic "no output" error. */
#define FC_PNG_ERR_SZ 256
static void png_sink_error(png_structp png, png_const_charp msg)
{
char *buf = (char *)png_get_error_ptr(png);
if (buf && msg) {
snprintf(buf, FC_PNG_ERR_SZ, "%s", msg);
}
longjmp(png_jmpbuf(png), 1);
}
int fastchart_encode_png_sink(fastchart_sink_t *sink,
const fastchart_pixels_t *pix)
{
char png_err[FC_PNG_ERR_SZ] = {0};
png_structp png = png_create_write_struct(PNG_LIBPNG_VER_STRING,
png_err, png_sink_error, NULL);
if (!png) return -1;
png_infop info = png_create_info_struct(png);
if (!info) {
png_destroy_write_struct(&png, NULL);
return -1;
}
/* Sink callbacks can bail out inside the live libpng session. Release
* the vendor state before re-entering the bailout. */
volatile int rc = 0;
zend_try {
if (setjmp(png_jmpbuf(png))) {
png_destroy_write_struct(&png, &info);
if (!EG(exception)) {
zend_throw_error(NULL, "FastChart: libpng error: %s",
png_err[0] ? png_err : "write failed");
}
rc = -1;
goto done;
}
png_set_write_fn(png, sink, png_sink_write, png_sink_flush);
/* Chart output is flat fills and anti-aliased edges, never
* photographic. libpng's default per-row adaptive filtering (try
* all five, keep the best) costs ~40% of the row-write stage here
* for a size difference under half a percent; a fixed UP filter
* keeps the size and drops the search. */
png_set_filter(png, 0, PNG_FILTER_UP);
if (pix->png_level >= 0) {
png_set_compression_level(png, pix->png_level);
}
int color_type = pix->has_alpha ? PNG_COLOR_TYPE_RGB_ALPHA
: PNG_COLOR_TYPE_RGB;
png_set_IHDR(png, info, pix->w, pix->h, 8, color_type,
PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT,
PNG_FILTER_TYPE_DEFAULT);
if (pix->dpi > 0) {
/* DPI -> pixels per meter: 1 inch = 0.0254 m. */
png_uint_32 ppm = (png_uint_32)((double)pix->dpi / 0.0254 + 0.5);
png_set_pHYs(png, info, ppm, ppm, PNG_RESOLUTION_METER);
}
png_write_info(png, info);
if (!pix->has_alpha) {
/* Strip the A byte per pixel during write. libpng can pack
* from RGBA if we tell it to filter the trailing channel. */
png_set_filler(png, 0, PNG_FILLER_AFTER);
}
const uint8_t *row = pix->rgba;
for (int y = 0; y < pix->h; y++) {
png_write_row(png, (png_bytep)row);
row += pix->w * 4;
}
png_write_end(png, info);
png_destroy_write_struct(&png, &info);
done:;
} zend_catch {
png_destroy_write_struct(&png, &info);
zend_bailout();
} zend_end_try();
return rc;
}
int fastchart_encode_png(smart_str *out, const fastchart_pixels_t *pix)
{
fastchart_sink_t sink;
fastchart_sink_init_smart_str(&sink, out);
return fastchart_encode_png_sink(&sink, pix);
}
int fastchart_have_libpng(void) { return 1; }
const char *fastchart_libpng_version(void) { return PNG_LIBPNG_VER_STRING; }
#else /* !HAVE_LIBPNG */
int fastchart_encode_png_sink(fastchart_sink_t *sink,
const fastchart_pixels_t *pix)
{
(void)sink; (void)pix;
return -2;
}
int fastchart_encode_png(smart_str *out, const fastchart_pixels_t *pix)
{
fastchart_sink_t sink;
fastchart_sink_init_smart_str(&sink, out);
return fastchart_encode_png_sink(&sink, pix);
}
int fastchart_have_libpng(void) { return 0; }
const char *fastchart_libpng_version(void) { return NULL; }
#endif
/* --------------------------- JPEG ---------------------------------- */
#ifdef HAVE_LIBJPEG
struct fc_jpeg_err {
struct jpeg_error_mgr base;
jmp_buf jmp;
};
static void fc_jpeg_error_exit(j_common_ptr cinfo)
{
struct fc_jpeg_err *e = (struct fc_jpeg_err *)cinfo->err;
longjmp(e->jmp, 1);
}
/* Custom destination manager writing straight into the caller's sink.
* jpeg_mem_dest is avoided on
* purpose: it publishes the final buffer address only at
* term_destination, so once its internal buffer grows past the initial
* allocation the caller-side pointer dangles at a block
* empty_mem_output_buffer already freed — an error_exit longjmp
* mid-encode would then double-free it and leak the live grown buffer.
* Streaming into the sink leaves no malloc'd intermediate to
* clean up on either path. */
#define FC_JPEG_STAGE_SZ 8192
struct fc_jpeg_dest {
struct jpeg_destination_mgr base;
fastchart_sink_t *sink;
JOCTET stage[FC_JPEG_STAGE_SZ];
};
static void fc_jpeg_init_destination(j_compress_ptr cinfo)
{
struct fc_jpeg_dest *d = (struct fc_jpeg_dest *)cinfo->dest;
d->base.next_output_byte = d->stage;
d->base.free_in_buffer = FC_JPEG_STAGE_SZ;
}
static boolean fc_jpeg_empty_output_buffer(j_compress_ptr cinfo)
{
struct fc_jpeg_dest *d = (struct fc_jpeg_dest *)cinfo->dest;
/* libjpeg's contract: flush the WHOLE stage buffer here regardless
* of free_in_buffer (jdatadst.c documents the same). */
if (fc_sink_write(d->sink, d->stage, FC_JPEG_STAGE_SZ) != 0) {
ERREXIT(cinfo, JERR_FILE_WRITE);
}
d->base.next_output_byte = d->stage;
d->base.free_in_buffer = FC_JPEG_STAGE_SZ;
return TRUE;
}
static void fc_jpeg_term_destination(j_compress_ptr cinfo)
{
struct fc_jpeg_dest *d = (struct fc_jpeg_dest *)cinfo->dest;
size_t used = FC_JPEG_STAGE_SZ - d->base.free_in_buffer;
if (used > 0) {
if (fc_sink_write(d->sink, d->stage, used) != 0) {
ERREXIT(cinfo, JERR_FILE_WRITE);
}
}
}
int fastchart_encode_jpeg_sink(fastchart_sink_t *sink,
const fastchart_pixels_t *pix, int quality, int bg_rgb)
{
if (quality < 1) quality = 1;
if (quality > 100) quality = 100;
struct jpeg_compress_struct cinfo;
struct fc_jpeg_err err;
cinfo.err = jpeg_std_error(&err.base);
err.base.error_exit = fc_jpeg_error_exit;
struct fc_jpeg_dest dest;
dest.sink = sink;
/* `volatile` keeps the pointer's live value in memory across the
* setjmp boundary. Per C99 §7.13.2.1, automatic-storage locals
* modified after setjmp() and read in the longjmp() recovery branch
* have indeterminate values unless declared volatile. Without it,
* the optimizer may keep rgb_row in a register that libjpeg's
* longjmp() clobbers — the cleanup branch would then read a stale
* NULL or garbage and either leak the allocation or double-free. */
uint8_t * volatile rgb_row = NULL;
/* Gate the destroy on a completed create: if jpeg_create_compress
* itself longjmps (struct/version mismatch), cinfo.mem is still
* uninitialized and jpeg_destroy_compress must not run on it. */
volatile int created = 0;
volatile int rc = 0;
/* Sink callbacks can bail out mid-session while optimize_coding holds
* whole-image coefficient buffers. Release them before re-entering
* the bailout. */
zend_try {
if (setjmp(err.jmp)) {
if (created) jpeg_destroy_compress(&cinfo);
if (rgb_row) efree(rgb_row);
/* Partial bytes already streamed into the sink are the caller's
* to discard — same
* convention as the PNG encoder. */
rc = -1;
goto done;
}
jpeg_create_compress(&cinfo);
created = 1;
dest.base.init_destination = fc_jpeg_init_destination;
dest.base.empty_output_buffer = fc_jpeg_empty_output_buffer;
dest.base.term_destination = fc_jpeg_term_destination;
cinfo.dest = &dest.base;
cinfo.image_width = pix->w;
cinfo.image_height = pix->h;
cinfo.input_components = 3;
cinfo.in_color_space = JCS_RGB;
jpeg_set_defaults(&cinfo);
jpeg_set_quality(&cinfo, quality, TRUE);
cinfo.optimize_coding = TRUE;
if (pix->dpi > 0) {
cinfo.density_unit = 1; /* dots per inch */
cinfo.X_density = (UINT16)pix->dpi;
cinfo.Y_density = (UINT16)pix->dpi;
}
/* 4:2:0 chroma subsampling — matches the eval reference. Setting
* it explicitly because jpeg_set_quality flips to 4:4:4 above
* q=90 in some libjpeg-turbo versions. */
cinfo.comp_info[0].h_samp_factor = 2;
cinfo.comp_info[0].v_samp_factor = 2;
cinfo.comp_info[1].h_samp_factor = 1;
cinfo.comp_info[1].v_samp_factor = 1;
cinfo.comp_info[2].h_samp_factor = 1;
cinfo.comp_info[2].v_samp_factor = 1;
jpeg_start_compress(&cinfo, TRUE);
/* Per-row RGBA -> RGB strip. Two paths:
* - opaque (pix->has_alpha == 0, set by fastchart_rasterize_doc's
* opaque-detect): SSSE3 on x86_64 or NEON on AArch64 packs
* pixels in vector chunks; scalar straight copy handles the rest.
* - translucent: scalar alpha-flatten over bg. JPEG has no
* alpha channel, so transparent regions show through as the
* composited background. */
/* Computed past the setjmp() above so it isn't flagged -Wclobbered;
* set once here and only read in the loop. Negative bg_rgb (the
* chart-side default) keeps the historical white fill. */
uint8_t bg_r = 255, bg_g = 255, bg_b = 255;
if (bg_rgb >= 0) {
bg_r = (uint8_t)((bg_rgb >> 16) & 0xFF);
bg_g = (uint8_t)((bg_rgb >> 8) & 0xFF);
bg_b = (uint8_t)( bg_rgb & 0xFF);
}
rgb_row = emalloc((size_t)pix->w * 3 + 16); /* +16 trailing slack for x86 SSE store overrun */
for (int y = 0; y < pix->h; y++) {
/* Honor max_execution_time: EG() is per-thread, so this is
* ZTS-safe. Bail out to the nearest zend_try (which releases
* the compress struct and rgb_row) so the VM can raise the
* timeout Error instead of running the whole canvas first. */
if ((y & 63) == 0 && FC_TIMED_OUT()) {
zend_bailout();
}
const uint8_t *src = pix->rgba + (size_t)y * pix->w * 4;
uint8_t *dst = rgb_row;
int x = 0;
if (!pix->has_alpha) {
#ifdef FC_ENC_HAVE_ARM_NEON
x = fc_enc_pack_rgba_to_rgb_neon(src, dst, pix->w);
#elif defined(FC_ENC_HAVE_X86_SIMD)
if (fc_enc_cpu_has_ssse3()) {
x = fc_enc_pack_rgba_to_rgb_ssse3(src, dst, pix->w);
}
#endif
for (; x < pix->w; x++) {
dst[(size_t)x * 3 + 0] = src[(size_t)x * 4 + 0];
dst[(size_t)x * 3 + 1] = src[(size_t)x * 4 + 1];
dst[(size_t)x * 3 + 2] = src[(size_t)x * 4 + 2];
}
} else {
for (x = 0; x < pix->w; x++) {
const uint8_t *p = src + (size_t)x * 4;
uint8_t *q = dst + (size_t)x * 3;
uint8_t r = p[0], g = p[1], b = p[2], a = p[3];
if (a == 255) {
q[0] = r; q[1] = g; q[2] = b;
} else if (a == 0) {
q[0] = bg_r; q[1] = bg_g; q[2] = bg_b;
} else {
/* Flatten over bg with round-half-up (+127); the
* truncating /255 darkens mid-alpha edges by up
* to one level per channel. */
int ia = 255 - a;
q[0] = (uint8_t)((r * a + bg_r * ia + 127) / 255);
q[1] = (uint8_t)((g * a + bg_g * ia + 127) / 255);
q[2] = (uint8_t)((b * a + bg_b * ia + 127) / 255);
}
}
}
JSAMPROW row = rgb_row;
jpeg_write_scanlines(&cinfo, &row, 1);
}
efree(rgb_row);
rgb_row = NULL;
jpeg_finish_compress(&cinfo);
jpeg_destroy_compress(&cinfo);
done:;
} zend_catch {
if (created) jpeg_destroy_compress(&cinfo);
if (rgb_row) efree(rgb_row);
zend_bailout();
} zend_end_try();
return rc;
}
int fastchart_encode_jpeg(smart_str *out, const fastchart_pixels_t *pix,
int quality, int bg_rgb)
{
fastchart_sink_t sink;
fastchart_sink_init_smart_str(&sink, out);
return fastchart_encode_jpeg_sink(&sink, pix, quality, bg_rgb);
}
int fastchart_have_libjpeg(void) { return 1; }
/* Value reported in the MINFO row labelled "libjpeg". LIBJPEG_TURBO_-
* VERSION expands to bare 2.1.2 in jconfig.h (not a string literal),
* so stringify it. The "(turbo)" suffix distinguishes from a
* reference-libjpeg build where only the JPEG_LIB_VERSION API number
* is available. */
#define FC_STR(x) #x
#define FC_XSTR(x) FC_STR(x)
const char *fastchart_libjpeg_version(void)
{
#ifdef LIBJPEG_TURBO_VERSION
return FC_XSTR(LIBJPEG_TURBO_VERSION) " (turbo)";
#else
return "API " FC_XSTR(JPEG_LIB_VERSION);
#endif
}
#else /* !HAVE_LIBJPEG */
int fastchart_encode_jpeg_sink(fastchart_sink_t *sink,
const fastchart_pixels_t *pix, int quality, int bg_rgb)
{
(void)sink; (void)pix; (void)quality; (void)bg_rgb;
return -2;
}
int fastchart_encode_jpeg(smart_str *out, const fastchart_pixels_t *pix,
int quality, int bg_rgb)
{
fastchart_sink_t sink;
fastchart_sink_init_smart_str(&sink, out);
return fastchart_encode_jpeg_sink(&sink, pix, quality, bg_rgb);
}
int fastchart_have_libjpeg(void) { return 0; }
const char *fastchart_libjpeg_version(void) { return NULL; }
#endif
/* --------------------------- WebP ---------------------------------- */
#ifdef HAVE_LIBWEBP
/* Advanced API instead of WebPEncodeRGBA/WebPEncodeRGB. Three knobs
* matter for chart-shaped content (flat fills, sharp edges, small
* palette):
* - WEBP_PRESET_DRAWING tunes the entropy analysis for line-art /
* drawing content. WEBP_PRESET_DEFAULT (the simple API's choice)
* spends analysis cycles on photographic detail charts don't have.
* - method = 2 trades a few percent of file size for a 2-3x encode
* speedup. The simple API defaults to method = 4 (moderate).
* - thread_level = 1 enables parallel entropy encoding on libwebp
* builds compiled with pthread support; the simple API never
* opts in.
*
* The encoder still produces a baseline-compatible .webp stream that
* every conformant decoder accepts. */
static int fc_webp_sink_write(const uint8_t *data, size_t data_size,
const WebPPicture *picture)
{
fastchart_sink_t *sink = (fastchart_sink_t *)picture->custom_ptr;
return fc_sink_write(sink, data, data_size) == 0;
}
int fastchart_encode_webp_sink(fastchart_sink_t *sink,
const fastchart_pixels_t *pix, int quality, int mode)
{
float q = (float)quality;
if (q < 1.0f) q = 1.0f;
if (q > 100.0f) q = 100.0f;
WebPConfig config;
switch (mode) {
case FASTCHART_WEBP_PHOTO:
if (!WebPConfigPreset(&config, WEBP_PRESET_PHOTO, q)) return -1;
config.method = 4;
break;
case FASTCHART_WEBP_LOSSLESS:
/* Lossless ignores perceptual quality; the encoder picks
* compression strategy from method. method=6 is the
* highest-compression setting and is the right pick when
* the user asks for "lossless" (size matters more than
* speed in that scenario). */
if (!WebPConfigPreset(&config, WEBP_PRESET_DEFAULT, q)) return -1;
config.lossless = 1;
config.method = 6;
break;
case FASTCHART_WEBP_FAST:
if (!WebPConfigPreset(&config, WEBP_PRESET_DRAWING, q)) return -1;
config.method = 0;
break;
case FASTCHART_WEBP_DRAWING:
default:
if (!WebPConfigPreset(&config, WEBP_PRESET_DRAWING, q)) return -1;
config.method = 2;
break;
}
config.thread_level = 1;
/* The picture lives on the heap because WebPEncode mutates it after
* zend_try's setjmp. The pointer remains valid in the bailout handler
* even when the callback aborts from inside the encoder. */
WebPPicture *picture = emalloc(sizeof(*picture));
if (!WebPPictureInit(picture)) {
efree(picture);
return -1;
}
picture->width = pix->w;
picture->height = pix->h;
/* Lossless must import straight into the ARGB plane: with
* use_argb == 0 libwebp converts RGBA to YUV420 at import time
* (4:2:0 chroma decimation — lossy per webp/encode.h), and VP8L
* would encode the degraded pixels. Lossy modes keep the YUV
* import; it is their native fast path and the opaque-detect
* note below depends on it. */
picture->use_argb = (mode == FASTCHART_WEBP_LOSSLESS);
/* Always import RGBA — no manual RGB pack. When the input is
* opaque (pix->has_alpha == 0, set by fastchart_rasterize_doc's
* opaque-detect), libwebp's internal WebPPictureHasTransparency
* sees all-FF alphas and skips the alpha plane during YUV
* conversion. Saves a w*h*3 emalloc and a per-pixel scalar
* copy that previously dominated the encoder's CPU on opaque
* charts. */
if (!WebPPictureImportRGBA(picture, pix->rgba, pix->w * 4)) {
WebPPictureFree(picture);
efree(picture);
return -1;
}
picture->writer = fc_webp_sink_write;
picture->custom_ptr = sink;
volatile int enc_ok = 0;
zend_try {
enc_ok = WebPEncode(&config, picture);
} zend_catch {
WebPPictureFree(picture);
efree(picture);
zend_bailout();
} zend_end_try();
WebPPictureFree(picture);
efree(picture);
return enc_ok && !sink->failed ? 0 : -1;
}
int fastchart_encode_webp(smart_str *out, const fastchart_pixels_t *pix,
int quality, int mode)
{
fastchart_sink_t sink;
fastchart_sink_init_smart_str(&sink, out);
return fastchart_encode_webp_sink(&sink, pix, quality, mode);
}
int fastchart_have_libwebp(void) { return 1; }
/* Formatted once at MINIT (fastchart_encoder_init): a per-call
* snprintf into the shared static was a benign-but-racy write under
* ZTS when two threads hit MINFO concurrently. */
static char fc_webp_ver[16];
static void fc_webp_version_init(void)
{
int v = WebPGetEncoderVersion();
snprintf(fc_webp_ver, sizeof(fc_webp_ver), "%d.%d.%d",
(v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF);
}
const char *fastchart_libwebp_version(void)
{
return fc_webp_ver;
}
#else /* !HAVE_LIBWEBP */
int fastchart_encode_webp_sink(fastchart_sink_t *sink,
const fastchart_pixels_t *pix, int quality, int mode)
{
(void)sink; (void)pix; (void)quality; (void)mode;
return -2;
}
int fastchart_encode_webp(smart_str *out, const fastchart_pixels_t *pix,
int quality, int mode)
{
fastchart_sink_t sink;
fastchart_sink_init_smart_str(&sink, out);
return fastchart_encode_webp_sink(&sink, pix, quality, mode);
}
int fastchart_have_libwebp(void) { return 0; }
const char *fastchart_libwebp_version(void) { return NULL; }
#endif