-
Notifications
You must be signed in to change notification settings - Fork 136
/
Copy pathconvert-to-nia.c
1043 lines (940 loc) · 35.4 KB
/
convert-to-nia.c
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
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2020 The Wuffs Authors.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//
// SPDX-License-Identifier: Apache-2.0 OR MIT
// ----------------
/*
convert-to-nia converts an image from stdin (e.g. in the BMP, GIF, JPEG or PNG
format) to stdout (in the NIA/NIE format).
See the "const char* g_usage" string below for details.
An equivalent program (using the Chromium image codecs) is at:
https://chromium-review.googlesource.com/c/chromium/src/+/2210331
An equivalent program (using the Skia image codecs) is at:
https://skia-review.googlesource.com/c/skia/+/290618
Define the DECODE_ONLY_JPEG macro to limit the variety of image file formats
that Wuffs decodes to just JPEG, for smaller binaries and faster compiles.
*/
#include <errno.h>
#include <inttypes.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
// Wuffs ships as a "single file C library" or "header file library" as per
// https://github.com/nothings/stb/blob/master/docs/stb_howto.txt
//
// To use that single file as a "foo.c"-like implementation, instead of a
// "foo.h"-like header, #define WUFFS_IMPLEMENTATION before #include'ing or
// compiling it.
#define WUFFS_IMPLEMENTATION
// Defining the WUFFS_CONFIG__STATIC_FUNCTIONS macro is optional, but when
// combined with WUFFS_IMPLEMENTATION, it demonstrates making all of Wuffs'
// functions have static storage.
//
// This can help the compiler ignore or discard unused code, which can produce
// faster compiles and smaller binaries. Other motivations are discussed in the
// "ALLOW STATIC IMPLEMENTATION" section of
// https://raw.githubusercontent.com/nothings/stb/master/docs/stb_howto.txt
#define WUFFS_CONFIG__STATIC_FUNCTIONS
// Defining the WUFFS_CONFIG__MODULE* macros are optional, but it lets users of
// release/c/etc.c choose which parts of Wuffs to build. That file contains the
// entire Wuffs standard library, implementing a variety of codecs and file
// formats. Without this macro definition, an optimizing compiler or linker may
// very well discard Wuffs code for unused codecs, but listing the Wuffs
// modules we use makes that process explicit. Preprocessing means that such
// code simply isn't compiled.
#define WUFFS_CONFIG__MODULES
#define WUFFS_CONFIG__MODULE__BASE
#define WUFFS_CONFIG__MODULE__CRC32
#define WUFFS_CONFIG__MODULE__JPEG
#if !defined(DECODE_ONLY_JPEG)
#define WUFFS_CONFIG__MODULE__ADLER32
#define WUFFS_CONFIG__MODULE__BMP
#define WUFFS_CONFIG__MODULE__DEFLATE
#define WUFFS_CONFIG__MODULE__ETC2
#define WUFFS_CONFIG__MODULE__GIF
#define WUFFS_CONFIG__MODULE__NETPBM
#define WUFFS_CONFIG__MODULE__NIE
#define WUFFS_CONFIG__MODULE__PNG
#define WUFFS_CONFIG__MODULE__QOI
#define WUFFS_CONFIG__MODULE__TARGA
#define WUFFS_CONFIG__MODULE__THUMBHASH
#define WUFFS_CONFIG__MODULE__VP8
#define WUFFS_CONFIG__MODULE__WBMP
#define WUFFS_CONFIG__MODULE__WEBP
#define WUFFS_CONFIG__MODULE__ZLIB
#endif
// Defining the WUFFS_CONFIG__DST_PIXEL_FORMAT__ENABLE_ALLOWLIST (and the
// associated ETC__ALLOW_FOO) macros are optional, but can lead to smaller
// programs (in terms of binary size). By default (without these macros),
// Wuffs' standard library can decode images to a variety of pixel formats,
// such as BGR_565, BGRA_PREMUL or RGBA_NONPREMUL. The destination pixel format
// is selectable at runtime. Using these macros essentially makes the selection
// at compile time, by narrowing the list of supported destination pixel
// formats. The FOO in ETC__ALLOW_FOO should match the pixel format passed (as
// part of the wuffs_base__image_config argument) to the decode_frame method.
//
// If using the wuffs_aux C++ API, without overriding the SelectPixfmt method,
// the implicit destination pixel format is BGRA_PREMUL.
#define WUFFS_CONFIG__DST_PIXEL_FORMAT__ENABLE_ALLOWLIST
#define WUFFS_CONFIG__DST_PIXEL_FORMAT__ALLOW_BGRA_NONPREMUL
// If building this program in an environment that doesn't easily accommodate
// relative includes, you can use the script/inline-c-relative-includes.go
// program to generate a stand-alone C file.
#include "../../release/c/wuffs-unsupported-snapshot.c"
#define UNCOMPNG_CONFIG__STATIC_FUNCTIONS
#define UNCOMPNG_IMPLEMENTATION
#include "../../snippet/uncompng.c"
// ----
#if defined(__linux__)
#include <linux/seccomp.h>
#include <sys/prctl.h>
#include <sys/syscall.h>
#define WUFFS_EXAMPLE_USE_SECCOMP
#endif
#define TRY(error_msg) \
do { \
const char* z = error_msg; \
if (z) { \
return z; \
} \
} while (false)
static const char* g_usage =
"Usage: convert-to-nia -flags < src.img > dst.nia\n"
"\n"
"Flags:\n"
" -1 -first-frame-only\n"
" -d -output-crc32-digest\n"
" -p -output-netpbm\n"
" -u -output-uncompressed-png\n"
" -fail-if-unsandboxed\n"
"\n"
"convert-to-nia converts an image from stdin (e.g. in the BMP, GIF, JPEG\n"
"or PNG format) to stdout (in the NIA format, or in the NIE, hash, PPM\n"
"or PNG format if the -1, -d, -p or -u flag is given).\n"
"\n"
"NIA/NIE is a trivial animated/still image file format, specified at\n"
"https://github.com/google/wuffs/blob/main/doc/spec/nie-spec.md\n"
"\n"
"Using -d produces just the CRC-32/IEEE digest of the NIA form. Storing\n"
"shorter hashes is cheaper than storing complete NIA files but comparing\n"
"hashes can still detect most changes in codec output.\n"
"\n"
"Using -p means that this program outputs the same format as djpeg. PPM\n"
"(color) and PGM (gray) are also trivial still image file formats. They\n"
"do not support alpha or animation.\n"
"\n"
"Using -u produces PNG output that's relatively large for PNG but still\n"
"perfectly valid, suitable for piping to tools like cwebp or pngcrush.\n"
"\n"
"The -fail-if-unsandboxed flag causes the program to exit if it does not\n"
"self-impose a sandbox. On Linux, it self-imposes a SECCOMP_MODE_STRICT\n"
"sandbox, regardless of whether this flag was set.";
// ----
#define STDIN_FD 0
#define STDOUT_FD 1
#define STDERR_FD 2
bool g_sandboxed = false;
wuffs_base__pixel_buffer g_pixbuf = {0};
wuffs_base__io_buffer g_src = {0};
wuffs_base__slice_u8 g_pixbuf_slice = {0};
wuffs_base__slice_u8 g_pixbuf_backup_slice = {0};
wuffs_base__slice_u8 g_workbuf_slice = {0};
wuffs_base__image_config g_image_config = {0};
wuffs_base__frame_config g_frame_config = {0};
int32_t g_fourcc = 0;
uint32_t g_width = 0;
uint32_t g_height = 0;
bool g_pixfmt_is_gray = false;
uint32_t g_num_animation_loops = 0;
uint64_t g_num_printed_frames = 0;
wuffs_base__image_decoder* g_image_decoder = NULL;
union {
wuffs_jpeg__decoder jpeg;
#if !defined(DECODE_ONLY_JPEG)
wuffs_bmp__decoder bmp;
wuffs_etc2__decoder etc2;
wuffs_gif__decoder gif;
wuffs_netpbm__decoder netpbm;
wuffs_nie__decoder nie;
wuffs_png__decoder png;
wuffs_qoi__decoder qoi;
wuffs_targa__decoder targa;
wuffs_thumbhash__decoder thumbhash;
wuffs_wbmp__decoder wbmp;
wuffs_webp__decoder webp;
#endif
} g_potential_decoders;
wuffs_crc32__ieee_hasher g_digest_hasher;
// ----
#define BYTES_PER_PIXEL 4
#ifndef MAX_DIMENSION
#define MAX_DIMENSION 65535
#endif
#ifndef SRC_BUFFER_ARRAY_SIZE
#define SRC_BUFFER_ARRAY_SIZE (64 * 1024)
#endif
#ifndef WORKBUF_ARRAY_SIZE
#define WORKBUF_ARRAY_SIZE (256 * 1024 * 1024)
#endif
#ifndef PIXBUF_ARRAY_SIZE
#define PIXBUF_ARRAY_SIZE (256 * 1024 * 1024)
#endif
// Uncomment this #define (or use a C compiler flag) to decode very large
// images like test/3pdata/blinksuite/large-size-image-crash.jpeg which is
// 48010 * 16173 = 776_465730 pixels, roughly 2.9 GiB at 4 bytes per pixel.
//
// This requires calling malloc (before self-imposing a SECCOMP_MODE_STRICT
// sandbox). By default (without this #define), the buffers are statically
// allocated and do not require syscalls.
//
// #define ALLOW_GIGABYTES_OF_PIXEL_BUFFERS 1
uint8_t g_src_buffer_array[SRC_BUFFER_ARRAY_SIZE] = {0};
#if !defined(ALLOW_GIGABYTES_OF_PIXEL_BUFFERS)
uint8_t g_workbuf_array[WORKBUF_ARRAY_SIZE] = {0};
uint8_t g_pixbuf_array[PIXBUF_ARRAY_SIZE] = {0};
#endif
// ----
struct {
int remaining_argc;
char** remaining_argv;
bool fail_if_unsandboxed;
bool first_frame_only;
bool output_crc32_digest;
bool output_netpbm;
bool output_uncompressed_png;
} g_flags = {0};
const char* //
parse_flags(int argc, char** argv) {
int c = (argc > 0) ? 1 : 0; // Skip argv[0], the program name.
for (; c < argc; c++) {
char* arg = argv[c];
if (*arg++ != '-') {
break;
}
// A double-dash "--foo" is equivalent to a single-dash "-foo". As special
// cases, a bare "-" is not a flag (some programs may interpret it as
// stdin) and a bare "--" means to stop parsing flags.
if (*arg == '\x00') {
break;
} else if (*arg == '-') {
arg++;
if (*arg == '\x00') {
c++;
break;
}
}
if (!strcmp(arg, "fail-if-unsandboxed")) {
g_flags.fail_if_unsandboxed = true;
continue;
}
if (!strcmp(arg, "1") || !strcmp(arg, "first-frame-only")) {
g_flags.first_frame_only = true;
continue;
}
if (!strcmp(arg, "d") || !strcmp(arg, "output-crc32-digest")) {
if (g_flags.output_crc32_digest || g_flags.output_netpbm ||
g_flags.output_uncompressed_png) {
return "main: multiple --output-etc flags";
}
g_flags.output_crc32_digest = true;
continue;
}
if (!strcmp(arg, "p") || !strcmp(arg, "output-netpbm")) {
if (g_flags.output_crc32_digest || g_flags.output_netpbm ||
g_flags.output_uncompressed_png) {
return "main: multiple --output-etc flags";
}
g_flags.output_netpbm = true;
continue;
}
if (!strcmp(arg, "u") || !strcmp(arg, "output-uncompressed-png")) {
if (g_flags.output_crc32_digest || g_flags.output_netpbm ||
g_flags.output_uncompressed_png) {
return "main: multiple --output-etc flags";
}
g_flags.output_uncompressed_png = true;
continue;
}
return g_usage;
}
if (!g_flags.first_frame_only) {
// No-op.
} else if (g_flags.output_crc32_digest || //
g_flags.output_netpbm || //
g_flags.output_uncompressed_png) {
return g_usage;
}
g_flags.remaining_argc = argc - c;
g_flags.remaining_argv = argv + c;
return NULL;
}
// ----
// ignore_return_value suppresses errors from -Wall -Werror.
static void //
ignore_return_value(int ignored) {}
ssize_t //
write_to_stdout(const void* ptr, size_t len) {
if (len > SSIZE_MAX) {
return -EFBIG;
} else if (!g_flags.output_crc32_digest) {
return write(STDOUT_FD, ptr, len);
}
wuffs_crc32__ieee_hasher__update(
&g_digest_hasher, wuffs_base__make_slice_u8((uint8_t*)ptr, len));
return (ssize_t)len;
}
const char* //
read_more_src() {
if (g_src.meta.closed) {
return "main: unexpected end of file";
}
wuffs_base__io_buffer__compact(&g_src);
if (g_src.meta.wi == g_src.data.len) {
return "main: internal error: no I/O progress possible";
}
ssize_t n = read(STDIN_FD, g_src.data.ptr + g_src.meta.wi,
g_src.data.len - g_src.meta.wi);
if (n > 0) {
g_src.meta.wi += n;
} else if (n == 0) {
g_src.meta.closed = true;
} else if (errno != EINTR) {
return strerror(errno);
}
return NULL;
}
const char* //
load_image_type() {
g_fourcc = 0;
while (true) {
g_fourcc = wuffs_base__magic_number_guess_fourcc(
wuffs_base__io_buffer__reader_slice(&g_src), g_src.meta.closed);
if ((g_fourcc >= 0) ||
(wuffs_base__io_buffer__reader_length(&g_src) == g_src.data.len)) {
break;
}
TRY(read_more_src());
}
return NULL;
}
const char* //
initialize_image_decoder() {
wuffs_base__status status;
switch (g_fourcc) {
case WUFFS_BASE__FOURCC__JPEG:
status = wuffs_jpeg__decoder__initialize(
&g_potential_decoders.jpeg, sizeof g_potential_decoders.jpeg,
WUFFS_VERSION, WUFFS_INITIALIZE__DEFAULT_OPTIONS);
TRY(wuffs_base__status__message(&status));
g_image_decoder =
wuffs_jpeg__decoder__upcast_as__wuffs_base__image_decoder(
&g_potential_decoders.jpeg);
return NULL;
#if !defined(DECODE_ONLY_JPEG)
case WUFFS_BASE__FOURCC__BMP:
status = wuffs_bmp__decoder__initialize(
&g_potential_decoders.bmp, sizeof g_potential_decoders.bmp,
WUFFS_VERSION, WUFFS_INITIALIZE__DEFAULT_OPTIONS);
TRY(wuffs_base__status__message(&status));
g_image_decoder =
wuffs_bmp__decoder__upcast_as__wuffs_base__image_decoder(
&g_potential_decoders.bmp);
return NULL;
case WUFFS_BASE__FOURCC__ETC2:
status = wuffs_etc2__decoder__initialize(
&g_potential_decoders.etc2, sizeof g_potential_decoders.etc2,
WUFFS_VERSION, WUFFS_INITIALIZE__DEFAULT_OPTIONS);
TRY(wuffs_base__status__message(&status));
g_image_decoder =
wuffs_etc2__decoder__upcast_as__wuffs_base__image_decoder(
&g_potential_decoders.etc2);
return NULL;
case WUFFS_BASE__FOURCC__GIF:
status = wuffs_gif__decoder__initialize(
&g_potential_decoders.gif, sizeof g_potential_decoders.gif,
WUFFS_VERSION, WUFFS_INITIALIZE__DEFAULT_OPTIONS);
TRY(wuffs_base__status__message(&status));
g_image_decoder =
wuffs_gif__decoder__upcast_as__wuffs_base__image_decoder(
&g_potential_decoders.gif);
return NULL;
case WUFFS_BASE__FOURCC__NIE:
status = wuffs_nie__decoder__initialize(
&g_potential_decoders.nie, sizeof g_potential_decoders.nie,
WUFFS_VERSION, WUFFS_INITIALIZE__DEFAULT_OPTIONS);
TRY(wuffs_base__status__message(&status));
g_image_decoder =
wuffs_nie__decoder__upcast_as__wuffs_base__image_decoder(
&g_potential_decoders.nie);
return NULL;
case WUFFS_BASE__FOURCC__NPBM:
status = wuffs_netpbm__decoder__initialize(
&g_potential_decoders.netpbm, sizeof g_potential_decoders.netpbm,
WUFFS_VERSION, WUFFS_INITIALIZE__DEFAULT_OPTIONS);
TRY(wuffs_base__status__message(&status));
g_image_decoder =
wuffs_netpbm__decoder__upcast_as__wuffs_base__image_decoder(
&g_potential_decoders.netpbm);
return NULL;
case WUFFS_BASE__FOURCC__PNG:
status = wuffs_png__decoder__initialize(
&g_potential_decoders.png, sizeof g_potential_decoders.png,
WUFFS_VERSION, WUFFS_INITIALIZE__DEFAULT_OPTIONS);
TRY(wuffs_base__status__message(&status));
g_image_decoder =
wuffs_png__decoder__upcast_as__wuffs_base__image_decoder(
&g_potential_decoders.png);
return NULL;
case WUFFS_BASE__FOURCC__QOI:
status = wuffs_qoi__decoder__initialize(
&g_potential_decoders.qoi, sizeof g_potential_decoders.qoi,
WUFFS_VERSION, WUFFS_INITIALIZE__DEFAULT_OPTIONS);
TRY(wuffs_base__status__message(&status));
g_image_decoder =
wuffs_qoi__decoder__upcast_as__wuffs_base__image_decoder(
&g_potential_decoders.qoi);
return NULL;
case WUFFS_BASE__FOURCC__TGA:
status = wuffs_targa__decoder__initialize(
&g_potential_decoders.targa, sizeof g_potential_decoders.targa,
WUFFS_VERSION, WUFFS_INITIALIZE__DEFAULT_OPTIONS);
TRY(wuffs_base__status__message(&status));
g_image_decoder =
wuffs_targa__decoder__upcast_as__wuffs_base__image_decoder(
&g_potential_decoders.targa);
return NULL;
case WUFFS_BASE__FOURCC__TH:
status = wuffs_thumbhash__decoder__initialize(
&g_potential_decoders.thumbhash,
sizeof g_potential_decoders.thumbhash, WUFFS_VERSION,
WUFFS_INITIALIZE__DEFAULT_OPTIONS);
TRY(wuffs_base__status__message(&status));
g_image_decoder =
wuffs_thumbhash__decoder__upcast_as__wuffs_base__image_decoder(
&g_potential_decoders.thumbhash);
return NULL;
case WUFFS_BASE__FOURCC__WBMP:
status = wuffs_wbmp__decoder__initialize(
&g_potential_decoders.wbmp, sizeof g_potential_decoders.wbmp,
WUFFS_VERSION, WUFFS_INITIALIZE__DEFAULT_OPTIONS);
TRY(wuffs_base__status__message(&status));
g_image_decoder =
wuffs_wbmp__decoder__upcast_as__wuffs_base__image_decoder(
&g_potential_decoders.wbmp);
return NULL;
case WUFFS_BASE__FOURCC__WEBP:
status = wuffs_webp__decoder__initialize(
&g_potential_decoders.webp, sizeof g_potential_decoders.webp,
WUFFS_VERSION, WUFFS_INITIALIZE__DEFAULT_OPTIONS);
TRY(wuffs_base__status__message(&status));
g_image_decoder =
wuffs_webp__decoder__upcast_as__wuffs_base__image_decoder(
&g_potential_decoders.webp);
return NULL;
#endif
}
return "main: unsupported file format";
}
const char* //
advance_for_redirect() {
wuffs_base__io_buffer empty = wuffs_base__empty_io_buffer();
wuffs_base__more_information minfo = wuffs_base__empty_more_information();
wuffs_base__status status = wuffs_base__image_decoder__tell_me_more(
g_image_decoder, &empty, &minfo, &g_src);
if (status.repr != NULL) {
return wuffs_base__status__message(&status);
} else if (minfo.flavor !=
WUFFS_BASE__MORE_INFORMATION__FLAVOR__IO_REDIRECT) {
return "main: unsupported file format";
}
g_fourcc =
(int32_t)(wuffs_base__more_information__io_redirect__fourcc(&minfo));
if (g_fourcc <= 0) {
return "main: unsupported file format";
}
// Advance g_src's reader_position to pos.
uint64_t pos =
wuffs_base__more_information__io_redirect__range(&minfo).min_incl;
if (pos < wuffs_base__io_buffer__reader_position(&g_src)) {
// Redirects must go forward.
return "main: unsupported file format";
}
while (true) {
uint64_t relative_pos =
pos - wuffs_base__io_buffer__reader_position(&g_src);
if (relative_pos <= (g_src.meta.wi - g_src.meta.ri)) {
g_src.meta.ri += relative_pos;
break;
}
g_src.meta.ri = g_src.meta.wi;
TRY(read_more_src());
}
return NULL;
}
const char* //
load_image_config() {
bool redirected = false;
redirect:
TRY(initialize_image_decoder());
// Decode the wuffs_base__image_config.
while (true) {
wuffs_base__status status = wuffs_base__image_decoder__decode_image_config(
g_image_decoder, &g_image_config, &g_src);
if (status.repr == NULL) {
break;
} else if (status.repr == wuffs_base__note__i_o_redirect) {
if (redirected) {
return "main: unsupported file format";
}
redirected = true;
TRY(advance_for_redirect());
goto redirect;
} else if (status.repr != wuffs_base__suspension__short_read) {
return wuffs_base__status__message(&status);
}
TRY(read_more_src());
}
// Read the dimensions.
uint32_t w = wuffs_base__pixel_config__width(&g_image_config.pixcfg);
uint32_t h = wuffs_base__pixel_config__height(&g_image_config.pixcfg);
if ((w > MAX_DIMENSION) || (h > MAX_DIMENSION)) {
return "main: image is too large";
}
g_width = w;
g_height = h;
switch (wuffs_base__pixel_config__pixel_format(&g_image_config.pixcfg).repr) {
case WUFFS_BASE__PIXEL_FORMAT__Y:
case WUFFS_BASE__PIXEL_FORMAT__Y_16LE:
case WUFFS_BASE__PIXEL_FORMAT__Y_16BE:
g_pixfmt_is_gray = true;
break;
default:
g_pixfmt_is_gray = false;
break;
}
// Override the image's native pixel format to be BGRA_NONPREMUL.
wuffs_base__pixel_config__set(&g_image_config.pixcfg,
WUFFS_BASE__PIXEL_FORMAT__BGRA_NONPREMUL,
WUFFS_BASE__PIXEL_SUBSAMPLING__NONE, w, h);
// Configure the work buffer.
uint64_t workbuf_len =
wuffs_base__image_decoder__workbuf_len(g_image_decoder).max_incl;
if (g_workbuf_slice.len < workbuf_len) {
return "main: image is too large (to configure work buffer)";
}
g_workbuf_slice.len = workbuf_len;
// Configure the pixel buffer and (if there's capacity) its backup buffer.
uint64_t num_pixels = ((uint64_t)w) * ((uint64_t)h);
if (g_pixbuf_slice.len < (num_pixels * BYTES_PER_PIXEL)) {
return "main: image is too large (to configure pixel buffer)";
}
size_t old_pixbuf_slice_len = g_pixbuf_slice.len;
g_pixbuf_slice.len = num_pixels * BYTES_PER_PIXEL;
size_t pixbuf_array_remaining = old_pixbuf_slice_len - g_pixbuf_slice.len;
if (pixbuf_array_remaining >= g_pixbuf_slice.len) {
g_pixbuf_backup_slice.ptr = g_pixbuf_slice.ptr + g_pixbuf_slice.len;
g_pixbuf_backup_slice.len = g_pixbuf_slice.len;
}
// Configure the wuffs_base__pixel_buffer struct.
wuffs_base__status status = wuffs_base__pixel_buffer__set_from_slice(
&g_pixbuf, &g_image_config.pixcfg, g_pixbuf_slice);
TRY(wuffs_base__status__message(&status));
wuffs_base__table_u8 tab = wuffs_base__pixel_buffer__plane(&g_pixbuf, 0);
if ((tab.width != (g_width * BYTES_PER_PIXEL)) || (tab.height != g_height)) {
return "main: inconsistent pixel buffer dimensions";
}
return NULL;
}
void //
fill_rectangle(wuffs_base__rect_ie_u32 rect,
wuffs_base__color_u32_argb_premul color) {
if (rect.max_excl_x > g_width) {
rect.max_excl_x = g_width;
}
if (rect.max_excl_y > g_height) {
rect.max_excl_y = g_height;
}
uint32_t nonpremul =
wuffs_base__color_u32_argb_premul__as__color_u32_argb_nonpremul(color);
wuffs_base__table_u8 tab = wuffs_base__pixel_buffer__plane(&g_pixbuf, 0);
for (uint32_t y = rect.min_incl_y; y < rect.max_excl_y; y++) {
uint8_t* p =
tab.ptr + (y * tab.stride) + (rect.min_incl_x * BYTES_PER_PIXEL);
for (uint32_t x = rect.min_incl_x; x < rect.max_excl_x; x++) {
wuffs_base__poke_u32le__no_bounds_check(p, nonpremul);
p += BYTES_PER_PIXEL;
}
}
}
void //
print_nix_header(uint32_t magic_u32le) {
static const uint32_t version1_bn4_u32le = 0x346E62FF;
uint8_t data[16];
wuffs_base__poke_u32le__no_bounds_check(data + 0x00, magic_u32le);
wuffs_base__poke_u32le__no_bounds_check(data + 0x04, version1_bn4_u32le);
wuffs_base__poke_u32le__no_bounds_check(data + 0x08, g_width);
wuffs_base__poke_u32le__no_bounds_check(data + 0x0C, g_height);
ignore_return_value(write_to_stdout(&data[0], 16));
}
void //
print_netpbm_header() {
char data[256];
int n = snprintf(data, sizeof(data), "P%c\n%" PRIu32 " %" PRIu32 "\n255\n",
(g_pixfmt_is_gray ? '5' : '6'), g_width, g_height);
ignore_return_value(write_to_stdout(&data[0], n));
}
void //
print_nia_duration(wuffs_base__flicks duration) {
uint8_t data[8];
wuffs_base__poke_u64le__no_bounds_check(data + 0x00, duration);
ignore_return_value(write_to_stdout(&data[0], 8));
}
void //
print_nie_frame() {
g_num_printed_frames++;
print_nix_header(0x45AFC36E); // "nïE" as a u32le.
wuffs_base__table_u8 tab = wuffs_base__pixel_buffer__plane(&g_pixbuf, 0);
if (tab.width == tab.stride) {
ignore_return_value(write_to_stdout(tab.ptr, tab.width * tab.height));
} else {
for (size_t y = 0; y < tab.height; y++) {
ignore_return_value(
write_to_stdout(tab.ptr + (y * tab.stride), tab.width));
}
}
}
void //
print_netpbm_frame() {
g_num_printed_frames++;
uint8_t data[4096];
size_t o = 0;
const size_t o_increment = g_pixfmt_is_gray ? 1 : 3;
wuffs_base__table_u8 tab = wuffs_base__pixel_buffer__plane(&g_pixbuf, 0);
for (size_t y = 0; y < tab.height; y++) {
const uint8_t* row = tab.ptr + (y * tab.stride);
for (size_t x = 0; x < tab.width; x += 4) {
data[o + 0] = row[x + 2];
data[o + 1] = row[x + 1];
data[o + 2] = row[x + 0];
o += o_increment;
if ((o + 3) > sizeof(data)) {
ignore_return_value(write_to_stdout(&data[0], o));
o = 0;
}
}
}
if (o > 0) {
ignore_return_value(write_to_stdout(&data[0], o));
o = 0;
}
}
int //
my_uncompng_write_func(void* context,
const uint8_t* data_ptr,
size_t data_len) {
ssize_t n = write_to_stdout(data_ptr, data_len);
return (n >= 0) ? 0 : -1;
}
bool //
print_uncompressed_png_frame() {
uint32_t pixfmt = 0;
if (g_pixfmt_is_gray) {
pixfmt = UNCOMPNG__PIXEL_FORMAT__YXXX;
} else if (wuffs_base__pixel_buffer__is_opaque(&g_pixbuf)) {
pixfmt = UNCOMPNG__PIXEL_FORMAT__BGRX;
} else {
pixfmt = UNCOMPNG__PIXEL_FORMAT__BGRA_NONPREMUL;
}
uint32_t w = wuffs_base__pixel_config__width(&g_pixbuf.pixcfg);
uint32_t h = wuffs_base__pixel_config__height(&g_pixbuf.pixcfg);
wuffs_base__table_u8 tab = wuffs_base__pixel_buffer__plane(&g_pixbuf, 0);
return UNCOMPNG__RESULT__OK ==
uncompng__encode(&my_uncompng_write_func, NULL, tab.ptr,
wuffs_base__table__flattened_length(
tab.width, tab.height, tab.stride),
w, h, tab.stride, pixfmt);
}
void //
print_nia_padding() {
if (g_width & g_height & 1) {
uint8_t data[4];
wuffs_base__poke_u32le__no_bounds_check(data + 0x00, 0);
ignore_return_value(write_to_stdout(&data[0], 4));
}
}
void //
print_nia_footer() {
// For still (non-animated) images, the number of animation loops has no
// practical effect: the pixels on screen do not change over time regardless
// of its value. In the wire format encoding, there might be no explicit
// "number of animation loops" value listed in the source bytes. Various
// codec implementations may therefore choose an implicit default of 0 ("loop
// forever") or 1 ("loop exactly once"). Either is equally valid.
//
// However, when comparing the output of this convert-to-NIA program (backed
// by Wuffs' image codecs) with other convert-to-NIA programs, it is useful
// to canonicalize still images' "number of animation loops" to 0.
uint32_t n = g_num_animation_loops;
if (g_num_printed_frames <= 1) {
n = 0;
}
uint8_t data[8];
wuffs_base__poke_u32le__no_bounds_check(data + 0x00, n);
wuffs_base__poke_u32le__no_bounds_check(data + 0x04, 0x80000000);
ignore_return_value(write_to_stdout(&data[0], 8));
}
const char* //
convert_frames() {
wuffs_base__flicks total_duration = 0;
while (true) {
// Decode the wuffs_base__frame_config.
while (true) {
wuffs_base__status dfc_status =
wuffs_base__image_decoder__decode_frame_config(
g_image_decoder, &g_frame_config, &g_src);
if (dfc_status.repr == NULL) {
break;
} else if (dfc_status.repr == wuffs_base__note__end_of_data) {
return NULL;
} else if (dfc_status.repr != wuffs_base__suspension__short_read) {
return wuffs_base__status__message(&dfc_status);
}
TRY(read_more_src());
}
wuffs_base__flicks duration =
wuffs_base__frame_config__duration(&g_frame_config);
if (duration < 0) {
return "main: animation frame duration is negative";
} else if (total_duration > (INT64_MAX - duration)) {
return "main: animation frame duration overflow";
}
total_duration += duration;
if (wuffs_base__frame_config__index(&g_frame_config) == 0) {
fill_rectangle(
wuffs_base__pixel_config__bounds(&g_image_config.pixcfg),
wuffs_base__frame_config__background_color(&g_frame_config));
}
switch (wuffs_base__frame_config__disposal(&g_frame_config)) {
case WUFFS_BASE__ANIMATION_DISPOSAL__RESTORE_PREVIOUS: {
if (g_pixbuf_slice.len != g_pixbuf_backup_slice.len) {
return "main: image is too large (to configure pixel backup buffer)";
}
memcpy(g_pixbuf_backup_slice.ptr, g_pixbuf_slice.ptr,
g_pixbuf_slice.len);
break;
}
}
// Decode the frame (the pixels).
wuffs_base__status df_status;
const char* decode_frame_io_error_message = NULL;
while (true) {
df_status = wuffs_base__image_decoder__decode_frame(
g_image_decoder, &g_pixbuf, &g_src,
wuffs_base__frame_config__overwrite_instead_of_blend(&g_frame_config)
? WUFFS_BASE__PIXEL_BLEND__SRC
: WUFFS_BASE__PIXEL_BLEND__SRC_OVER,
g_workbuf_slice, NULL);
if (df_status.repr != wuffs_base__suspension__short_read) {
break;
}
decode_frame_io_error_message = read_more_src();
if (decode_frame_io_error_message != NULL) {
// Neuter the "short read" df_status so that convert_frames returns the
// I/O error message instead.
df_status.repr = NULL;
break;
}
}
// Update g_num_animation_loops. It's rare in practice, but the animation
// loop count can change over the course of decoding an image file.
//
// This program updates the global once per frame (even though the Wuffs
// API also lets you call wuffs_base__image_decoder__num_animation_loops
// just once, after the decoding is complete) to more closely match the
// Chromium web browser. This program emits (via print_nia_footer) the
// value from the final animation frame's update.
//
// Chromium image decoding uses two passes. (Wuffs' API lets you use a
// single pass but Chromium also wraps other libraries). Its first pass
// counts the number of animation frames (call it N). The second pass
// decodes exactly N frames. In particular, if the animation loop count
// would change between the end of frame N and the end of the file then
// Chromium's design will not pick up that change, even if it's a valid
// change in terms of the image file format.
//
// Specifically, for the test/data/artificial-gif/multiple-loop-counts.gif
// file this program emits 31 (0x1F) to match Chromium, even though the
// file arguably has a 41 (0x29) loop count after a complete decode.
g_num_animation_loops =
wuffs_base__image_decoder__num_animation_loops(g_image_decoder);
// Print a complete NIE frame (and surrounding bytes, for NIA).
if (g_flags.output_netpbm) {
print_netpbm_frame();
} else if (g_flags.output_uncompressed_png) {
if (!print_uncompressed_png_frame()) {
return "main: PNG encoding failed";
}
} else {
if (!g_flags.first_frame_only) {
print_nia_duration(total_duration);
}
print_nie_frame();
if (!g_flags.first_frame_only) {
print_nia_padding();
}
}
// Return early if there was an error decoding the frame.
if (df_status.repr != NULL) {
return wuffs_base__status__message(&df_status);
} else if (decode_frame_io_error_message != NULL) {
return decode_frame_io_error_message;
} else if (g_flags.first_frame_only || g_flags.output_netpbm ||
g_flags.output_uncompressed_png) {
return NULL;
}
// Dispose the frame.
switch (wuffs_base__frame_config__disposal(&g_frame_config)) {
case WUFFS_BASE__ANIMATION_DISPOSAL__RESTORE_BACKGROUND: {
fill_rectangle(
wuffs_base__frame_config__bounds(&g_frame_config),
wuffs_base__frame_config__background_color(&g_frame_config));
break;
}
case WUFFS_BASE__ANIMATION_DISPOSAL__RESTORE_PREVIOUS: {
if (g_pixbuf_slice.len != g_pixbuf_backup_slice.len) {
return "main: image is too large (to configure pixel backup buffer)";
}
memcpy(g_pixbuf_slice.ptr, g_pixbuf_backup_slice.ptr,
g_pixbuf_slice.len);
break;
}
}
}
return "main: unreachable";
}
const char* //
main1(int argc, char** argv) {
TRY(parse_flags(argc, argv));
if (g_flags.remaining_argc > 0) {
return "main: bad argument: use \"program < input\", not \"program input\"";
} else if (g_flags.fail_if_unsandboxed && !g_sandboxed) {
return "main: unsandboxed";
}
if (g_flags.output_crc32_digest) {
wuffs_base__status status = wuffs_crc32__ieee_hasher__initialize(
&g_digest_hasher, sizeof g_digest_hasher, WUFFS_VERSION,
WUFFS_INITIALIZE__DEFAULT_OPTIONS);
if (status.repr) {
return wuffs_base__status__message(&status);
}
}
g_src.data.ptr = g_src_buffer_array;
g_src.data.len = SRC_BUFFER_ARRAY_SIZE;
TRY(load_image_type());
TRY(load_image_config());
if (g_flags.output_netpbm) {
print_netpbm_header();
} else if (g_flags.output_uncompressed_png) {
// No-op.
} else if (!g_flags.first_frame_only) {
print_nix_header(0x41AFC36E); // "nïA" as a u32le.
}
const char* ret = convert_frames();
if (!g_flags.first_frame_only && !g_flags.output_netpbm &&
!g_flags.output_uncompressed_png) {
print_nia_footer();
}
return ret;
}
int //
compute_exit_code(const char* status_msg) {
if (!status_msg) {
return 0;
}
size_t n;
if (status_msg == g_usage) {
n = strlen(status_msg);
} else {
n = strnlen(status_msg, 2047);
if (n >= 2047) {
status_msg = "main: internal error: error message is too long";
n = strlen(status_msg);
}
}
ignore_return_value(write(STDERR_FD, status_msg, n));
ignore_return_value(write(STDERR_FD, "\n", 1));
// Return an exit code of 1 for regular (foreseen) errors, e.g. badly
// formatted or unsupported input.
//
// Return an exit code of 2 for internal (exceptional) errors, e.g. defensive
// run-time checks found that an internal invariant did not hold.
//
// Automated testing, including badly formatted inputs, can therefore
// discriminate between expected failure (exit code 1) and unexpected failure
// (other non-zero exit codes). Specifically, exit code 2 for internal
// invariant violation, exit code 139 (which is 128 + SIGSEGV on x86_64
// linux) for a segmentation fault (e.g. null pointer dereference).
return strstr(status_msg, "internal error:") ? 2 : 1;
}
void //
print_crc32_digest(bool bad) {
const char* hex = "0123456789abcdef";
uint32_t hash = wuffs_crc32__ieee_hasher__checksum_u32(&g_digest_hasher);
char buf[13];
memcpy(buf + 0, bad ? "BAD " : "OK. ", 4);
for (int i = 0; i < 8; i++) {
buf[4 + i] = hex[hash >> 28];
hash <<= 4;
}
buf[12] = '\n';
const int stdout_fd = 1;
ignore_return_value(write(stdout_fd, buf, 13));
}
int //
main(int argc, char** argv) {
#if !defined(ALLOW_GIGABYTES_OF_PIXEL_BUFFERS)