-
Notifications
You must be signed in to change notification settings - Fork 613
/
Copy pathYYImageCoder.m
2870 lines (2538 loc) · 112 KB
/
YYImageCoder.m
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
//
// YYImageCoder.m
// YYImage <https://github.com/ibireme/YYImage>
//
// Created by ibireme on 15/5/13.
// Copyright (c) 2015 ibireme.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import "YYImageCoder.h"
#import "YYImage.h"
#import <CoreFoundation/CoreFoundation.h>
#import <ImageIO/ImageIO.h>
#import <Accelerate/Accelerate.h>
#import <QuartzCore/QuartzCore.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import <objc/runtime.h>
#import <pthread.h>
#import <zlib.h>
#ifndef YYIMAGE_WEBP_ENABLED
#if __has_include(<webp/decode.h>) && __has_include(<webp/encode.h>) && \
__has_include(<webp/demux.h>) && __has_include(<webp/mux.h>)
#define YYIMAGE_WEBP_ENABLED 1
#import <webp/decode.h>
#import <webp/encode.h>
#import <webp/demux.h>
#import <webp/mux.h>
#elif __has_include("webp/decode.h") && __has_include("webp/encode.h") && \
__has_include("webp/demux.h") && __has_include("webp/mux.h")
#define YYIMAGE_WEBP_ENABLED 1
#import "webp/decode.h"
#import "webp/encode.h"
#import "webp/demux.h"
#import "webp/mux.h"
#else
#define YYIMAGE_WEBP_ENABLED 0
#endif
#endif
////////////////////////////////////////////////////////////////////////////////
#pragma mark - Utility (for little endian platform)
#define YY_FOUR_CC(c1,c2,c3,c4) ((uint32_t)(((c4) << 24) | ((c3) << 16) | ((c2) << 8) | (c1)))
#define YY_TWO_CC(c1,c2) ((uint16_t)(((c2) << 8) | (c1)))
static inline uint16_t yy_swap_endian_uint16(uint16_t value) {
return
(uint16_t) ((value & 0x00FF) << 8) |
(uint16_t) ((value & 0xFF00) >> 8) ;
}
static inline uint32_t yy_swap_endian_uint32(uint32_t value) {
return
(uint32_t)((value & 0x000000FFU) << 24) |
(uint32_t)((value & 0x0000FF00U) << 8) |
(uint32_t)((value & 0x00FF0000U) >> 8) |
(uint32_t)((value & 0xFF000000U) >> 24) ;
}
////////////////////////////////////////////////////////////////////////////////
#pragma mark - APNG
/*
PNG spec: http://www.libpng.org/pub/png/spec/1.2/PNG-Structure.html
APNG spec: https://wiki.mozilla.org/APNG_Specification
===============================================================================
PNG format:
header (8): 89 50 4e 47 0d 0a 1a 0a
chunk, chunk, chunk, ...
===============================================================================
chunk format:
length (4): uint32_t big endian
fourcc (4): chunk type code
data (length): data
crc32 (4): uint32_t big endian crc32(fourcc + data)
===============================================================================
PNG chunk define:
IHDR (Image Header) required, must appear first, 13 bytes
width (4) pixel count, should not be zero
height (4) pixel count, should not be zero
bit depth (1) expected: 1, 2, 4, 8, 16
color type (1) 1<<0 (palette used), 1<<1 (color used), 1<<2 (alpha channel used)
compression method (1) 0 (deflate/inflate)
filter method (1) 0 (adaptive filtering with five basic filter types)
interlace method (1) 0 (no interlace) or 1 (Adam7 interlace)
IDAT (Image Data) required, must appear consecutively if there's multiple 'IDAT' chunk
IEND (End) required, must appear last, 0 bytes
===============================================================================
APNG chunk define:
acTL (Animation Control) required, must appear before 'IDAT', 8 bytes
num frames (4) number of frames
num plays (4) number of times to loop, 0 indicates infinite looping
fcTL (Frame Control) required, must appear before the 'IDAT' or 'fdAT' chunks of the frame to which it applies, 26 bytes
sequence number (4) sequence number of the animation chunk, starting from 0
width (4) width of the following frame
height (4) height of the following frame
x offset (4) x position at which to render the following frame
y offset (4) y position at which to render the following frame
delay num (2) frame delay fraction numerator
delay den (2) frame delay fraction denominator
dispose op (1) type of frame area disposal to be done after rendering this frame (0:none, 1:background 2:previous)
blend op (1) type of frame area rendering for this frame (0:source, 1:over)
fdAT (Frame Data) required
sequence number (4) sequence number of the animation chunk
frame data (x) frame data for this frame (same as 'IDAT')
===============================================================================
`dispose_op` specifies how the output buffer should be changed at the end of the delay
(before rendering the next frame).
* NONE: no disposal is done on this frame before rendering the next; the contents
of the output buffer are left as is.
* BACKGROUND: the frame's region of the output buffer is to be cleared to fully
transparent black before rendering the next frame.
* PREVIOUS: the frame's region of the output buffer is to be reverted to the previous
contents before rendering the next frame.
`blend_op` specifies whether the frame is to be alpha blended into the current output buffer
content, or whether it should completely replace its region in the output buffer.
* SOURCE: all color components of the frame, including alpha, overwrite the current contents
of the frame's output buffer region.
* OVER: the frame should be composited onto the output buffer based on its alpha,
using a simple OVER operation as described in the "Alpha Channel Processing" section
of the PNG specification
*/
typedef enum {
YY_PNG_ALPHA_TYPE_PALEETE = 1 << 0,
YY_PNG_ALPHA_TYPE_COLOR = 1 << 1,
YY_PNG_ALPHA_TYPE_ALPHA = 1 << 2,
} yy_png_alpha_type;
typedef enum {
YY_PNG_DISPOSE_OP_NONE = 0,
YY_PNG_DISPOSE_OP_BACKGROUND = 1,
YY_PNG_DISPOSE_OP_PREVIOUS = 2,
} yy_png_dispose_op;
typedef enum {
YY_PNG_BLEND_OP_SOURCE = 0,
YY_PNG_BLEND_OP_OVER = 1,
} yy_png_blend_op;
typedef struct {
uint32_t width; ///< pixel count, should not be zero
uint32_t height; ///< pixel count, should not be zero
uint8_t bit_depth; ///< expected: 1, 2, 4, 8, 16
uint8_t color_type; ///< see yy_png_alpha_type
uint8_t compression_method; ///< 0 (deflate/inflate)
uint8_t filter_method; ///< 0 (adaptive filtering with five basic filter types)
uint8_t interlace_method; ///< 0 (no interlace) or 1 (Adam7 interlace)
} yy_png_chunk_IHDR;
typedef struct {
uint32_t sequence_number; ///< sequence number of the animation chunk, starting from 0
uint32_t width; ///< width of the following frame
uint32_t height; ///< height of the following frame
uint32_t x_offset; ///< x position at which to render the following frame
uint32_t y_offset; ///< y position at which to render the following frame
uint16_t delay_num; ///< frame delay fraction numerator
uint16_t delay_den; ///< frame delay fraction denominator
uint8_t dispose_op; ///< see yy_png_dispose_op
uint8_t blend_op; ///< see yy_png_blend_op
} yy_png_chunk_fcTL;
typedef struct {
uint32_t offset; ///< chunk offset in PNG data
uint32_t fourcc; ///< chunk fourcc
uint32_t length; ///< chunk data length
uint32_t crc32; ///< chunk crc32
} yy_png_chunk_info;
typedef struct {
uint32_t chunk_index; ///< the first `fdAT`/`IDAT` chunk index
uint32_t chunk_num; ///< the `fdAT`/`IDAT` chunk count
uint32_t chunk_size; ///< the `fdAT`/`IDAT` chunk bytes
yy_png_chunk_fcTL frame_control;
} yy_png_frame_info;
typedef struct {
yy_png_chunk_IHDR header; ///< png header
yy_png_chunk_info *chunks; ///< chunks
uint32_t chunk_num; ///< count of chunks
yy_png_frame_info *apng_frames; ///< frame info, NULL if not apng
uint32_t apng_frame_num; ///< 0 if not apng
uint32_t apng_loop_num; ///< 0 indicates infinite looping
uint32_t *apng_shared_chunk_indexs; ///< shared chunk index
uint32_t apng_shared_chunk_num; ///< shared chunk count
uint32_t apng_shared_chunk_size; ///< shared chunk bytes
uint32_t apng_shared_insert_index; ///< shared chunk insert index
bool apng_first_frame_is_cover; ///< the first frame is same as png (cover)
} yy_png_info;
static void yy_png_chunk_IHDR_read(yy_png_chunk_IHDR *IHDR, const uint8_t *data) {
IHDR->width = yy_swap_endian_uint32(*((uint32_t *)(data)));
IHDR->height = yy_swap_endian_uint32(*((uint32_t *)(data + 4)));
IHDR->bit_depth = data[8];
IHDR->color_type = data[9];
IHDR->compression_method = data[10];
IHDR->filter_method = data[11];
IHDR->interlace_method = data[12];
}
static void yy_png_chunk_IHDR_write(yy_png_chunk_IHDR *IHDR, uint8_t *data) {
*((uint32_t *)(data)) = yy_swap_endian_uint32(IHDR->width);
*((uint32_t *)(data + 4)) = yy_swap_endian_uint32(IHDR->height);
data[8] = IHDR->bit_depth;
data[9] = IHDR->color_type;
data[10] = IHDR->compression_method;
data[11] = IHDR->filter_method;
data[12] = IHDR->interlace_method;
}
static void yy_png_chunk_fcTL_read(yy_png_chunk_fcTL *fcTL, const uint8_t *data) {
fcTL->sequence_number = yy_swap_endian_uint32(*((uint32_t *)(data)));
fcTL->width = yy_swap_endian_uint32(*((uint32_t *)(data + 4)));
fcTL->height = yy_swap_endian_uint32(*((uint32_t *)(data + 8)));
fcTL->x_offset = yy_swap_endian_uint32(*((uint32_t *)(data + 12)));
fcTL->y_offset = yy_swap_endian_uint32(*((uint32_t *)(data + 16)));
fcTL->delay_num = yy_swap_endian_uint16(*((uint16_t *)(data + 20)));
fcTL->delay_den = yy_swap_endian_uint16(*((uint16_t *)(data + 22)));
fcTL->dispose_op = data[24];
fcTL->blend_op = data[25];
}
static void yy_png_chunk_fcTL_write(yy_png_chunk_fcTL *fcTL, uint8_t *data) {
*((uint32_t *)(data)) = yy_swap_endian_uint32(fcTL->sequence_number);
*((uint32_t *)(data + 4)) = yy_swap_endian_uint32(fcTL->width);
*((uint32_t *)(data + 8)) = yy_swap_endian_uint32(fcTL->height);
*((uint32_t *)(data + 12)) = yy_swap_endian_uint32(fcTL->x_offset);
*((uint32_t *)(data + 16)) = yy_swap_endian_uint32(fcTL->y_offset);
*((uint16_t *)(data + 20)) = yy_swap_endian_uint16(fcTL->delay_num);
*((uint16_t *)(data + 22)) = yy_swap_endian_uint16(fcTL->delay_den);
data[24] = fcTL->dispose_op;
data[25] = fcTL->blend_op;
}
// convert double value to fraction
static void yy_png_delay_to_fraction(double duration, uint16_t *num, uint16_t *den) {
if (duration >= 0xFF) {
*num = 0xFF;
*den = 1;
} else if (duration <= 1.0 / (double)0xFF) {
*num = 1;
*den = 0xFF;
} else {
// Use continued fraction to calculate the num and den.
long MAX = 10;
double eps = (0.5 / (double)0xFF);
long p[MAX], q[MAX], a[MAX], i, numl = 0, denl = 0;
// The first two convergents are 0/1 and 1/0
p[0] = 0; q[0] = 1;
p[1] = 1; q[1] = 0;
// The rest of the convergents (and continued fraction)
for (i = 2; i < MAX; i++) {
a[i] = lrint(floor(duration));
p[i] = a[i] * p[i - 1] + p[i - 2];
q[i] = a[i] * q[i - 1] + q[i - 2];
if (p[i] <= 0xFF && q[i] <= 0xFF) { // uint16_t
numl = p[i];
denl = q[i];
} else break;
if (fabs(duration - a[i]) < eps) break;
duration = 1.0 / (duration - a[i]);
}
if (numl != 0 && denl != 0) {
*num = numl;
*den = denl;
} else {
*num = 1;
*den = 100;
}
}
}
// convert fraction to double value
static double yy_png_delay_to_seconds(uint16_t num, uint16_t den) {
if (den == 0) {
return num / 100.0;
} else {
return (double)num / (double)den;
}
}
static bool yy_png_validate_animation_chunk_order(yy_png_chunk_info *chunks, /* input */
uint32_t chunk_num, /* input */
uint32_t *first_idat_index, /* output */
bool *first_frame_is_cover /* output */) {
/*
PNG at least contains 3 chunks: IHDR, IDAT, IEND.
`IHDR` must appear first.
`IDAT` must appear consecutively.
`IEND` must appear end.
APNG must contains one `acTL` and at least one 'fcTL' and `fdAT`.
`fdAT` must appear consecutively.
`fcTL` must appear before `IDAT` or `fdAT`.
*/
if (chunk_num <= 2) return false;
if (chunks->fourcc != YY_FOUR_CC('I', 'H', 'D', 'R')) return false;
if ((chunks + chunk_num - 1)->fourcc != YY_FOUR_CC('I', 'E', 'N', 'D')) return false;
uint32_t prev_fourcc = 0;
uint32_t IHDR_num = 0;
uint32_t IDAT_num = 0;
uint32_t acTL_num = 0;
uint32_t fcTL_num = 0;
uint32_t first_IDAT = 0;
bool first_frame_cover = false;
for (uint32_t i = 0; i < chunk_num; i++) {
yy_png_chunk_info *chunk = chunks + i;
switch (chunk->fourcc) {
case YY_FOUR_CC('I', 'H', 'D', 'R'): { // png header
if (i != 0) return false;
if (IHDR_num > 0) return false;
IHDR_num++;
} break;
case YY_FOUR_CC('I', 'D', 'A', 'T'): { // png data
if (prev_fourcc != YY_FOUR_CC('I', 'D', 'A', 'T')) {
if (IDAT_num == 0)
first_IDAT = i;
else
return false;
}
IDAT_num++;
} break;
case YY_FOUR_CC('a', 'c', 'T', 'L'): { // apng control
if (acTL_num > 0) return false;
acTL_num++;
} break;
case YY_FOUR_CC('f', 'c', 'T', 'L'): { // apng frame control
if (i + 1 == chunk_num) return false;
if ((chunk + 1)->fourcc != YY_FOUR_CC('f', 'd', 'A', 'T') &&
(chunk + 1)->fourcc != YY_FOUR_CC('I', 'D', 'A', 'T')) {
return false;
}
if (fcTL_num == 0) {
if ((chunk + 1)->fourcc == YY_FOUR_CC('I', 'D', 'A', 'T')) {
first_frame_cover = true;
}
}
fcTL_num++;
} break;
case YY_FOUR_CC('f', 'd', 'A', 'T'): { // apng data
if (prev_fourcc != YY_FOUR_CC('f', 'd', 'A', 'T') && prev_fourcc != YY_FOUR_CC('f', 'c', 'T', 'L')) {
return false;
}
} break;
}
prev_fourcc = chunk->fourcc;
}
if (IHDR_num != 1) return false;
if (IDAT_num == 0) return false;
if (acTL_num != 1) return false;
if (fcTL_num < acTL_num) return false;
*first_idat_index = first_IDAT;
*first_frame_is_cover = first_frame_cover;
return true;
}
static void yy_png_info_release(yy_png_info *info) {
if (info) {
if (info->chunks) free(info->chunks);
if (info->apng_frames) free(info->apng_frames);
if (info->apng_shared_chunk_indexs) free(info->apng_shared_chunk_indexs);
free(info);
}
}
/**
Create a png info from a png file. See struct png_info for more information.
@param data png/apng file data.
@param length the data's length in bytes.
@return A png info object, you may call yy_png_info_release() to release it.
Returns NULL if an error occurs.
*/
static yy_png_info *yy_png_info_create(const uint8_t *data, uint32_t length) {
if (length < 32) return NULL;
if (*((uint32_t *)data) != YY_FOUR_CC(0x89, 0x50, 0x4E, 0x47)) return NULL;
if (*((uint32_t *)(data + 4)) != YY_FOUR_CC(0x0D, 0x0A, 0x1A, 0x0A)) return NULL;
uint32_t chunk_realloc_num = 16;
yy_png_chunk_info *chunks = malloc(sizeof(yy_png_chunk_info) * chunk_realloc_num);
if (!chunks) return NULL;
// parse png chunks
uint32_t offset = 8;
uint32_t chunk_num = 0;
uint32_t chunk_capacity = chunk_realloc_num;
uint32_t apng_loop_num = 0;
int32_t apng_sequence_index = -1;
int32_t apng_frame_index = 0;
int32_t apng_frame_number = -1;
bool apng_chunk_error = false;
do {
if (chunk_num >= chunk_capacity) {
yy_png_chunk_info *new_chunks = realloc(chunks, sizeof(yy_png_chunk_info) * (chunk_capacity + chunk_realloc_num));
if (!new_chunks) {
free(chunks);
return NULL;
}
chunks = new_chunks;
chunk_capacity += chunk_realloc_num;
}
yy_png_chunk_info *chunk = chunks + chunk_num;
const uint8_t *chunk_data = data + offset;
chunk->offset = offset;
chunk->length = yy_swap_endian_uint32(*((uint32_t *)chunk_data));
if ((uint64_t)chunk->offset + (uint64_t)chunk->length + 12 > length) {
free(chunks);
return NULL;
}
chunk->fourcc = *((uint32_t *)(chunk_data + 4));
if ((uint64_t)chunk->offset + 4 + chunk->length + 4 > (uint64_t)length) break;
chunk->crc32 = yy_swap_endian_uint32(*((uint32_t *)(chunk_data + 8 + chunk->length)));
chunk_num++;
offset += 12 + chunk->length;
switch (chunk->fourcc) {
case YY_FOUR_CC('a', 'c', 'T', 'L') : {
if (chunk->length == 8) {
apng_frame_number = yy_swap_endian_uint32(*((uint32_t *)(chunk_data + 8)));
apng_loop_num = yy_swap_endian_uint32(*((uint32_t *)(chunk_data + 12)));
} else {
apng_chunk_error = true;
}
} break;
case YY_FOUR_CC('f', 'c', 'T', 'L') :
case YY_FOUR_CC('f', 'd', 'A', 'T') : {
if (chunk->fourcc == YY_FOUR_CC('f', 'c', 'T', 'L')) {
if (chunk->length != 26) {
apng_chunk_error = true;
} else {
apng_frame_index++;
}
}
if (chunk->length > 4) {
uint32_t sequence = yy_swap_endian_uint32(*((uint32_t *)(chunk_data + 8)));
if (apng_sequence_index + 1 == sequence) {
apng_sequence_index++;
} else {
apng_chunk_error = true;
}
} else {
apng_chunk_error = true;
}
} break;
case YY_FOUR_CC('I', 'E', 'N', 'D') : {
offset = length; // end, break do-while loop
} break;
}
} while (offset + 12 <= length);
if (chunk_num < 3 ||
chunks->fourcc != YY_FOUR_CC('I', 'H', 'D', 'R') ||
chunks->length != 13) {
free(chunks);
return NULL;
}
// png info
yy_png_info *info = calloc(1, sizeof(yy_png_info));
if (!info) {
free(chunks);
return NULL;
}
info->chunks = chunks;
info->chunk_num = chunk_num;
yy_png_chunk_IHDR_read(&info->header, data + chunks->offset + 8);
// apng info
if (!apng_chunk_error && apng_frame_number == apng_frame_index && apng_frame_number >= 1) {
bool first_frame_is_cover = false;
uint32_t first_IDAT_index = 0;
if (!yy_png_validate_animation_chunk_order(info->chunks, info->chunk_num, &first_IDAT_index, &first_frame_is_cover)) {
return info; // ignore apng chunk
}
info->apng_loop_num = apng_loop_num;
info->apng_frame_num = apng_frame_number;
info->apng_first_frame_is_cover = first_frame_is_cover;
info->apng_shared_insert_index = first_IDAT_index;
info->apng_frames = calloc(apng_frame_number, sizeof(yy_png_frame_info));
if (!info->apng_frames) {
yy_png_info_release(info);
return NULL;
}
info->apng_shared_chunk_indexs = calloc(info->chunk_num, sizeof(uint32_t));
if (!info->apng_shared_chunk_indexs) {
yy_png_info_release(info);
return NULL;
}
int32_t frame_index = -1;
uint32_t *shared_chunk_index = info->apng_shared_chunk_indexs;
for (int32_t i = 0; i < info->chunk_num; i++) {
yy_png_chunk_info *chunk = info->chunks + i;
switch (chunk->fourcc) {
case YY_FOUR_CC('I', 'D', 'A', 'T'): {
if (info->apng_shared_insert_index == 0) {
info->apng_shared_insert_index = i;
}
if (first_frame_is_cover) {
yy_png_frame_info *frame = info->apng_frames + frame_index;
frame->chunk_num++;
frame->chunk_size += chunk->length + 12;
}
} break;
case YY_FOUR_CC('a', 'c', 'T', 'L'): {
} break;
case YY_FOUR_CC('f', 'c', 'T', 'L'): {
frame_index++;
yy_png_frame_info *frame = info->apng_frames + frame_index;
frame->chunk_index = i + 1;
yy_png_chunk_fcTL_read(&frame->frame_control, data + chunk->offset + 8);
} break;
case YY_FOUR_CC('f', 'd', 'A', 'T'): {
yy_png_frame_info *frame = info->apng_frames + frame_index;
frame->chunk_num++;
frame->chunk_size += chunk->length + 12;
} break;
default: {
*shared_chunk_index = i;
shared_chunk_index++;
info->apng_shared_chunk_size += chunk->length + 12;
info->apng_shared_chunk_num++;
} break;
}
}
}
return info;
}
/**
Copy a png frame data from an apng file.
@param data apng file data
@param info png info
@param index frame index (zero-based)
@param size output, the size of the frame data
@return A frame data (single-frame png file), call free() to release the data.
Returns NULL if an error occurs.
*/
static uint8_t *yy_png_copy_frame_data_at_index(const uint8_t *data,
const yy_png_info *info,
const uint32_t index,
uint32_t *size) {
if (index >= info->apng_frame_num) return NULL;
yy_png_frame_info *frame_info = info->apng_frames + index;
uint32_t frame_remux_size = 8 /* PNG Header */ + info->apng_shared_chunk_size + frame_info->chunk_size;
if (!(info->apng_first_frame_is_cover && index == 0)) {
frame_remux_size -= frame_info->chunk_num * 4; // remove fdAT sequence number
}
uint8_t *frame_data = malloc(frame_remux_size);
if (!frame_data) return NULL;
*size = frame_remux_size;
uint32_t data_offset = 0;
bool inserted = false;
memcpy(frame_data, data, 8); // PNG File Header
data_offset += 8;
for (uint32_t i = 0; i < info->apng_shared_chunk_num; i++) {
uint32_t shared_chunk_index = info->apng_shared_chunk_indexs[i];
yy_png_chunk_info *shared_chunk_info = info->chunks + shared_chunk_index;
if (shared_chunk_index >= info->apng_shared_insert_index && !inserted) { // replace IDAT with fdAT
inserted = true;
for (uint32_t c = 0; c < frame_info->chunk_num; c++) {
yy_png_chunk_info *insert_chunk_info = info->chunks + frame_info->chunk_index + c;
if (insert_chunk_info->fourcc == YY_FOUR_CC('f', 'd', 'A', 'T')) {
*((uint32_t *)(frame_data + data_offset)) = yy_swap_endian_uint32(insert_chunk_info->length - 4);
*((uint32_t *)(frame_data + data_offset + 4)) = YY_FOUR_CC('I', 'D', 'A', 'T');
memcpy(frame_data + data_offset + 8, data + insert_chunk_info->offset + 12, insert_chunk_info->length - 4);
uint32_t crc = (uint32_t)crc32(0, frame_data + data_offset + 4, insert_chunk_info->length);
*((uint32_t *)(frame_data + data_offset + insert_chunk_info->length + 4)) = yy_swap_endian_uint32(crc);
data_offset += insert_chunk_info->length + 8;
} else { // IDAT
memcpy(frame_data + data_offset, data + insert_chunk_info->offset, insert_chunk_info->length + 12);
data_offset += insert_chunk_info->length + 12;
}
}
}
if (shared_chunk_info->fourcc == YY_FOUR_CC('I', 'H', 'D', 'R')) {
uint8_t tmp[25] = {0};
memcpy(tmp, data + shared_chunk_info->offset, 25);
yy_png_chunk_IHDR IHDR = info->header;
IHDR.width = frame_info->frame_control.width;
IHDR.height = frame_info->frame_control.height;
yy_png_chunk_IHDR_write(&IHDR, tmp + 8);
*((uint32_t *)(tmp + 21)) = yy_swap_endian_uint32((uint32_t)crc32(0, tmp + 4, 17));
memcpy(frame_data + data_offset, tmp, 25);
data_offset += 25;
} else {
memcpy(frame_data + data_offset, data + shared_chunk_info->offset, shared_chunk_info->length + 12);
data_offset += shared_chunk_info->length + 12;
}
}
return frame_data;
}
////////////////////////////////////////////////////////////////////////////////
#pragma mark - Helper
/// Returns byte-aligned size.
static inline size_t YYImageByteAlign(size_t size, size_t alignment) {
return ((size + (alignment - 1)) / alignment) * alignment;
}
/// Convert degree to radians
static inline CGFloat YYImageDegreesToRadians(CGFloat degrees) {
return degrees * M_PI / 180;
}
CGColorSpaceRef YYCGColorSpaceGetDeviceRGB() {
static CGColorSpaceRef space;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
space = CGColorSpaceCreateDeviceRGB();
});
return space;
}
CGColorSpaceRef YYCGColorSpaceGetDeviceGray() {
static CGColorSpaceRef space;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
space = CGColorSpaceCreateDeviceGray();
});
return space;
}
BOOL YYCGColorSpaceIsDeviceRGB(CGColorSpaceRef space) {
return space && CFEqual(space, YYCGColorSpaceGetDeviceRGB());
}
BOOL YYCGColorSpaceIsDeviceGray(CGColorSpaceRef space) {
return space && CFEqual(space, YYCGColorSpaceGetDeviceGray());
}
/**
A callback used in CGDataProviderCreateWithData() to release data.
Example:
void *data = malloc(size);
CGDataProviderRef provider = CGDataProviderCreateWithData(data, data, size, YYCGDataProviderReleaseDataCallback);
*/
static void YYCGDataProviderReleaseDataCallback(void *info, const void *data, size_t size) {
if (info) free(info);
}
/**
Decode an image to bitmap buffer with the specified format.
@param srcImage Source image.
@param dest Destination buffer. It should be zero before call this method.
If decode succeed, you should release the dest->data using free().
@param destFormat Destination bitmap format.
@return Whether succeed.
@warning This method support iOS7.0 and later. If call it on iOS6, it just returns NO.
CG_AVAILABLE_STARTING(__MAC_10_9, __IPHONE_7_0)
*/
static BOOL YYCGImageDecodeToBitmapBufferWithAnyFormat(CGImageRef srcImage, vImage_Buffer *dest, vImage_CGImageFormat *destFormat) {
if (!srcImage || (((long)vImageConvert_AnyToAny) + 1 == 1) || !destFormat || !dest) return NO;
size_t width = CGImageGetWidth(srcImage);
size_t height = CGImageGetHeight(srcImage);
if (width == 0 || height == 0) return NO;
dest->data = NULL;
vImage_Error error = kvImageNoError;
CFDataRef srcData = NULL;
vImageConverterRef convertor = NULL;
vImage_CGImageFormat srcFormat = {0};
srcFormat.bitsPerComponent = (uint32_t)CGImageGetBitsPerComponent(srcImage);
srcFormat.bitsPerPixel = (uint32_t)CGImageGetBitsPerPixel(srcImage);
srcFormat.colorSpace = CGImageGetColorSpace(srcImage);
srcFormat.bitmapInfo = CGImageGetBitmapInfo(srcImage) | CGImageGetAlphaInfo(srcImage);
convertor = vImageConverter_CreateWithCGImageFormat(&srcFormat, destFormat, NULL, kvImageNoFlags, NULL);
if (!convertor) goto fail;
CGDataProviderRef srcProvider = CGImageGetDataProvider(srcImage);
srcData = srcProvider ? CGDataProviderCopyData(srcProvider) : NULL; // decode
size_t srcLength = srcData ? CFDataGetLength(srcData) : 0;
const void *srcBytes = srcData ? CFDataGetBytePtr(srcData) : NULL;
if (srcLength == 0 || !srcBytes) goto fail;
vImage_Buffer src = {0};
src.data = (void *)srcBytes;
src.width = width;
src.height = height;
src.rowBytes = CGImageGetBytesPerRow(srcImage);
error = vImageBuffer_Init(dest, height, width, 32, kvImageNoFlags);
if (error != kvImageNoError) goto fail;
error = vImageConvert_AnyToAny(convertor, &src, dest, NULL, kvImageNoFlags); // convert
if (error != kvImageNoError) goto fail;
CFRelease(convertor);
CFRelease(srcData);
return YES;
fail:
if (convertor) CFRelease(convertor);
if (srcData) CFRelease(srcData);
if (dest->data) free(dest->data);
dest->data = NULL;
return NO;
}
/**
Decode an image to bitmap buffer with the 32bit format (such as ARGB8888).
@param srcImage Source image.
@param dest Destination buffer. It should be zero before call this method.
If decode succeed, you should release the dest->data using free().
@param bitmapInfo Destination bitmap format.
@return Whether succeed.
*/
static BOOL YYCGImageDecodeToBitmapBufferWith32BitFormat(CGImageRef srcImage, vImage_Buffer *dest, CGBitmapInfo bitmapInfo) {
if (!srcImage || !dest) return NO;
size_t width = CGImageGetWidth(srcImage);
size_t height = CGImageGetHeight(srcImage);
if (width == 0 || height == 0) return NO;
BOOL hasAlpha = NO;
BOOL alphaFirst = NO;
BOOL alphaPremultiplied = NO;
BOOL byteOrderNormal = NO;
switch (bitmapInfo & kCGBitmapAlphaInfoMask) {
case kCGImageAlphaPremultipliedLast: {
hasAlpha = YES;
alphaPremultiplied = YES;
} break;
case kCGImageAlphaPremultipliedFirst: {
hasAlpha = YES;
alphaPremultiplied = YES;
alphaFirst = YES;
} break;
case kCGImageAlphaLast: {
hasAlpha = YES;
} break;
case kCGImageAlphaFirst: {
hasAlpha = YES;
alphaFirst = YES;
} break;
case kCGImageAlphaNoneSkipLast: {
} break;
case kCGImageAlphaNoneSkipFirst: {
alphaFirst = YES;
} break;
default: {
return NO;
} break;
}
switch (bitmapInfo & kCGBitmapByteOrderMask) {
case kCGBitmapByteOrderDefault: {
byteOrderNormal = YES;
} break;
case kCGBitmapByteOrder32Little: {
} break;
case kCGBitmapByteOrder32Big: {
byteOrderNormal = YES;
} break;
default: {
return NO;
} break;
}
/*
Try convert with vImageConvert_AnyToAny() (avaliable since iOS 7.0).
If fail, try decode with CGContextDrawImage().
CGBitmapContext use a premultiplied alpha format, unpremultiply may lose precision.
*/
vImage_CGImageFormat destFormat = {0};
destFormat.bitsPerComponent = 8;
destFormat.bitsPerPixel = 32;
destFormat.colorSpace = YYCGColorSpaceGetDeviceRGB();
destFormat.bitmapInfo = bitmapInfo;
dest->data = NULL;
if (YYCGImageDecodeToBitmapBufferWithAnyFormat(srcImage, dest, &destFormat)) return YES;
CGBitmapInfo contextBitmapInfo = bitmapInfo & kCGBitmapByteOrderMask;
if (!hasAlpha || alphaPremultiplied) {
contextBitmapInfo |= (bitmapInfo & kCGBitmapAlphaInfoMask);
} else {
contextBitmapInfo |= alphaFirst ? kCGImageAlphaPremultipliedFirst : kCGImageAlphaPremultipliedLast;
}
CGContextRef context = CGBitmapContextCreate(NULL, width, height, 8, 0, YYCGColorSpaceGetDeviceRGB(), contextBitmapInfo);
if (!context) goto fail;
CGContextDrawImage(context, CGRectMake(0, 0, width, height), srcImage); // decode and convert
size_t bytesPerRow = CGBitmapContextGetBytesPerRow(context);
size_t length = height * bytesPerRow;
void *data = CGBitmapContextGetData(context);
if (length == 0 || !data) goto fail;
dest->data = malloc(length);
dest->width = width;
dest->height = height;
dest->rowBytes = bytesPerRow;
if (!dest->data) goto fail;
if (hasAlpha && !alphaPremultiplied) {
vImage_Buffer tmpSrc = {0};
tmpSrc.data = data;
tmpSrc.width = width;
tmpSrc.height = height;
tmpSrc.rowBytes = bytesPerRow;
vImage_Error error;
if (alphaFirst && byteOrderNormal) {
error = vImageUnpremultiplyData_ARGB8888(&tmpSrc, dest, kvImageNoFlags);
} else {
error = vImageUnpremultiplyData_RGBA8888(&tmpSrc, dest, kvImageNoFlags);
}
if (error != kvImageNoError) goto fail;
} else {
memcpy(dest->data, data, length);
}
CFRelease(context);
return YES;
fail:
if (context) CFRelease(context);
if (dest->data) free(dest->data);
dest->data = NULL;
return NO;
return NO;
}
CGImageRef YYCGImageCreateDecodedCopy(CGImageRef imageRef, BOOL decodeForDisplay) {
if (!imageRef) return NULL;
size_t width = CGImageGetWidth(imageRef);
size_t height = CGImageGetHeight(imageRef);
if (width == 0 || height == 0) return NULL;
if (decodeForDisplay) { //decode with redraw (may lose some precision)
CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo(imageRef) & kCGBitmapAlphaInfoMask;
BOOL hasAlpha = NO;
if (alphaInfo == kCGImageAlphaPremultipliedLast ||
alphaInfo == kCGImageAlphaPremultipliedFirst ||
alphaInfo == kCGImageAlphaLast ||
alphaInfo == kCGImageAlphaFirst) {
hasAlpha = YES;
}
// BGRA8888 (premultiplied) or BGRX8888
// same as UIGraphicsBeginImageContext() and -[UIView drawRect:]
CGBitmapInfo bitmapInfo = kCGBitmapByteOrder32Host;
bitmapInfo |= hasAlpha ? kCGImageAlphaPremultipliedFirst : kCGImageAlphaNoneSkipFirst;
CGContextRef context = CGBitmapContextCreate(NULL, width, height, 8, 0, YYCGColorSpaceGetDeviceRGB(), bitmapInfo);
if (!context) return NULL;
CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef); // decode
CGImageRef newImage = CGBitmapContextCreateImage(context);
CFRelease(context);
return newImage;
} else {
CGColorSpaceRef space = CGImageGetColorSpace(imageRef);
size_t bitsPerComponent = CGImageGetBitsPerComponent(imageRef);
size_t bitsPerPixel = CGImageGetBitsPerPixel(imageRef);
size_t bytesPerRow = CGImageGetBytesPerRow(imageRef);
CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef);
if (bytesPerRow == 0 || width == 0 || height == 0) return NULL;
CGDataProviderRef dataProvider = CGImageGetDataProvider(imageRef);
if (!dataProvider) return NULL;
CFDataRef data = CGDataProviderCopyData(dataProvider); // decode
if (!data) return NULL;
CGDataProviderRef newProvider = CGDataProviderCreateWithCFData(data);
CFRelease(data);
if (!newProvider) return NULL;
CGImageRef newImage = CGImageCreate(width, height, bitsPerComponent, bitsPerPixel, bytesPerRow, space, bitmapInfo, newProvider, NULL, false, kCGRenderingIntentDefault);
CFRelease(newProvider);
return newImage;
}
}
CGImageRef YYCGImageCreateAffineTransformCopy(CGImageRef imageRef, CGAffineTransform transform, CGSize destSize, CGBitmapInfo destBitmapInfo) {
if (!imageRef) return NULL;
size_t srcWidth = CGImageGetWidth(imageRef);
size_t srcHeight = CGImageGetHeight(imageRef);
size_t destWidth = round(destSize.width);
size_t destHeight = round(destSize.height);
if (srcWidth == 0 || srcHeight == 0 || destWidth == 0 || destHeight == 0) return NULL;
CGDataProviderRef tmpProvider = NULL, destProvider = NULL;
CGImageRef tmpImage = NULL, destImage = NULL;
vImage_Buffer src = {0}, tmp = {0}, dest = {0};
if(!YYCGImageDecodeToBitmapBufferWith32BitFormat(imageRef, &src, kCGImageAlphaFirst | kCGBitmapByteOrderDefault)) return NULL;
size_t destBytesPerRow = YYImageByteAlign(destWidth * 4, 32);
tmp.data = malloc(destHeight * destBytesPerRow);
if (!tmp.data) goto fail;
tmp.width = destWidth;
tmp.height = destHeight;
tmp.rowBytes = destBytesPerRow;
vImage_CGAffineTransform vTransform = *((vImage_CGAffineTransform *)&transform);
uint8_t backColor[4] = {0};
vImage_Error error = vImageAffineWarpCG_ARGB8888(&src, &tmp, NULL, &vTransform, backColor, kvImageBackgroundColorFill);
if (error != kvImageNoError) goto fail;
free(src.data);
src.data = NULL;
tmpProvider = CGDataProviderCreateWithData(tmp.data, tmp.data, destHeight * destBytesPerRow, YYCGDataProviderReleaseDataCallback);
if (!tmpProvider) goto fail;
tmp.data = NULL; // hold by provider
tmpImage = CGImageCreate(destWidth, destHeight, 8, 32, destBytesPerRow, YYCGColorSpaceGetDeviceRGB(), kCGImageAlphaFirst | kCGBitmapByteOrderDefault, tmpProvider, NULL, false, kCGRenderingIntentDefault);
if (!tmpImage) goto fail;
CFRelease(tmpProvider);
tmpProvider = NULL;
if ((destBitmapInfo & kCGBitmapAlphaInfoMask) == kCGImageAlphaFirst &&
(destBitmapInfo & kCGBitmapByteOrderMask) != kCGBitmapByteOrder32Little) {
return tmpImage;
}
if (!YYCGImageDecodeToBitmapBufferWith32BitFormat(tmpImage, &dest, destBitmapInfo)) goto fail;
CFRelease(tmpImage);
tmpImage = NULL;
destProvider = CGDataProviderCreateWithData(dest.data, dest.data, destHeight * destBytesPerRow, YYCGDataProviderReleaseDataCallback);
if (!destProvider) goto fail;
dest.data = NULL; // hold by provider
destImage = CGImageCreate(destWidth, destHeight, 8, 32, destBytesPerRow, YYCGColorSpaceGetDeviceRGB(), destBitmapInfo, destProvider, NULL, false, kCGRenderingIntentDefault);
if (!destImage) goto fail;
CFRelease(destProvider);
destProvider = NULL;
return destImage;
fail:
if (src.data) free(src.data);
if (tmp.data) free(tmp.data);
if (dest.data) free(dest.data);
if (tmpProvider) CFRelease(tmpProvider);
if (tmpImage) CFRelease(tmpImage);
if (destProvider) CFRelease(destProvider);
return NULL;
}
UIImageOrientation YYUIImageOrientationFromEXIFValue(NSInteger value) {
switch (value) {
case kCGImagePropertyOrientationUp: return UIImageOrientationUp;
case kCGImagePropertyOrientationDown: return UIImageOrientationDown;
case kCGImagePropertyOrientationLeft: return UIImageOrientationLeft;
case kCGImagePropertyOrientationRight: return UIImageOrientationRight;
case kCGImagePropertyOrientationUpMirrored: return UIImageOrientationUpMirrored;
case kCGImagePropertyOrientationDownMirrored: return UIImageOrientationDownMirrored;
case kCGImagePropertyOrientationLeftMirrored: return UIImageOrientationLeftMirrored;
case kCGImagePropertyOrientationRightMirrored: return UIImageOrientationRightMirrored;
default: return UIImageOrientationUp;
}
}
NSInteger YYUIImageOrientationToEXIFValue(UIImageOrientation orientation) {
switch (orientation) {
case UIImageOrientationUp: return kCGImagePropertyOrientationUp;
case UIImageOrientationDown: return kCGImagePropertyOrientationDown;
case UIImageOrientationLeft: return kCGImagePropertyOrientationLeft;
case UIImageOrientationRight: return kCGImagePropertyOrientationRight;