-
Notifications
You must be signed in to change notification settings - Fork 189
/
read.c
2282 lines (1963 loc) · 84.3 KB
/
read.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 2019 Joe Drago. All rights reserved.
// SPDX-License-Identifier: BSD-2-Clause
#include "avif/internal.h"
#include <string.h>
// from the MIAF spec:
// ---
// Section 6.7
// "α is an alpha plane value, scaled into the range of 0 (fully transparent) to 1 (fully opaque), inclusive"
// ---
// Section 7.3.5.2
// "the sample values of the alpha plane divided by the maximum value (e.g. by 255 for 8-bit sample
// values) provides the multiplier to be used to obtain the intensity for the associated master image"
// ---
// The define AVIF_FIX_STUDIO_ALPHA detects when the alpha OBU is incorrectly using studio range
// and corrects it before returning the alpha pixels to the caller.
#define AVIF_FIX_STUDIO_ALPHA
#define AUXTYPE_SIZE 64
#define CONTENTTYPE_SIZE 64
#define MAX_COMPATIBLE_BRANDS 32
// class VisualSampleEntry(codingname) extends SampleEntry(codingname) {
// unsigned int(16) pre_defined = 0;
// const unsigned int(16) reserved = 0;
// unsigned int(32)[3] pre_defined = 0;
// unsigned int(16) width;
// unsigned int(16) height;
// template unsigned int(32) horizresolution = 0x00480000; // 72 dpi
// template unsigned int(32) vertresolution = 0x00480000; // 72 dpi
// const unsigned int(32) reserved = 0;
// template unsigned int(16) frame_count = 1;
// string[32] compressorname;
// template unsigned int(16) depth = 0x0018;
// int(16) pre_defined = -1;
// // other boxes from derived specifications
// CleanApertureBox clap; // optional
// PixelAspectRatioBox pasp; // optional
// }
static const size_t VISUALSAMPLEENTRY_SIZE = 78;
static const char xmpContentType[] = CONTENT_TYPE_XMP;
static const size_t xmpContentTypeSize = sizeof(xmpContentType);
// ---------------------------------------------------------------------------
// Box data structures
// ftyp
typedef struct avifFileType
{
uint8_t majorBrand[4];
uint32_t minorVersion;
uint8_t compatibleBrands[4 * MAX_COMPATIBLE_BRANDS];
int compatibleBrandsCount;
} avifFileType;
// ispe
typedef struct avifImageSpatialExtents
{
uint32_t width;
uint32_t height;
} avifImageSpatialExtents;
// auxC
typedef struct avifAuxiliaryType
{
char auxType[AUXTYPE_SIZE];
} avifAuxiliaryType;
// infe mime content_type
typedef struct avifContentType
{
char contentType[CONTENTTYPE_SIZE];
} avifContentType;
// colr
typedef struct avifColourInformationBox
{
avifProfileFormat format;
const uint8_t * icc;
size_t iccSize;
avifNclxColorProfile nclx;
} avifColourInformationBox;
// ---------------------------------------------------------------------------
// Top-level structures
// one "item" worth (all iref, iloc, iprp, etc refer to one of these)
typedef struct avifItem
{
uint32_t id;
uint8_t type[4];
uint32_t offset;
uint32_t size;
uint32_t idatID; // If non-zero, offset is relative to this idat box (iloc construction_method==1)
avifBool ispePresent;
avifImageSpatialExtents ispe;
avifBool auxCPresent;
avifAuxiliaryType auxC;
avifContentType contentType;
avifBool colrPresent;
avifColourInformationBox colr;
avifBool av1CPresent;
avifCodecConfigurationBox av1C;
uint32_t thumbnailForID; // if non-zero, this item is a thumbnail for Item #{thumbnailForID}
uint32_t auxForID; // if non-zero, this item is an auxC plane for Item #{auxForID}
uint32_t descForID; // if non-zero, this item is a content description for Item #{descForID}
uint32_t dimgForID; // if non-zero, this item is a derived image for Item #{dimgForID}
} avifItem;
AVIF_ARRAY_DECLARE(avifItemArray, avifItem, item);
// Temporary storage for ipco contents until they can be associated and memcpy'd to an avifItem
typedef struct avifProperty
{
uint8_t type[4];
avifImageSpatialExtents ispe;
avifAuxiliaryType auxC;
avifColourInformationBox colr;
avifCodecConfigurationBox av1C;
} avifProperty;
AVIF_ARRAY_DECLARE(avifPropertyArray, avifProperty, prop);
// idat storage
typedef struct avifItemData
{
uint32_t id;
avifROData data;
} avifItemData;
AVIF_ARRAY_DECLARE(avifItemDataArray, avifItemData, idat);
// grid storage
typedef struct avifImageGrid
{
uint8_t rows;
uint8_t columns;
uint32_t outputWidth;
uint32_t outputHeight;
} avifImageGrid;
// ---------------------------------------------------------------------------
// avifTrack
typedef struct avifSampleTableChunk
{
uint64_t offset;
} avifSampleTableChunk;
AVIF_ARRAY_DECLARE(avifSampleTableChunkArray, avifSampleTableChunk, chunk);
typedef struct avifSampleTableSampleToChunk
{
uint32_t firstChunk;
uint32_t samplesPerChunk;
uint32_t sampleDescriptionIndex;
} avifSampleTableSampleToChunk;
AVIF_ARRAY_DECLARE(avifSampleTableSampleToChunkArray, avifSampleTableSampleToChunk, sampleToChunk);
typedef struct avifSampleTableSampleSize
{
uint32_t size;
} avifSampleTableSampleSize;
AVIF_ARRAY_DECLARE(avifSampleTableSampleSizeArray, avifSampleTableSampleSize, sampleSize);
typedef struct avifSampleTableTimeToSample
{
uint32_t sampleCount;
uint32_t sampleDelta;
} avifSampleTableTimeToSample;
AVIF_ARRAY_DECLARE(avifSampleTableTimeToSampleArray, avifSampleTableTimeToSample, timeToSample);
typedef struct avifSyncSample
{
uint32_t sampleNumber;
} avifSyncSample;
AVIF_ARRAY_DECLARE(avifSyncSampleArray, avifSyncSample, syncSample);
typedef struct avifSampleDescription
{
uint8_t format[4];
avifBool av1CPresent;
avifCodecConfigurationBox av1C;
} avifSampleDescription;
AVIF_ARRAY_DECLARE(avifSampleDescriptionArray, avifSampleDescription, description);
typedef struct avifSampleTable
{
avifSampleTableChunkArray chunks;
avifSampleDescriptionArray sampleDescriptions;
avifSampleTableSampleToChunkArray sampleToChunks;
avifSampleTableSampleSizeArray sampleSizes;
avifSampleTableTimeToSampleArray timeToSamples;
avifSyncSampleArray syncSamples;
uint32_t allSamplesSize; // If this is non-zero, sampleSizes will be empty and all samples will be this size
} avifSampleTable;
static avifSampleTable * avifSampleTableCreate()
{
avifSampleTable * sampleTable = (avifSampleTable *)avifAlloc(sizeof(avifSampleTable));
memset(sampleTable, 0, sizeof(avifSampleTable));
avifArrayCreate(&sampleTable->chunks, sizeof(avifSampleTableChunk), 16);
avifArrayCreate(&sampleTable->sampleDescriptions, sizeof(avifSampleDescription), 2);
avifArrayCreate(&sampleTable->sampleToChunks, sizeof(avifSampleTableSampleToChunk), 16);
avifArrayCreate(&sampleTable->sampleSizes, sizeof(avifSampleTableSampleSize), 16);
avifArrayCreate(&sampleTable->timeToSamples, sizeof(avifSampleTableTimeToSample), 16);
avifArrayCreate(&sampleTable->syncSamples, sizeof(avifSyncSample), 16);
return sampleTable;
}
static void avifSampleTableDestroy(avifSampleTable * sampleTable)
{
avifArrayDestroy(&sampleTable->chunks);
avifArrayDestroy(&sampleTable->sampleDescriptions);
avifArrayDestroy(&sampleTable->sampleToChunks);
avifArrayDestroy(&sampleTable->sampleSizes);
avifArrayDestroy(&sampleTable->timeToSamples);
avifArrayDestroy(&sampleTable->syncSamples);
avifFree(sampleTable);
}
static uint32_t avifSampleTableGetImageDelta(avifSampleTable * sampleTable, int imageIndex)
{
int maxSampleIndex = 0;
for (uint32_t i = 0; i < sampleTable->timeToSamples.count; ++i) {
avifSampleTableTimeToSample * timeToSample = &sampleTable->timeToSamples.timeToSample[i];
maxSampleIndex += timeToSample->sampleCount;
if ((imageIndex < maxSampleIndex) || (i == (sampleTable->timeToSamples.count - 1))) {
return timeToSample->sampleDelta;
}
}
// TODO: fail here?
return 1;
}
static avifBool avifSampleTableHasFormat(avifSampleTable * sampleTable, const char * format)
{
for (uint32_t i = 0; i < sampleTable->sampleDescriptions.count; ++i) {
if (!memcmp(sampleTable->sampleDescriptions.description[i].format, format, 4)) {
return AVIF_TRUE;
}
}
return AVIF_FALSE;
}
static uint32_t avifCodecConfigurationBoxGetDepth(avifCodecConfigurationBox * av1C)
{
if (av1C->twelveBit) {
return 12;
} else if (av1C->highBitdepth) {
return 10;
}
return 8;
}
static uint32_t avifSampleTableGetDepth(avifSampleTable * sampleTable)
{
for (uint32_t i = 0; i < sampleTable->sampleDescriptions.count; ++i) {
avifSampleDescription * description = &sampleTable->sampleDescriptions.description[i];
if (!memcmp(description->format, "av01", 4) && description->av1CPresent) {
return avifCodecConfigurationBoxGetDepth(&description->av1C);
}
}
return 0;
}
// one video track ("trak" contents)
typedef struct avifTrack
{
uint32_t id;
uint32_t auxForID; // if non-zero, this item is an auxC plane for Track #{auxForID}
uint32_t mediaTimescale;
uint64_t mediaDuration;
uint32_t width;
uint32_t height;
avifSampleTable * sampleTable;
} avifTrack;
AVIF_ARRAY_DECLARE(avifTrackArray, avifTrack, track);
// ---------------------------------------------------------------------------
// avifCodecDecodeInput
avifCodecDecodeInput * avifCodecDecodeInputCreate(void)
{
avifCodecDecodeInput * decodeInput = (avifCodecDecodeInput *)avifAlloc(sizeof(avifCodecDecodeInput));
memset(decodeInput, 0, sizeof(avifCodecDecodeInput));
avifArrayCreate(&decodeInput->samples, sizeof(avifSample), 1);
return decodeInput;
}
void avifCodecDecodeInputDestroy(avifCodecDecodeInput * decodeInput)
{
avifArrayDestroy(&decodeInput->samples);
avifFree(decodeInput);
}
static avifBool avifCodecDecodeInputGetSamples(avifCodecDecodeInput * decodeInput, avifSampleTable * sampleTable, avifROData * rawInput)
{
uint32_t sampleSizeIndex = 0;
for (uint32_t chunkIndex = 0; chunkIndex < sampleTable->chunks.count; ++chunkIndex) {
avifSampleTableChunk * chunk = &sampleTable->chunks.chunk[chunkIndex];
// First, figure out how many samples are in this chunk
uint32_t sampleCount = 0;
for (int sampleToChunkIndex = sampleTable->sampleToChunks.count - 1; sampleToChunkIndex >= 0; --sampleToChunkIndex) {
avifSampleTableSampleToChunk * sampleToChunk = &sampleTable->sampleToChunks.sampleToChunk[sampleToChunkIndex];
if (sampleToChunk->firstChunk <= (chunkIndex + 1)) {
sampleCount = sampleToChunk->samplesPerChunk;
break;
}
}
if (sampleCount == 0) {
// chunks with 0 samples are invalid
return AVIF_FALSE;
}
uint64_t sampleOffset = chunk->offset;
for (uint32_t sampleIndex = 0; sampleIndex < sampleCount; ++sampleIndex) {
uint32_t sampleSize = sampleTable->allSamplesSize;
if (sampleSize == 0) {
if (sampleSizeIndex >= sampleTable->sampleSizes.count) {
// We've run out of samples to sum
return AVIF_FALSE;
}
avifSampleTableSampleSize * sampleSizePtr = &sampleTable->sampleSizes.sampleSize[sampleSizeIndex];
sampleSize = sampleSizePtr->size;
}
avifSample * sample = (avifSample *)avifArrayPushPtr(&decodeInput->samples);
sample->data.data = rawInput->data + sampleOffset;
sample->data.size = sampleSize;
sample->sync = AVIF_FALSE; // to potentially be set to true following the outer loop
if (sampleOffset > (uint64_t)rawInput->size) {
return AVIF_FALSE;
}
sampleOffset += sampleSize;
++sampleSizeIndex;
}
}
// Mark appropriate samples as sync
for (uint32_t syncSampleIndex = 0; syncSampleIndex < sampleTable->syncSamples.count; ++syncSampleIndex) {
uint32_t frameIndex = sampleTable->syncSamples.syncSample[syncSampleIndex].sampleNumber - 1; // sampleNumber is 1-based
if (frameIndex < decodeInput->samples.count) {
decodeInput->samples.sample[frameIndex].sync = AVIF_TRUE;
}
}
// Assume frame 0 is sync, just in case the stss box is absent in the BMFF. (Unnecessary?)
if (decodeInput->samples.count > 0) {
decodeInput->samples.sample[0].sync = AVIF_TRUE;
}
return AVIF_TRUE;
}
// ---------------------------------------------------------------------------
// avifData
typedef struct avifTile
{
avifCodecDecodeInput * input;
struct avifCodec * codec;
avifImage * image;
} avifTile;
AVIF_ARRAY_DECLARE(avifTileArray, avifTile, tile);
typedef struct avifData
{
avifFileType ftyp;
avifItemArray items;
avifPropertyArray properties;
avifItemDataArray idats;
avifTrackArray tracks;
avifROData rawInput;
avifTileArray tiles;
unsigned int colorTileCount;
unsigned int alphaTileCount;
avifImageGrid colorGrid;
avifImageGrid alphaGrid;
avifDecoderSource source;
avifSampleTable * sourceSampleTable; // NULL unless (source == AVIF_DECODER_SOURCE_TRACKS), owned by an avifTrack
uint32_t primaryItemID;
uint32_t metaBoxID; // Ever-incrementing ID for tracking which 'meta' box contains an idat, and which idat an iloc might refer to
} avifData;
static avifData * avifDataCreate()
{
avifData * data = (avifData *)avifAlloc(sizeof(avifData));
memset(data, 0, sizeof(avifData));
avifArrayCreate(&data->items, sizeof(avifItem), 8);
avifArrayCreate(&data->properties, sizeof(avifProperty), 16);
avifArrayCreate(&data->idats, sizeof(avifItemData), 1);
avifArrayCreate(&data->tracks, sizeof(avifTrack), 2);
avifArrayCreate(&data->tiles, sizeof(avifTile), 8);
return data;
}
static void avifDataResetCodec(avifData * data)
{
for (unsigned int i = 0; i < data->tiles.count; ++i) {
avifTile * tile = &data->tiles.tile[i];
if (tile->codec) {
avifCodecDestroy(tile->codec);
tile->codec = NULL;
}
}
}
static avifTile * avifDataNewTile(avifData * data)
{
avifTile * tile = (avifTile *)avifArrayPushPtr(&data->tiles);
tile->image = avifImageCreateEmpty();
tile->input = avifCodecDecodeInputCreate();
return tile;
}
static void avifDataClearTiles(avifData * data)
{
for (unsigned int i = 0; i < data->tiles.count; ++i) {
avifTile * tile = &data->tiles.tile[i];
if (tile->input) {
avifCodecDecodeInputDestroy(tile->input);
tile->input = NULL;
}
if (tile->codec) {
avifCodecDestroy(tile->codec);
tile->codec = NULL;
}
if (tile->image) {
avifImageDestroy(tile->image);
tile->image = NULL;
}
}
data->tiles.count = 0;
data->colorTileCount = 0;
data->alphaTileCount = 0;
}
static void avifDataDestroy(avifData * data)
{
avifArrayDestroy(&data->items);
avifArrayDestroy(&data->properties);
avifArrayDestroy(&data->idats);
for (uint32_t i = 0; i < data->tracks.count; ++i) {
if (data->tracks.track[i].sampleTable) {
avifSampleTableDestroy(data->tracks.track[i].sampleTable);
}
}
avifArrayDestroy(&data->tracks);
avifDataClearTiles(data);
avifArrayDestroy(&data->tiles);
avifFree(data);
}
static avifItem * avifDataFindItem(avifData * data, uint32_t itemID)
{
if (itemID == 0) {
return NULL;
}
for (uint32_t i = 0; i < data->items.count; ++i) {
if (data->items.item[i].id == itemID) {
return &data->items.item[i];
}
}
avifItem * item = (avifItem *)avifArrayPushPtr(&data->items);
item->id = itemID;
return item;
}
static const uint8_t * avifDataCalcItemPtr(avifData * data, avifItem * item)
{
avifROData * offsetBuffer = NULL;
if (item->idatID == 0) {
// construction_method: file(0)
offsetBuffer = &data->rawInput;
} else {
// construction_method: idat(1)
// Find associated idat block
for (uint32_t i = 0; i < data->idats.count; ++i) {
if (data->idats.idat[i].id == item->idatID) {
offsetBuffer = &data->idats.idat[i].data;
break;
}
}
if (offsetBuffer == NULL) {
// no idat box was found in this meta box, bail out
return NULL;
}
}
if (item->offset > offsetBuffer->size) {
return NULL;
}
uint64_t offsetSize = (uint64_t)item->offset + (uint64_t)item->size;
if (offsetSize > (uint64_t)offsetBuffer->size) {
return NULL;
}
return offsetBuffer->data + item->offset;
}
static avifBool avifDataGenerateImageGridTiles(avifData * data, avifImageGrid * grid, avifItem * gridItem, avifBool alpha)
{
unsigned int tilesRequested = (unsigned int)grid->rows * (unsigned int)grid->columns;
// Count number of dimg for this item, bail out if it doesn't match perfectly
unsigned int tilesAvailable = 0;
for (uint32_t i = 0; i < data->items.count; ++i) {
avifItem * item = &data->items.item[i];
if (item->dimgForID == gridItem->id) {
if (memcmp(item->type, "av01", 4)) {
continue;
}
++tilesAvailable;
}
}
if (tilesRequested != tilesAvailable) {
return AVIF_FALSE;
}
for (uint32_t i = 0; i < data->items.count; ++i) {
avifItem * item = &data->items.item[i];
if (item->dimgForID == gridItem->id) {
if (memcmp(item->type, "av01", 4)) {
continue;
}
avifTile * tile = avifDataNewTile(data);
avifSample * sample = (avifSample *)avifArrayPushPtr(&tile->input->samples);
sample->data.data = avifDataCalcItemPtr(data, item);
sample->data.size = item->size;
sample->sync = AVIF_TRUE;
tile->input->alpha = alpha;
}
}
return AVIF_TRUE;
}
static avifBool avifDataFillImageGrid(avifData * data,
avifImageGrid * grid,
avifImage * dstImage,
unsigned int firstTileIndex,
unsigned int tileCount,
avifBool alpha)
{
if (tileCount == 0) {
return AVIF_FALSE;
}
avifTile * firstTile = &data->tiles.tile[firstTileIndex];
unsigned int tileWidth = firstTile->image->width;
unsigned int tileHeight = firstTile->image->height;
unsigned int tileDepth = firstTile->image->depth;
avifPixelFormat tileFormat = firstTile->image->yuvFormat;
avifRange tileRange = firstTile->image->yuvRange;
avifBool tileUVPresent = (firstTile->image->yuvPlanes[AVIF_CHAN_U] && firstTile->image->yuvPlanes[AVIF_CHAN_V]) ? AVIF_TRUE
: AVIF_FALSE;
for (unsigned int i = 1; i < tileCount; ++i) {
avifTile * tile = &data->tiles.tile[firstTileIndex + i];
avifBool uvPresent = (tile->image->yuvPlanes[AVIF_CHAN_U] && tile->image->yuvPlanes[AVIF_CHAN_V]) ? AVIF_TRUE : AVIF_FALSE;
if ((tile->image->width != tileWidth) || (tile->image->height != tileHeight) || (tile->image->depth != tileDepth) ||
(tile->image->yuvFormat != tileFormat) || (tile->image->yuvRange != tileRange) || (uvPresent != tileUVPresent)) {
return AVIF_FALSE;
}
}
if ((dstImage->width != grid->outputWidth) || (dstImage->height != grid->outputHeight) || (dstImage->depth != tileDepth) ||
(dstImage->yuvFormat != tileFormat)) {
if (alpha) {
// Alpha doesn't match size, just bail out
return AVIF_FALSE;
}
avifImageFreePlanes(dstImage, AVIF_PLANES_ALL);
dstImage->width = grid->outputWidth;
dstImage->height = grid->outputHeight;
dstImage->depth = tileDepth;
dstImage->yuvFormat = tileFormat;
dstImage->yuvRange = tileRange;
}
avifImageAllocatePlanes(dstImage, alpha ? AVIF_PLANES_A : AVIF_PLANES_YUV);
avifPixelFormatInfo formatInfo;
avifGetPixelFormatInfo(tileFormat, &formatInfo);
unsigned int tileIndex = firstTileIndex;
size_t pixelBytes = avifImageUsesU16(dstImage) ? 2 : 1;
for (unsigned int rowIndex = 0; rowIndex < grid->rows; ++rowIndex) {
for (unsigned int colIndex = 0; colIndex < grid->columns; ++colIndex, ++tileIndex) {
avifTile * tile = &data->tiles.tile[tileIndex];
unsigned int widthToCopy = tileWidth;
unsigned int maxX = tileWidth * (colIndex + 1);
if (maxX > grid->outputWidth) {
widthToCopy -= maxX - grid->outputWidth;
}
unsigned int heightToCopy = tileHeight;
unsigned int maxY = tileHeight * (rowIndex + 1);
if (maxY > grid->outputHeight) {
heightToCopy -= maxY - grid->outputHeight;
}
// Y and A channels
size_t yaColOffset = colIndex * tileWidth;
size_t yaRowOffset = rowIndex * tileHeight;
size_t yaRowBytes = widthToCopy * pixelBytes;
if (alpha) {
// A
for (unsigned int j = 0; j < heightToCopy; ++j) {
uint8_t * src = &tile->image->alphaPlane[j * tile->image->alphaRowBytes];
uint8_t * dst = &dstImage->alphaPlane[(yaColOffset * pixelBytes) + ((yaRowOffset + j) * dstImage->alphaRowBytes)];
memcpy(dst, src, yaRowBytes);
}
} else {
// Y
for (unsigned int j = 0; j < heightToCopy; ++j) {
uint8_t * src = &tile->image->yuvPlanes[AVIF_CHAN_Y][j * tile->image->yuvRowBytes[AVIF_CHAN_Y]];
uint8_t * dst =
&dstImage->yuvPlanes[AVIF_CHAN_Y][(yaColOffset * pixelBytes) + ((yaRowOffset + j) * dstImage->yuvRowBytes[AVIF_CHAN_Y])];
memcpy(dst, src, yaRowBytes);
}
if (!tileUVPresent) {
continue;
}
// UV
widthToCopy >>= formatInfo.chromaShiftX;
heightToCopy >>= formatInfo.chromaShiftY;
size_t uvColOffset = yaColOffset >> formatInfo.chromaShiftX;
size_t uvRowOffset = yaRowOffset >> formatInfo.chromaShiftY;
size_t uvRowBytes = yaRowBytes >> formatInfo.chromaShiftX;
for (unsigned int j = 0; j < heightToCopy; ++j) {
uint8_t * srcU = &tile->image->yuvPlanes[AVIF_CHAN_U][j * tile->image->yuvRowBytes[AVIF_CHAN_U]];
uint8_t * dstU =
&dstImage->yuvPlanes[AVIF_CHAN_U][(uvColOffset * pixelBytes) + ((uvRowOffset + j) * dstImage->yuvRowBytes[AVIF_CHAN_U])];
memcpy(dstU, srcU, uvRowBytes);
uint8_t * srcV = &tile->image->yuvPlanes[AVIF_CHAN_V][j * tile->image->yuvRowBytes[AVIF_CHAN_V]];
uint8_t * dstV =
&dstImage->yuvPlanes[AVIF_CHAN_V][(uvColOffset * pixelBytes) + ((uvRowOffset + j) * dstImage->yuvRowBytes[AVIF_CHAN_V])];
memcpy(dstV, srcV, uvRowBytes);
}
}
}
}
return AVIF_TRUE;
}
// ---------------------------------------------------------------------------
// URN
static avifBool isAlphaURN(char * urn)
{
if (!strcmp(urn, URN_ALPHA0))
return AVIF_TRUE;
if (!strcmp(urn, URN_ALPHA1))
return AVIF_TRUE;
return AVIF_FALSE;
}
// ---------------------------------------------------------------------------
// BMFF Parsing
#define BEGIN_STREAM(VARNAME, PTR, SIZE) \
avifROStream VARNAME; \
avifROData VARNAME##_roData; \
VARNAME##_roData.data = PTR; \
VARNAME##_roData.size = SIZE; \
avifROStreamStart(&VARNAME, &VARNAME##_roData)
static avifBool avifParseItemLocationBox(avifData * data, const uint8_t * raw, size_t rawLen)
{
BEGIN_STREAM(s, raw, rawLen);
uint8_t version;
uint8_t flags[3];
CHECK(avifROStreamReadVersionAndFlags(&s, &version, flags));
if (version > 2) {
return AVIF_FALSE;
}
uint8_t offsetSizeAndLengthSize;
CHECK(avifROStreamRead(&s, &offsetSizeAndLengthSize, 1));
uint8_t offsetSize = (offsetSizeAndLengthSize >> 4) & 0xf; // unsigned int(4) offset_size;
uint8_t lengthSize = (offsetSizeAndLengthSize >> 0) & 0xf; // unsigned int(4) length_size;
uint8_t baseOffsetSizeAndIndexSize;
CHECK(avifROStreamRead(&s, &baseOffsetSizeAndIndexSize, 1));
uint8_t baseOffsetSize = (baseOffsetSizeAndIndexSize >> 4) & 0xf; // unsigned int(4) base_offset_size;
uint8_t indexSize = 0;
if ((version == 1) || (version == 2)) {
indexSize = baseOffsetSizeAndIndexSize & 0xf; // unsigned int(4) index_size;
if (indexSize != 0) {
// extent_index unsupported
return AVIF_FALSE;
}
}
uint16_t tmp16;
uint32_t itemCount;
if (version < 2) {
CHECK(avifROStreamReadU16(&s, &tmp16)); // unsigned int(16) item_count;
itemCount = tmp16;
} else {
CHECK(avifROStreamReadU32(&s, &itemCount)); // unsigned int(32) item_count;
}
for (uint32_t i = 0; i < itemCount; ++i) {
uint32_t itemID;
uint32_t idatID = 0;
if (version < 2) {
CHECK(avifROStreamReadU16(&s, &tmp16)); // unsigned int(16) item_ID;
itemID = tmp16;
} else {
CHECK(avifROStreamReadU32(&s, &itemID)); // unsigned int(32) item_ID;
}
if ((version == 1) || (version == 2)) {
uint8_t ignored;
uint8_t constructionMethod;
CHECK(avifROStreamRead(&s, &ignored, 1)); // unsigned int(12) reserved = 0;
CHECK(avifROStreamRead(&s, &constructionMethod, 1)); // unsigned int(4) construction_method;
constructionMethod = constructionMethod & 0xf;
if ((constructionMethod != 0 /* file */) && (constructionMethod != 1 /* idat */)) {
// construction method item(2) unsupported
return AVIF_FALSE;
}
if (constructionMethod == 1) {
idatID = data->metaBoxID;
}
}
uint16_t dataReferenceIndex; // unsigned int(16) data_ref rence_index;
CHECK(avifROStreamReadU16(&s, &dataReferenceIndex)); //
uint64_t baseOffset; // unsigned int(base_offset_size*8) base_offset;
CHECK(avifROStreamReadUX8(&s, &baseOffset, baseOffsetSize)); //
uint16_t extentCount; // unsigned int(16) extent_count;
CHECK(avifROStreamReadU16(&s, &extentCount)); //
if (extentCount == 1) {
// If extent_index is ever supported, this spec must be implemented here:
// :: if (((version == 1) || (version == 2)) && (index_size > 0)) {
// :: unsigned int(index_size*8) extent_index;
// :: }
uint64_t extentOffset; // unsigned int(offset_size*8) extent_offset;
CHECK(avifROStreamReadUX8(&s, &extentOffset, offsetSize));
uint64_t extentLength; // unsigned int(offset_size*8) extent_length;
CHECK(avifROStreamReadUX8(&s, &extentLength, lengthSize));
avifItem * item = avifDataFindItem(data, itemID);
if (!item) {
return AVIF_FALSE;
}
item->id = itemID;
item->offset = (uint32_t)(baseOffset + extentOffset);
item->size = (uint32_t)extentLength;
item->idatID = idatID;
} else {
// TODO: support more than one extent
return AVIF_FALSE;
}
}
return AVIF_TRUE;
}
static avifBool avifParseImageGridBox(avifImageGrid * grid, const uint8_t * raw, size_t rawLen)
{
BEGIN_STREAM(s, raw, rawLen);
uint8_t version, flags;
CHECK(avifROStreamRead(&s, &version, 1)); // unsigned int(8) version = 0;
if (version != 0) {
return AVIF_FALSE;
}
CHECK(avifROStreamRead(&s, &flags, 1)); // unsigned int(8) flags;
CHECK(avifROStreamRead(&s, &grid->rows, 1)); // unsigned int(8) rows_minus_one;
CHECK(avifROStreamRead(&s, &grid->columns, 1)); // unsigned int(8) columns_minus_one;
++grid->rows;
++grid->columns;
uint32_t fieldLength = ((flags & 1) + 1) * 16;
if (fieldLength == 16) {
uint16_t outputWidth16, outputHeight16;
CHECK(avifROStreamReadU16(&s, &outputWidth16)); // unsigned int(FieldLength) output_width;
CHECK(avifROStreamReadU16(&s, &outputHeight16)); // unsigned int(FieldLength) output_height;
grid->outputWidth = outputWidth16;
grid->outputHeight = outputHeight16;
} else {
if (fieldLength != 32) {
// This should be impossible
return AVIF_FALSE;
}
CHECK(avifROStreamReadU32(&s, &grid->outputWidth)); // unsigned int(FieldLength) output_width;
CHECK(avifROStreamReadU32(&s, &grid->outputHeight)); // unsigned int(FieldLength) output_height;
}
return AVIF_TRUE;
}
static avifBool avifParseImageSpatialExtentsProperty(avifData * data, const uint8_t * raw, size_t rawLen, int propertyIndex)
{
BEGIN_STREAM(s, raw, rawLen);
CHECK(avifROStreamReadAndEnforceVersion(&s, 0));
CHECK(avifROStreamReadU32(&s, &data->properties.prop[propertyIndex].ispe.width));
CHECK(avifROStreamReadU32(&s, &data->properties.prop[propertyIndex].ispe.height));
return AVIF_TRUE;
}
static avifBool avifParseAuxiliaryTypeProperty(avifData * data, const uint8_t * raw, size_t rawLen, int propertyIndex)
{
BEGIN_STREAM(s, raw, rawLen);
CHECK(avifROStreamReadAndEnforceVersion(&s, 0));
CHECK(avifROStreamReadString(&s, data->properties.prop[propertyIndex].auxC.auxType, AUXTYPE_SIZE));
return AVIF_TRUE;
}
static avifBool avifParseColourInformationBox(avifData * data, const uint8_t * raw, size_t rawLen, int propertyIndex)
{
BEGIN_STREAM(s, raw, rawLen);
data->properties.prop[propertyIndex].colr.format = AVIF_PROFILE_FORMAT_NONE;
uint8_t colourType[4]; // unsigned int(32) colour_type;
CHECK(avifROStreamRead(&s, colourType, 4));
if (!memcmp(colourType, "rICC", 4) || !memcmp(colourType, "prof", 4)) {
data->properties.prop[propertyIndex].colr.format = AVIF_PROFILE_FORMAT_ICC;
data->properties.prop[propertyIndex].colr.icc = avifROStreamCurrent(&s);
data->properties.prop[propertyIndex].colr.iccSize = avifROStreamRemainingBytes(&s);
} else if (!memcmp(colourType, "nclx", 4)) {
// unsigned int(16) colour_primaries;
CHECK(avifROStreamReadU16(&s, &data->properties.prop[propertyIndex].colr.nclx.colourPrimaries));
// unsigned int(16) transfer_characteristics;
CHECK(avifROStreamReadU16(&s, &data->properties.prop[propertyIndex].colr.nclx.transferCharacteristics));
// unsigned int(16) matrix_coefficients;
CHECK(avifROStreamReadU16(&s, &data->properties.prop[propertyIndex].colr.nclx.matrixCoefficients));
// unsigned int(1) full_range_flag;
// unsigned int(7) reserved = 0;
CHECK(avifROStreamRead(&s, &data->properties.prop[propertyIndex].colr.nclx.fullRangeFlag, 1));
data->properties.prop[propertyIndex].colr.nclx.fullRangeFlag |= 0x80;
data->properties.prop[propertyIndex].colr.format = AVIF_PROFILE_FORMAT_NCLX;
}
return AVIF_TRUE;
}
static avifBool avifParseAV1CodecConfigurationBox(const uint8_t * raw, size_t rawLen, avifCodecConfigurationBox * av1C)
{
BEGIN_STREAM(s, raw, rawLen);
uint8_t markerAndVersion = 0;
CHECK(avifROStreamRead(&s, &markerAndVersion, 1));
uint8_t seqProfileAndIndex = 0;
CHECK(avifROStreamRead(&s, &seqProfileAndIndex, 1));
uint8_t rawFlags = 0;
CHECK(avifROStreamRead(&s, &rawFlags, 1));
if (markerAndVersion != 0x81) {
// Marker and version must both == 1
return AVIF_FALSE;
}
av1C->seqProfile = (seqProfileAndIndex >> 5) & 0x7; // unsigned int (3) seq_profile;
av1C->seqLevelIdx0 = (seqProfileAndIndex >> 0) & 0x1f; // unsigned int (5) seq_level_idx_0;
av1C->seqTier0 = (rawFlags >> 7) & 0x1; // unsigned int (1) seq_tier_0;
av1C->highBitdepth = (rawFlags >> 6) & 0x1; // unsigned int (1) high_bitdepth;
av1C->twelveBit = (rawFlags >> 5) & 0x1; // unsigned int (1) twelve_bit;
av1C->monochrome = (rawFlags >> 4) & 0x1; // unsigned int (1) monochrome;
av1C->chromaSubsamplingX = (rawFlags >> 3) & 0x1; // unsigned int (1) chroma_subsampling_x;
av1C->chromaSubsamplingY = (rawFlags >> 2) & 0x1; // unsigned int (1) chroma_subsampling_y;
av1C->chromaSamplePosition = (rawFlags >> 0) & 0x3; // unsigned int (2) chroma_sample_position;
return AVIF_TRUE;
}
static avifBool avifParseAV1CodecConfigurationBoxProperty(avifData * data, const uint8_t * raw, size_t rawLen, int propertyIndex)
{
return avifParseAV1CodecConfigurationBox(raw, rawLen, &data->properties.prop[propertyIndex].av1C);
}
static avifBool avifParseItemPropertyContainerBox(avifData * data, const uint8_t * raw, size_t rawLen)
{
BEGIN_STREAM(s, raw, rawLen);
while (avifROStreamHasBytesLeft(&s, 1)) {
avifBoxHeader header;
CHECK(avifROStreamReadBoxHeader(&s, &header));
int propertyIndex = avifArrayPushIndex(&data->properties);
memcpy(data->properties.prop[propertyIndex].type, header.type, 4);
if (!memcmp(header.type, "ispe", 4)) {
CHECK(avifParseImageSpatialExtentsProperty(data, avifROStreamCurrent(&s), header.size, propertyIndex));
}
if (!memcmp(header.type, "auxC", 4)) {
CHECK(avifParseAuxiliaryTypeProperty(data, avifROStreamCurrent(&s), header.size, propertyIndex));
}
if (!memcmp(header.type, "colr", 4)) {
CHECK(avifParseColourInformationBox(data, avifROStreamCurrent(&s), header.size, propertyIndex));
}
if (!memcmp(header.type, "av1C", 4)) {
CHECK(avifParseAV1CodecConfigurationBoxProperty(data, avifROStreamCurrent(&s), header.size, propertyIndex));
}
CHECK(avifROStreamSkip(&s, header.size));
}
return AVIF_TRUE;
}
static avifBool avifParseItemPropertyAssociation(avifData * data, const uint8_t * raw, size_t rawLen)
{
BEGIN_STREAM(s, raw, rawLen);
uint8_t version;
uint8_t flags[3];
CHECK(avifROStreamReadVersionAndFlags(&s, &version, flags));
avifBool propertyIndexIsU16 = (flags[2] & 0x1) ? AVIF_TRUE : AVIF_FALSE; // is flags[2] correct?
uint32_t entryCount;
CHECK(avifROStreamReadU32(&s, &entryCount));
for (uint32_t entryIndex = 0; entryIndex < entryCount; ++entryIndex) {
unsigned int itemID;
if (version < 1) {
uint16_t tmp;
CHECK(avifROStreamReadU16(&s, &tmp));
itemID = tmp;
} else {
CHECK(avifROStreamReadU32(&s, &itemID));
}
uint8_t associationCount;
CHECK(avifROStreamRead(&s, &associationCount, 1));
for (uint8_t associationIndex = 0; associationIndex < associationCount; ++associationIndex) {
// avifBool essential = AVIF_FALSE; // currently unused
uint16_t propertyIndex = 0;
if (propertyIndexIsU16) {
CHECK(avifROStreamReadU16(&s, &propertyIndex));
// essential = (propertyIndex & 0x8000) ? AVIF_TRUE : AVIF_FALSE;
propertyIndex &= 0x7fff;
} else {
uint8_t tmp;
CHECK(avifROStreamRead(&s, &tmp, 1));
// essential = (tmp & 0x80) ? AVIF_TRUE : AVIF_FALSE;
propertyIndex = tmp & 0x7f;
}
if (propertyIndex == 0) {
// Not associated with any item
continue;
}
--propertyIndex; // 1-indexed
if (propertyIndex >= data->properties.count) {
return AVIF_FALSE;
}
avifItem * item = avifDataFindItem(data, itemID);
if (!item) {
return AVIF_FALSE;
}
// Associate property with item
avifProperty * prop = &data->properties.prop[propertyIndex];
if (!memcmp(prop->type, "ispe", 4)) {
item->ispePresent = AVIF_TRUE;
memcpy(&item->ispe, &prop->ispe, sizeof(avifImageSpatialExtents));
} else if (!memcmp(prop->type, "auxC", 4)) {
item->auxCPresent = AVIF_TRUE;
memcpy(&item->auxC, &prop->auxC, sizeof(avifAuxiliaryType));
} else if (!memcmp(prop->type, "colr", 4)) {
item->colrPresent = AVIF_TRUE;
memcpy(&item->colr, &prop->colr, sizeof(avifColourInformationBox));
} else if (!memcmp(prop->type, "av1C", 4)) {
item->av1CPresent = AVIF_TRUE;
memcpy(&item->av1C, &prop->av1C, sizeof(avifCodecConfigurationBox));
}
}
}
return AVIF_TRUE;
}
static avifBool avifParsePrimaryItemBox(avifData * data, const uint8_t * raw, size_t rawLen)
{
if (data->primaryItemID > 0) {
// Illegal to have multiple pitm boxes, bail out
return AVIF_FALSE;
}
BEGIN_STREAM(s, raw, rawLen);