ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/CV/CV.xs
Revision: 1.74
Committed: Tue Sep 16 08:43:27 2025 UTC (11 months, 4 weeks ago) by root
Branch: MAIN
CVS Tags: HEAD
Changes since 1.73: +15 -4 lines
Log Message:
*** empty log message ***

File Contents

# Content
1 #include "EXTERN.h"
2 #include "perl.h"
3 #include "XSUB.h"
4
5 #include <string.h>
6 #include <setjmp.h>
7 #include <math.h>
8
9 #include <magic.h>
10
11 #include <jpeglib.h>
12 #include <jerror.h>
13
14 #include <glib.h>
15 #include <gtk/gtk.h>
16 #include <gdk/gdkx.h>
17 #include <gdk-pixbuf/gdk-pixbuf.h>
18
19 #include <gperl.h>
20 #include <gtk2perl.h>
21
22 #include <assert.h>
23
24 #if JXL
25 #include <jxl/decode.h>
26 #include "jxl/thread_parallel_runner.h"
27 #endif
28
29 #if WEBP
30 #include <webp/demux.h>
31 #include <webp/decode.h>
32 #endif
33
34 #if AVIF
35 #include <avif/avif.h>
36 #endif
37
38 #include "perlmulticore.h"
39
40 #define IW 80 /* MUST match Schnauzer.pm! */
41 #define IH 60 /* MUST match Schnauzer.pm! */
42
43 #define LINELENGTH 240
44
45 #define ELLIPSIS "\xe2\x80\xa6"
46
47 typedef char *octet_string;
48
49 static magic_t magic_cookie[2]; /* !mime, mime */
50
51 static int thread_max = 1;
52
53 struct jpg_err_mgr
54 {
55 struct jpeg_error_mgr err;
56 jmp_buf setjmp_buffer;
57 };
58
59 static void
60 cv_error_exit (j_common_ptr cinfo)
61 {
62 cinfo->err->output_message (cinfo);
63 longjmp (((struct jpg_err_mgr *)cinfo->err)->setjmp_buffer, 99);
64 }
65
66 static void
67 cv_error_output (j_common_ptr cinfo)
68 {
69 char msg[JMSG_LENGTH_MAX];
70
71 cinfo->err->format_message (cinfo, msg);
72
73 fprintf (stderr, "JPEG decoding error: %s\n", msg);
74 return;
75 }
76
77 static void
78 rgb_to_hsv (unsigned int r, unsigned int g, unsigned int b,
79 unsigned int *h, unsigned int *s, unsigned int *v)
80 {
81 unsigned int mx = r; if (g > mx) mx = g; if (b > mx) mx = b;
82 unsigned int mn = r; if (g < mn) mn = g; if (b < mn) mn = b;
83 unsigned int delta = mx - mn;
84
85 *v = mx;
86
87 *s = mx ? delta * 255 / mx : 0;
88
89 if (delta == 0)
90 *h = 0;
91 else
92 {
93 if (r == mx)
94 *h = ((int)g - (int)b) * 255 / (int)(delta * 3);
95 else if (g == mx)
96 *h = ((int)b - (int)r) * 255 / (int)(delta * 3) + 52;
97 else if (b == mx)
98 *h = ((int)r - (int)g) * 255 / (int)(delta * 3) + 103;
99
100 *h &= 255;
101 }
102 }
103
104 struct feature {
105 float v1, v2, v3; // mean, square, cube
106 int n;
107 };
108
109 static void
110 feature_init (struct feature *f)
111 {
112 f->v1 = 0.;
113 f->v2 = 0.;
114 f->v3 = 0.;
115 f->n = 0;
116 }
117
118 // didn't find an algorithm to neatly do mean, variance and skew in one pass.
119 // elmex ist schuld.
120 static void
121 feature_update_pass_1 (struct feature *f, unsigned int v)
122 {
123 f->v1 += v;
124 f->n += 1;
125 }
126
127 static void
128 feature_finish_pass_1 (struct feature *f)
129 {
130 if (f->n < 1)
131 return;
132
133 f->v1 /= f->n;
134 }
135
136 static void
137 feature_update_pass_2 (struct feature *f, unsigned int v)
138 {
139 float d = v - f->v1;
140
141 f->v2 += d * d;
142 f->v3 += d * d * d;
143 }
144
145 static void
146 feature_finish_pass_2 (struct feature *f)
147 {
148 if (f->n < 1)
149 return;
150
151 f->v2 /= f->n;
152 f->v3 /= f->n;
153
154 f->v1 /= 255.;
155 f->v2 /= 255. * 255.; f->v2 = sqrtf (f->v2);
156 f->v3 /= 255. * 255. * 255.; f->v3 = powf (fabsf (f->v3), 1./3.);
157 }
158
159 static guint32 a85_val;
160 static guint a85_cnt;
161 static guchar a85_buf[LINELENGTH], *a85_ptr;
162
163 static void
164 a85_init (void)
165 {
166 a85_cnt = 4;
167 a85_ptr = a85_buf;
168 }
169
170 static void
171 a85_push (PerlIO *fp, guchar c)
172 {
173 a85_val = a85_val << 8 | c;
174
175 if (!--a85_cnt)
176 {
177 a85_cnt = 4;
178 if (a85_val)
179 {
180 a85_ptr[4] = (a85_val % 85) + 33; a85_val /= 85;
181 a85_ptr[3] = (a85_val % 85) + 33; a85_val /= 85;
182 a85_ptr[2] = (a85_val % 85) + 33; a85_val /= 85;
183 a85_ptr[1] = (a85_val % 85) + 33; a85_val /= 85;
184 a85_ptr[0] = (a85_val ) + 33;
185
186 a85_ptr += 5;
187 }
188 else
189 *a85_ptr++ = 'z';
190
191 if (a85_ptr >= a85_buf + sizeof (a85_buf) - 7)
192 {
193 *a85_ptr++ = '\n';
194 PerlIO_write (fp, a85_buf, a85_ptr - a85_buf);
195 a85_ptr = a85_buf;
196 }
197 }
198
199 }
200
201 static void
202 a85_finish (PerlIO *fp)
203 {
204 while (a85_cnt != 4)
205 a85_push (fp, 0);
206
207 *a85_ptr++ = '~'; // probably buggy end-marker
208 *a85_ptr++ = '>'; // probably buggy end-marker
209 *a85_ptr++ = '\n';
210
211 PerlIO_write (fp, a85_buf, a85_ptr - a85_buf);
212 }
213
214 /////////////////////////////////////////////////////////////////////////////
215 // memory source for libjpeg
216
217 static void cv_ms_init (j_decompress_ptr cinfo)
218 {
219 }
220
221 static void cv_ms_term (j_decompress_ptr cinfo)
222 {
223 }
224
225 static boolean cv_ms_fill (j_decompress_ptr cinfo)
226 {
227 // unexpected EOF, warn and generate fake EOI marker
228
229 WARNMS (cinfo, JWRN_JPEG_EOF);
230
231 struct jpeg_source_mgr *src = (struct jpeg_source_mgr *)cinfo->src;
232
233 static const JOCTET eoi[] = { 0xFF, JPEG_EOI };
234
235 src->next_input_byte = eoi;
236 src->bytes_in_buffer = sizeof (eoi);
237
238 return TRUE;
239 }
240
241 static void cv_ms_skip (j_decompress_ptr cinfo, long num_bytes)
242 {
243 struct jpeg_source_mgr *src = (struct jpeg_source_mgr *)cinfo->src;
244
245 src->next_input_byte += num_bytes;
246 src->bytes_in_buffer -= num_bytes;
247 }
248
249 static void cv_jpeg_mem_src (j_decompress_ptr cinfo, void *buf, size_t buflen)
250 {
251 struct jpeg_source_mgr *src;
252
253 if (!cinfo->src)
254 cinfo->src = (struct jpeg_source_mgr *)
255 (*cinfo->mem->alloc_small) (
256 (j_common_ptr) cinfo, JPOOL_PERMANENT, sizeof (struct jpeg_source_mgr)
257 );
258
259 src = (struct jpeg_source_mgr *)cinfo->src;
260 src->init_source = cv_ms_init;
261 src->fill_input_buffer = cv_ms_fill;
262 src->skip_input_data = cv_ms_skip;
263 src->resync_to_restart = jpeg_resync_to_restart;
264 src->term_source = cv_ms_term;
265 src->next_input_byte = (JOCTET *)buf;
266 src->bytes_in_buffer = buflen;
267 }
268
269 /////////////////////////////////////////////////////////////////////////////
270
271 /* great, the jpeg-xl reference implementaton requires us to parse bmff files */
272
273 struct bmff_box
274 {
275 char type[4];
276 const uint8_t *ptr;
277 size_t size;
278 };
279
280 static int
281 bmff_parse_box (struct bmff_box *box, const uint8_t **next_in, size_t *avail_in)
282 {
283 if (*avail_in < 8)
284 return 0;
285
286 box->size = ((*next_in)[0] << 24)
287 | ((*next_in)[1] << 16)
288 | ((*next_in)[2] << 8)
289 | ((*next_in)[3] );
290
291 if (box->size < 8)
292 return 0;
293
294 if (*avail_in < box->size)
295 return 0;
296
297 memcpy (box->type, *next_in + 4, 4);
298 box->ptr = *next_in + 8;
299
300 *next_in += box->size;
301 *avail_in -= box->size;
302
303 box->size -= 8;
304
305 return 1;
306 }
307
308 /////////////////////////////////////////////////////////////////////////////
309 // libavif api is just annoying on every minor detail
310
311 static int
312 is_avif (U8 *data, STRLEN data_len)
313 {
314 #if AVIF
315 avifROData buf;
316 buf.data = data;
317 buf.size = data_len;
318 return avifPeekCompatibleFileType (&buf);
319 #else
320 return data_len >= 12
321 && data[ 4] == 'f'
322 && data[ 5] == 't'
323 && data[ 6] == 'y'
324 && data[ 7] == 'p'
325 && data[ 8] == 'a'
326 && data[ 9] == 'v'
327 && data[10] == 'i'
328 && data[11] == 'f'
329 ;
330 #endif
331 }
332
333 /////////////////////////////////////////////////////////////////////////////
334
335 MODULE = Gtk2::CV PACKAGE = Gtk2::CV
336
337 PROTOTYPES: ENABLE
338
339 void
340 _exit (int code)
341
342 void
343 set_thread_max (int new_thread_max)
344 CODE:
345 thread_max = new_thread_max;
346
347 # calculate the common prefix length of two strings
348 # missing function in perl. really :)
349 int
350 common_prefix_length (a, b)
351 unsigned char *a = (unsigned char *)SvPVutf8_nolen ($arg);
352 unsigned char *b = (unsigned char *)SvPVutf8_nolen ($arg);
353 CODE:
354 RETVAL = 0;
355
356 while (*a == *b && *a)
357 {
358 RETVAL += (*a & 0xc0) != 0x80;
359 a++, b++;
360 }
361
362 OUTPUT:
363 RETVAL
364
365 int
366 common_prefix_length_byte (a, b)
367 unsigned char *a = (unsigned char *)SvPVbyte_nolen ($arg);
368 unsigned char *b = (unsigned char *)SvPVbyte_nolen ($arg);
369 CODE:
370 RETVAL = 0;
371 while (*a == *b && *a)
372 a++, b++, RETVAL++;
373 OUTPUT:
374 RETVAL
375
376 const char *
377 magic (SV *path_or_data)
378 ALIAS:
379 magic = 0
380 magic_mime = 1
381 magic_buffer = 2
382 magic_buffer_mime = 3
383 CODE:
384 {
385 STRLEN len;
386 char *data = SvPVbyte (path_or_data, len);
387
388 if (!magic_cookie[0])
389 {
390 magic_cookie[0] = magic_open (MAGIC_SYMLINK);
391 magic_cookie[1] = magic_open (MAGIC_SYMLINK | MAGIC_MIME_TYPE);
392 magic_load (magic_cookie[0], 0);
393 magic_load (magic_cookie[1], 0);
394 }
395
396 perlinterp_release ();
397
398 RETVAL = ix & 2
399 ? magic_buffer (magic_cookie[ix & 1], data, len)
400 : magic_file (magic_cookie[ix & 1], data);
401
402 perlinterp_acquire ();
403 }
404 OUTPUT:
405 RETVAL
406
407 # missing/broken in Gtk2 perl module
408
409 void
410 gdk_window_clear_hints (GdkWindow *window)
411 CODE:
412 gdk_window_set_geometry_hints (window, 0, 0);
413
414 gboolean
415 gdk_net_wm_supports (GdkAtom property)
416 CODE:
417 #if defined(GDK_WINDOWING_X11) && !defined(GDK_MULTIHEAD_SAFE)
418 RETVAL = gdk_net_wm_supports (property);
419 #else
420 RETVAL = 0;
421 #endif
422 OUTPUT:
423 RETVAL
424
425 GdkPixbuf_noinc *
426 dealpha_expose (GdkPixbuf *pb)
427 CODE:
428 perlinterp_release ();
429 {
430 int w = gdk_pixbuf_get_width (pb);
431 int h = gdk_pixbuf_get_height (pb);
432 int bpp = gdk_pixbuf_get_n_channels (pb);
433 int x, y, i;
434 guchar *src = gdk_pixbuf_get_pixels (pb), *dst;
435 int sstr = gdk_pixbuf_get_rowstride (pb), dstr;
436
437 RETVAL = gdk_pixbuf_new (GDK_COLORSPACE_RGB, 0, 8, w, h);
438
439 dst = gdk_pixbuf_get_pixels (RETVAL);
440 dstr = gdk_pixbuf_get_rowstride (RETVAL);
441
442 for (x = 0; x < w; x++)
443 for (y = 0; y < h; y++)
444 for (i = 0; i < 3; i++)
445 dst[x * 3 + y * dstr + i] = src[x * bpp + y * sstr + i];
446 }
447 perlinterp_acquire ();
448 OUTPUT:
449 RETVAL
450
451 GdkPixbuf_noinc *
452 rotate (GdkPixbuf *pb, int angle)
453 CODE:
454 perlinterp_release ();
455 if (angle < 0)
456 angle += 360;
457 RETVAL = gdk_pixbuf_rotate_simple (pb, angle == 0 ? GDK_PIXBUF_ROTATE_NONE
458 : angle == 90 ? GDK_PIXBUF_ROTATE_COUNTERCLOCKWISE
459 : angle == 180 ? GDK_PIXBUF_ROTATE_UPSIDEDOWN
460 : angle == 270 ? GDK_PIXBUF_ROTATE_CLOCKWISE
461 : angle);
462 perlinterp_acquire ();
463 OUTPUT:
464 RETVAL
465
466 const char *
467 filetype (SV *image_data)
468 CODE:
469 {
470 STRLEN data_len;
471 U8 *data = SvPVbyte (image_data, data_len);
472 static const unsigned char jxl_header[] = {
473 0, 0, 0, 0x0c, 0x4a, 0x58, 0x4c, 0x20, 0x0d, 0xa, 0x87, 0x0a
474 };
475
476 if (data_len >= 20
477 && data[0] == 0xff
478 && data[1] == 0xd8
479 && data[2] == 0xff)
480 RETVAL = "image/jpeg";
481 else if (data_len >= 12
482 && data[ 0] == (U8)'R'
483 && data[ 1] == (U8)'I'
484 && data[ 2] == (U8)'F'
485 && data[ 3] == (U8)'F'
486 && data[ 8] == (U8)'W'
487 && data[ 9] == (U8)'E'
488 && data[10] == (U8)'B'
489 && data[11] == (U8)'P')
490 RETVAL = "image/webp";
491 else if (data_len >= 16
492 && data[ 0] == 0x89
493 && data[ 1] == (U8)'P'
494 && data[ 2] == (U8)'N'
495 && data[ 3] == (U8)'G'
496 && data[ 4] == 0x0d
497 && data[ 5] == 0x0a
498 && data[ 6] == 0x1a
499 && data[ 7] == 0x0a)
500 RETVAL = "image/png";
501 else if (is_avif (data, data_len))
502 RETVAL = "image/avif";
503 else if (data_len >= sizeof (jxl_header) && memcmp (data, jxl_header, sizeof (jxl_header)) == 0)
504 RETVAL = "image/jxl"; // todo: might want to use JxlSignatureCheck
505 else if (data_len >= 2
506 && data[0] == 0xff
507 && data[1] == 0x0a)
508 RETVAL = "image/jxl";
509 else if (data_len >= 13
510 && data[0] == 'G'
511 && data[1] == 'I'
512 && data[2] == 'F'
513 && data[3] == '8'
514 //&& (data[4] == '7' || data[4] == '9')
515 && data[5] == 'a')
516 {
517 RETVAL = "image/gif";
518
519 // now see if its animated - we require the netscape application header for this
520 int ofs = 13;
521
522 if (data[10] & 0x80)
523 ofs += (1 << ((data[10] & 7) + 1)) * 3;
524
525 if (data_len >= ofs + 2 + 1 + 11)
526 {
527
528 // skip a graphic control extension block. we assume
529 // there is at most one such block - while the NAB
530 // has to come firstz, some files do not obey this
531 if (data[ofs] == 0x21 && data[ofs + 1] == 0xf9)
532 ofs += 3 + data[ofs + 2] + 1;
533
534 if (data_len >= ofs + 2 + 1 + 11)
535 if (!memcmp (data + ofs, "\x21\xff\x0bNETSCAPE2.0", sizeof ("\x21\xff\x0bNETSCAPE2.0") - 1))
536 RETVAL = "video/gif";
537 }
538 }
539 else if (data_len >= 0x8000 + 6
540 && data[0x8000+1] == (U8)'B'
541 && data[0x8000+2] == (U8)'E'
542 && data[0x8000+3] == (U8)'A'
543 && data[0x8000+4] == (U8)'0'
544 && data[0x8000+5] == (U8)'1')
545 RETVAL = "video/iso-bluray";
546 else if (data_len >= 0x8000 + 6
547 && data[0x8000+1] == (U8)'C'
548 && data[0x8000+2] == (U8)'D'
549 && data[0x8000+3] == (U8)'0'
550 && data[0x8000+4] == (U8)'0'
551 && data[0x8000+5] == (U8)'1')
552 RETVAL = "video/iso9660";
553
554 else
555 XSRETURN_UNDEF;
556 }
557 OUTPUT:
558 RETVAL
559
560 GdkPixbuf_noinc *
561 decode_jpeg (SV *image_data, int thumbnail = 0, int iw = 0, int ih = 0)
562 CODE:
563 {
564 struct jpeg_decompress_struct cinfo;
565 struct jpg_err_mgr jerr;
566 int rs;
567 volatile GdkPixbuf *pb = 0;
568 STRLEN data_len;
569 guchar *data = SvPVbyte (image_data, data_len);
570
571 RETVAL = 0;
572
573 perlinterp_release ();
574
575 cinfo.err = jpeg_std_error (&jerr.err);
576
577 jerr.err.error_exit = cv_error_exit;
578 jerr.err.output_message = cv_error_output;
579
580 if ((rs = setjmp (jerr.setjmp_buffer)))
581 {
582 jpeg_destroy_decompress (&cinfo);
583
584 if (pb)
585 g_object_unref ((gpointer)pb);
586
587 perlinterp_acquire ();
588 XSRETURN_UNDEF;
589 }
590
591 if (!data_len)
592 longjmp (jerr.setjmp_buffer, 4);
593
594 jpeg_create_decompress (&cinfo);
595 cv_jpeg_mem_src (&cinfo, data, data_len);
596
597 jpeg_read_header (&cinfo, TRUE);
598
599 cinfo.dct_method = JDCT_DEFAULT;
600 cinfo.do_fancy_upsampling = FALSE; /* worse quality, but nobody compained so far, and gdk-pixbuf does the same */
601 cinfo.do_block_smoothing = FALSE;
602 cinfo.out_color_space = JCS_RGB;
603 cinfo.quantize_colors = FALSE;
604
605 cinfo.scale_num = 1;
606 cinfo.scale_denom = 1;
607
608 jpeg_calc_output_dimensions (&cinfo);
609
610 if (thumbnail)
611 {
612 cinfo.dct_method = JDCT_FASTEST;
613 cinfo.do_fancy_upsampling = FALSE;
614
615 while (cinfo.scale_denom < 8
616 && cinfo.output_width >= iw*4
617 && cinfo.output_height >= ih*4)
618 {
619 cinfo.scale_denom <<= 1;
620 jpeg_calc_output_dimensions (&cinfo);
621 }
622 }
623
624 if (cinfo.output_components != 3)
625 longjmp (jerr.setjmp_buffer, 3);
626
627 if (cinfo.jpeg_color_space == JCS_YCCK || cinfo.jpeg_color_space == JCS_CMYK)
628 {
629 cinfo.out_color_space = JCS_CMYK;
630 cinfo.output_components = 4;
631 }
632
633 pb = RETVAL = gdk_pixbuf_new (GDK_COLORSPACE_RGB, cinfo.output_components == 4, 8, cinfo.output_width, cinfo.output_height);
634 if (!RETVAL)
635 longjmp (jerr.setjmp_buffer, 2);
636
637 data = gdk_pixbuf_get_pixels (RETVAL);
638 rs = gdk_pixbuf_get_rowstride (RETVAL);
639
640 jpeg_start_decompress (&cinfo);
641
642 while (cinfo.output_scanline < cinfo.output_height)
643 {
644 int remaining = cinfo.output_height - cinfo.output_scanline;
645 JSAMPROW rp[4];
646
647 rp [0] = data + cinfo.output_scanline * rs;
648 rp [1] = (guchar *)rp [0] + rs;
649 rp [2] = (guchar *)rp [1] + rs;
650 rp [3] = (guchar *)rp [2] + rs;
651
652 jpeg_read_scanlines (&cinfo, rp, remaining < 4 ? remaining : 4);
653 }
654
655 if (cinfo.out_color_space == JCS_CMYK)
656 {
657 guchar *end = data + cinfo.output_height * rs;
658
659 while (data < end)
660 {
661 U32 c = data [0];
662 U32 m = data [1];
663 U32 y = data [2];
664 U32 k = data [3];
665
666 if (0)
667 if (cinfo.Adobe_transform == 2)
668 {
669 c ^= 0xff;
670 m ^= 0xff;
671 y ^= 0xff;
672 k ^= 0xff;
673 }
674
675 data [0] = (c * k + 0x80) / 0xff;
676 data [1] = (m * k + 0x80) / 0xff;
677 data [2] = (y * k + 0x80) / 0xff;
678 data [3] = 0xff;
679
680 data += 4;
681 }
682 }
683
684 jpeg_finish_decompress (&cinfo);
685 jpeg_destroy_decompress (&cinfo);
686 perlinterp_acquire ();
687 }
688 OUTPUT:
689 RETVAL
690
691 GdkPixbuf_noinc *
692 decode_jxl (SV *image_data, int thumbnail = 0, int iw = 0, int ih = 0)
693 CODE:
694 {
695 #if JXL
696 JxlDecoder *dec;
697 JxlBasicInfo info;
698 const uint8_t *next_in = (uint8_t *)SvPVbyte_nolen (image_data);
699 size_t avail_in = SvCUR (image_data);
700 const char *error = 0;
701 JxlDecoderStatus status;
702 static void *runner_cache;
703 void *runner = 0;
704
705 RETVAL = 0;
706
707 if (runner_cache)
708 runner = runner_cache;
709 else
710 runner = JxlThreadParallelRunnerCreate (0, JxlThreadParallelRunnerDefaultNumWorkerThreads ());
711
712 runner_cache = 0;
713
714 perlinterp_release ();
715
716 dec = JxlDecoderCreate (0);
717
718 error = "JxlDecoderCreate failed";
719 if (!dec)
720 goto done;
721
722 status = JxlDecoderSetParallelRunner (dec, JxlThreadParallelRunner, runner);
723 error = "JxlDecoderSetParallelRunner failed";
724 if (status != JXL_DEC_SUCCESS)
725 goto done;
726
727 error = "JxlDecoderSubscribeEvents failed";
728 status = JxlDecoderSubscribeEvents (dec, JXL_DEC_BASIC_INFO | JXL_DEC_FULL_IMAGE);
729 if (status != JXL_DEC_SUCCESS)
730 goto done;
731
732 status = JxlDecoderSetInput (dec, next_in, avail_in);
733 error = "JxlDecoderSetInput failed";
734 if (status != JXL_DEC_SUCCESS)
735 goto done;
736
737 for (;;)
738 {
739 status = JxlDecoderProcessInput (dec);
740
741 switch (status)
742 {
743 case JXL_DEC_FULL_IMAGE:
744 error = 0;
745 goto done;
746
747 case JXL_DEC_ERROR:
748 error = "JxlDecoderProcessInput failed";
749 goto done;
750
751 case JXL_DEC_NEED_MORE_INPUT:
752 error = "incomplete file";
753 goto done;
754
755 case JXL_DEC_SUCCESS:
756 error = "incomplete decode";
757 goto done;
758
759 case JXL_DEC_BASIC_INFO:
760 {
761 status = JxlDecoderGetBasicInfo (dec, &info);
762 error = "JxlDecoderGetBasicInfo failed";
763 if (status != JXL_DEC_SUCCESS)
764 goto done;
765
766 RETVAL = gdk_pixbuf_new (GDK_COLORSPACE_RGB, !!info.alpha_bits, 8, info.xsize, info.ysize);
767 error = "unable to allocate pixbuf";
768 if (!RETVAL)
769 goto done;
770
771 JxlPixelFormat format = {
772 info.alpha_bits ? 4 : 3,
773 JXL_TYPE_UINT8,
774 JXL_NATIVE_ENDIAN,
775 gdk_pixbuf_get_rowstride (RETVAL)
776 };
777
778 // cannot use gdk_pixbuf_get_byte_length because that does
779 // not return the size of the buffer, but the size of the buffer without
780 // the last padding bytes. the internal buffer is rowstride * ysize,
781 // and this is what the jxl decoder needs. none of this is documented
782 // in either library, of course.
783
784 status = JxlDecoderSetImageOutBuffer (
785 dec,
786 &format,
787 gdk_pixbuf_get_pixels (RETVAL),
788 gdk_pixbuf_get_rowstride (RETVAL) * info.ysize
789 );
790 error = "JxlDecoderSetImageOutBuffer failed";
791 if (status != JXL_DEC_SUCCESS)
792 goto done;
793 }
794 break;
795
796 default:
797 error = "unexpected event";
798 goto done;
799 }
800 }
801
802 done:
803 if (dec)
804 JxlDecoderDestroy (dec);
805
806 perlinterp_acquire ();
807
808 if (runner_cache)
809 JxlThreadParallelRunnerDestroy (runner);
810
811 runner_cache = runner;
812
813 if (error)
814 {
815 if (RETVAL)
816 g_object_unref (RETVAL);
817
818 croak ("load_jxl: %s (status %d)", error, status);
819 }
820 #else
821 croak ("load_jxl: jpeg-xl not enabled at compile time");
822 #endif
823 }
824 OUTPUT:
825 RETVAL
826
827 GdkPixbuf_noinc *
828 decode_webp (SV *image_data, int thumbnail = 0, int iw = 0, int ih = 0)
829 CODE:
830 {
831 #if WEBP
832 STRLEN data_size;
833 int alpha;
834 WebPData data;
835 WebPDemuxer *demux;
836 WebPIterator iter;
837 WebPDecoderConfig config;
838 int inw, inh;
839
840 data.bytes = (uint8_t *)SvPVbyte (image_data, data_size);
841 data.size = data_size;
842
843 perlinterp_release ();
844
845 RETVAL = 0;
846
847 if (!(demux = WebPDemux (&data)))
848 goto err_demux;
849
850 if (!WebPDemuxGetFrame (demux, 1, &iter))
851 goto err_iter;
852
853 if (!WebPInitDecoderConfig (&config))
854 goto err_iter;
855
856 config.options.use_threads = 1;
857
858 if (WebPGetFeatures (iter.fragment.bytes, iter.fragment.size, &config.input) != VP8_STATUS_OK)
859 goto err_iter;
860
861 inw = config.input.width;
862 inh = config.input.height;
863
864 if (thumbnail)
865 {
866 if (inw * ih > inh * iw)
867 ih = (iw * inh + inw - 1) / inw;
868 else
869 iw = (ih * inw + inh - 1) / inh;
870
871 config.options.bypass_filtering = 1;
872 config.options.no_fancy_upsampling = 1;
873
874 config.options.use_scaling = 1;
875 config.options.scaled_width = iw;
876 config.options.scaled_height = ih;
877 }
878 else
879 {
880 iw = inw;
881 ih = inh;
882 }
883
884 alpha = !!config.input.has_alpha;
885
886 RETVAL = gdk_pixbuf_new (GDK_COLORSPACE_RGB, alpha, 8, iw, ih);
887 if (!RETVAL)
888 goto err_iter;
889
890 config.output.colorspace = alpha ? MODE_RGBA : MODE_RGB;
891 config.output.u.RGBA.rgba = gdk_pixbuf_get_pixels (RETVAL);
892 config.output.u.RGBA.stride = gdk_pixbuf_get_rowstride (RETVAL);
893 config.output.u.RGBA.size = gdk_pixbuf_get_byte_length (RETVAL);
894 config.output.is_external_memory = 1;
895
896 if (WebPDecode (iter.fragment.bytes, iter.fragment.size, &config) != VP8_STATUS_OK)
897 {
898 g_object_unref (RETVAL);
899 RETVAL = 0;
900 goto err_iter;
901 }
902
903 err_iter:
904 WebPDemuxReleaseIterator (&iter);
905 err_demux:
906 WebPDemuxDelete (demux);
907
908 perlinterp_acquire ();
909 #else
910 croak ("load_webp: webp not enabled at compile time");
911 #endif
912 }
913 OUTPUT:
914 RETVAL
915
916 GdkPixbuf_noinc *
917 decode_avif (SV *image_data, int thumbnail = 0, int iw = 0, int ih = 0)
918 CODE:
919 {
920 #if AVIF
921 STRLEN data_size;
922 uint8_t *data;
923 const char *error = 0;
924 avifDecoder *decoder = 0;
925 avifImage *image = 0;
926 avifResult result = AVIF_RESULT_OK;
927
928 data = (uint8_t *)SvPVbyte (image_data, data_size);
929
930 perlinterp_release ();
931
932 RETVAL = 0;
933 decoder = avifDecoderCreate ();
934
935 error = "unable to create avif decoder";
936 if (!decoder)
937 goto error;
938
939 decoder->strictFlags = AVIF_STRICT_DISABLED;
940 decoder->maxThreads = thread_max;
941 decoder->imageDimensionLimit = 65536; // default is 16384, for webp garbage compatibility, probably
942
943 error = "avifDecoderSetIOMemory: %s";
944 result = avifDecoderSetIOMemory (decoder, data, data_size);
945 if (result != AVIF_RESULT_OK)
946 goto error;
947
948 error = "avifDecoderParse: %s";
949 result = avifDecoderParse (decoder);
950 if (result != AVIF_RESULT_OK)
951 goto error;
952
953 error = "avifDecoderNextImage: %s";
954 result = avifDecoderNextImage (decoder);
955 if (result != AVIF_RESULT_OK)
956 goto error;
957
958 image = decoder->image;
959
960 error = "unable to create pixbuf for avif decoding";
961 RETVAL = gdk_pixbuf_new (GDK_COLORSPACE_RGB, !!image->alphaPlane, 8, image->width, image->height);
962 if (!RETVAL)
963 goto error;
964
965 if (image->colorPrimaries == AVIF_COLOR_PRIMARIES_UNSPECIFIED)
966 image->colorPrimaries = AVIF_COLOR_PRIMARIES_BT709; // libavif seems to ignore this without icc profile
967
968 if (image->transferCharacteristics == AVIF_TRANSFER_CHARACTERISTICS_UNSPECIFIED)
969 image->transferCharacteristics = AVIF_TRANSFER_CHARACTERISTICS_SRGB; // libavif seems to ignore this without icc profile
970
971 if (image->matrixCoefficients == AVIF_MATRIX_COEFFICIENTS_UNSPECIFIED)
972 image->matrixCoefficients = AVIF_MATRIX_COEFFICIENTS_BT709;
973
974 avifRGBImage rgb;
975 avifRGBImageSetDefaults (&rgb, image);
976
977 rgb.format = image->alphaPlane ? AVIF_RGB_FORMAT_RGBA : AVIF_RGB_FORMAT_RGB;
978 rgb.depth = 8;
979 rgb.pixels = gdk_pixbuf_get_pixels (RETVAL);
980 rgb.rowBytes = gdk_pixbuf_get_rowstride (RETVAL);
981 //rgb.chromaUpsampling = AVIF_CHROMA_UPSAMPLING_BEST_QUALITY;
982 rgb.maxThreads = thread_max;
983
984 error = "avifImageYUVToRGB: %s";
985 result = avifImageYUVToRGB (image, &rgb);
986 if (result != AVIF_RESULT_OK)
987 goto error;
988
989 error = 0;
990
991 error:
992
993 if (decoder)
994 avifDecoderDestroy (decoder);
995
996 perlinterp_acquire ();
997
998 if (error)
999 {
1000 if (RETVAL)
1001 g_object_unref (RETVAL);
1002
1003 croak (error, avifResultToString (result));
1004 }
1005 #else
1006 croak ("load_avif: avif not enabled at compile time");
1007 #endif
1008 }
1009 OUTPUT:
1010 RETVAL
1011
1012 void
1013 compare (GdkPixbuf *a, GdkPixbuf *b)
1014 PPCODE:
1015 perlinterp_release ();
1016 {
1017 int w = gdk_pixbuf_get_width (a);
1018 int h = gdk_pixbuf_get_height (a);
1019
1020 int sa = gdk_pixbuf_get_rowstride (a);
1021 int sb = gdk_pixbuf_get_rowstride (b);
1022
1023 guchar *pa = gdk_pixbuf_get_pixels (a);
1024 guchar *pb = gdk_pixbuf_get_pixels (b);
1025
1026 int x, y;
1027
1028 assert (w == gdk_pixbuf_get_width (b));
1029 assert (h == gdk_pixbuf_get_height (b));
1030
1031 assert (gdk_pixbuf_get_n_channels (a) == 3);
1032 assert (gdk_pixbuf_get_n_channels (b) == 3);
1033
1034 double diff = 0.;
1035 int peak = 0;
1036
1037 if (w && h)
1038 for (y = 0; y < h; y++)
1039 {
1040 guchar *pa_ = pa + y * sa;
1041 guchar *pb_ = pb + y * sb;
1042
1043 for (x = 0; x < w; x++)
1044 {
1045 int d;
1046
1047 d = ((int)*pa_++) - ((int)*pb_++); diff += d*d; peak = MAX (peak, abs (d));
1048 d = ((int)*pa_++) - ((int)*pb_++); diff += d*d; peak = MAX (peak, abs (d));
1049 d = ((int)*pa_++) - ((int)*pb_++); diff += d*d; peak = MAX (peak, abs (d));
1050 }
1051 }
1052
1053 perlinterp_acquire ();
1054
1055 EXTEND (SP, 2);
1056 PUSHs (sv_2mortal (newSVnv (sqrt (diff / (w * h * 3. * 255. * 255.)))));
1057 PUSHs (sv_2mortal (newSVnv (peak / 255.)));
1058 }
1059
1060 #############################################################################
1061
1062 MODULE = Gtk2::CV PACKAGE = Gtk2::CV::Schnauzer
1063
1064 # currently only works for filenames (octet strings)
1065
1066 SV *
1067 foldcase (SV *pathsv)
1068 PROTOTYPE: $
1069 CODE:
1070 {
1071 STRLEN plen;
1072 U8 *path = (U8 *)SvPV (pathsv, plen);
1073 U8 *pend = path + plen;
1074 U8 dst [plen * 8 * 3], *dstp = dst;
1075
1076 while (path < pend)
1077 {
1078 U8 ch = *path;
1079
1080 if (ch >= 'a' && ch <= 'z')
1081 *dstp++ = *path++;
1082 else if (ch >= 'A' && ch <= 'Z')
1083 *dstp++ = *path++ + ('a' - 'A');
1084 else if (ch >= '0' && ch <= '9')
1085 {
1086 /* version sort, up to 8 digits */
1087 STRLEN el, nl = 0;
1088 while (*path >= '0' && *path <= '9' && path < pend)
1089 path++, nl++;
1090
1091 for (el = nl; el < 8; el++)
1092 *dstp++ = '0';
1093
1094 memcpy (dstp, path - nl, nl);
1095 dstp += nl;
1096 }
1097 else
1098 *dstp++ = *path++;
1099 #if 0
1100 else
1101 {
1102 STRLEN cl;
1103 to_utf8_fold (path, dstp, &cl);
1104 dstp += cl;
1105 path += is_utf8_char (path);
1106 }
1107 #endif
1108 }
1109
1110 RETVAL = newSVpvn ((const char *)dst, dstp - dst);
1111 }
1112 OUTPUT:
1113 RETVAL
1114
1115 GdkPixbuf_noinc *
1116 p7_to_pb (int w, int h, SV *src_sv)
1117 PROTOTYPE: @
1118 CODE:
1119 {
1120 int x, y;
1121 guchar *dst, *d;
1122 int dstr;
1123 guchar *src = (guchar *)SvPVbyte_nolen (src_sv);
1124
1125 RETVAL = gdk_pixbuf_new (GDK_COLORSPACE_RGB, 0, 8, w, h);
1126 dst = gdk_pixbuf_get_pixels (RETVAL);
1127 dstr = gdk_pixbuf_get_rowstride (RETVAL);
1128
1129 for (y = 0; y < h; y++)
1130 for (d = dst + y * dstr, x = 0; x < w; x++)
1131 {
1132 *d++ = (((*src >> 5) & 7) * 255 + 4) / 7;
1133 *d++ = (((*src >> 2) & 7) * 255 + 4) / 7;
1134 *d++ = (((*src >> 0) & 3) * 255 + 2) / 3;
1135
1136 src++;
1137 }
1138 }
1139 OUTPUT:
1140 RETVAL
1141
1142 #############################################################################
1143
1144 MODULE = Gtk2::CV PACKAGE = Gtk2::CV::PostScript
1145
1146 void
1147 dump_ascii85 (PerlIO *fp, GdkPixbuf *pb)
1148 CODE:
1149 {
1150 int w = gdk_pixbuf_get_width (pb);
1151 int h = gdk_pixbuf_get_height (pb);
1152 int x, y, i;
1153 guchar *dst;
1154 int bpp = gdk_pixbuf_get_n_channels (pb);
1155 guchar *src = gdk_pixbuf_get_pixels (pb);
1156 int sstr = gdk_pixbuf_get_rowstride (pb);
1157
1158 a85_init ();
1159
1160 for (y = 0; y < h; y++)
1161 for (x = 0; x < w; x++)
1162 for (i = 0; i < (bpp < 3 ? 1 : 3); i++)
1163 a85_push (fp, src [x * bpp + y * sstr + i]);
1164
1165 a85_finish (fp);
1166 }
1167
1168 void
1169 dump_binary (PerlIO *fp, GdkPixbuf *pb)
1170 CODE:
1171 {
1172 int w = gdk_pixbuf_get_width (pb);
1173 int h = gdk_pixbuf_get_height (pb);
1174 int x, y, i;
1175 guchar *dst;
1176 int bpp = gdk_pixbuf_get_n_channels (pb);
1177 guchar *src = gdk_pixbuf_get_pixels (pb);
1178 int sstr = gdk_pixbuf_get_rowstride (pb);
1179
1180 for (y = 0; y < h; y++)
1181 for (x = 0; x < w; x++)
1182 for (i = 0; i < (bpp < 3 ? 1 : 3); i++)
1183 PerlIO_putc (fp, src [x * bpp + y * sstr + i]);
1184 }
1185
1186 #############################################################################
1187
1188 MODULE = Gtk2::CV PACKAGE = Gtk2::CV
1189
1190 SV *
1191 pb_to_hv84 (GdkPixbuf *pb)
1192 CODE:
1193 {
1194 int w = gdk_pixbuf_get_width (pb);
1195 int h = gdk_pixbuf_get_height (pb);
1196 int x, y;
1197 guchar *dst;
1198 int bpp = gdk_pixbuf_get_n_channels (pb);
1199 guchar *src = gdk_pixbuf_get_pixels (pb);
1200 int sstr = gdk_pixbuf_get_rowstride (pb);
1201
1202 RETVAL = newSV (6 * 8 * 12 / 8);
1203 SvPOK_only (RETVAL);
1204 SvCUR_set (RETVAL, 6 * 8 * 12 / 8);
1205
1206 dst = (guchar *)SvPVX (RETVAL);
1207
1208 /* some primitive error distribution + random dithering */
1209
1210 for (y = 0; y < h; y++)
1211 {
1212 guchar *p = src + y * sstr;
1213
1214 for (x = 0; x < w; x += 2)
1215 {
1216 unsigned int r, g, b, h, s, v, H, V1, V2;
1217
1218 if (bpp == 3)
1219 r = *p++, g = *p++, b = *p++;
1220 else if (bpp == 1)
1221 r = g = b = *p++;
1222 else
1223 abort ();
1224
1225 rgb_to_hsv (r, g, b, &h, &s, &v);
1226
1227 H = (h * 15 / 255) << 4;
1228 V1 = v;
1229
1230 if (bpp == 3)
1231 r = *p++, g = *p++, b = *p++;
1232 else if (bpp == 1)
1233 r = g = b = *p++;
1234 else
1235 abort ();
1236
1237 rgb_to_hsv (r, g, b, &h, &s, &v);
1238
1239 H |= h * 15 / 255;
1240 V2 = v;
1241
1242 *dst++ = H;
1243 *dst++ = V1;
1244 *dst++ = V2;
1245 }
1246 }
1247 }
1248 OUTPUT:
1249 RETVAL
1250
1251 SV *
1252 hv84_to_av (unsigned char *hv84)
1253 CODE:
1254 {
1255 int i = 72 / 3;
1256 AV *av = newAV ();
1257
1258 RETVAL = (SV *)newRV_noinc ((SV *)av);
1259 while (i--)
1260 {
1261 int h = *hv84++;
1262 int v1 = *hv84++;
1263 int v2 = *hv84++;
1264
1265 av_push (av, newSViv (v1));
1266 av_push (av, newSViv ((h >> 4) * 255 / 15));
1267 av_push (av, newSViv (v2));
1268 av_push (av, newSViv ((h & 15) * 255 / 15));
1269 }
1270 }
1271 OUTPUT:
1272 RETVAL
1273
1274 #############################################################################
1275
1276 MODULE = Gtk2::CV PACKAGE = Gtk2::CV::Plugin::RCluster
1277
1278 SV *
1279 extract_features (SV *ar)
1280 CODE:
1281 {
1282 int i;
1283 AV *av, *result;
1284
1285 if (!SvROK (ar) || SvTYPE (SvRV (ar)) != SVt_PVAV)
1286 croak ("Not an array ref as first argument to extract_features");
1287
1288 av = (AV *) SvRV (ar);
1289 result = newAV ();
1290
1291 for (i = 0; i <= av_len (av); ++i)
1292 {
1293 SV *sv = *av_fetch (av, i, 1);
1294 SV *histsv = newSV (9 * sizeof (float) + 1);
1295
1296 SvPOK_on (histsv);
1297 SvCUR_set (histsv, 9 * sizeof (float));
1298 float *hist = (float *)SvPVX (histsv);
1299
1300 struct feature f_h, f_s, f_v;
1301 feature_init (&f_h);
1302 feature_init (&f_s);
1303 feature_init (&f_v);
1304
1305 {
1306 STRLEN len;
1307 unsigned char *buf = (unsigned char *)SvPVbyte (sv, len);
1308 while (len >= 3)
1309 {
1310 unsigned int r, g, b, h, s, v;
1311 r = *buf++; g = *buf++; b = *buf++;
1312 rgb_to_hsv (r, g, b, &h, &s, &v);
1313
1314 feature_update_pass_1 (&f_h, h);
1315 feature_update_pass_1 (&f_s, s);
1316 feature_update_pass_1 (&f_v, v);
1317
1318 len -= 3;
1319 }
1320
1321 feature_finish_pass_1 (&f_h);
1322 feature_finish_pass_1 (&f_s);
1323 feature_finish_pass_1 (&f_v);
1324 }
1325
1326 {
1327 STRLEN len;
1328 unsigned char *buf = (unsigned char *)SvPVbyte (sv, len);
1329 while (len >= 3)
1330 {
1331 unsigned int r, g, b, h, s, v;
1332 r = *buf++; g = *buf++; b = *buf++;
1333 rgb_to_hsv (r, g, b, &h, &s, &v);
1334
1335 feature_update_pass_2 (&f_h, h);
1336 feature_update_pass_2 (&f_s, s);
1337 feature_update_pass_2 (&f_v, v);
1338
1339 len -= 3;
1340 }
1341
1342 feature_finish_pass_2 (&f_h);
1343 feature_finish_pass_2 (&f_s);
1344 feature_finish_pass_2 (&f_v);
1345 }
1346
1347 hist [0] = f_h.v1 * 2.; hist [1] = f_h.v2 * 2.; hist [2] = f_h.v3 * 2.;
1348 hist [3] = f_s.v1 ; hist [4] = f_s.v2 ; hist [5] = f_s.v3 ;
1349 hist [6] = f_v.v1 * .5; hist [7] = f_v.v2 * .5; hist [8] = f_v.v3 * .5;
1350
1351 av_push (result, histsv);
1352 }
1353
1354 RETVAL = newRV_noinc ((SV *)result);
1355 }
1356 OUTPUT:
1357 RETVAL
1358