forked from AOMediaCodec/libavif
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathwrite.c
3850 lines (3442 loc) · 202 KB
/
write.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 <assert.h>
#include <stdint.h>
#include <string.h>
#include <time.h>
// Section 8.11.14.2 of ISO/IEC 14496-12 (ItemPropertyAssociationBox 'ipma' syntax):
// if (flags & 1)
// unsigned int(15) property_index;
// else
// unsigned int(7) property_index;
//
// libavif writes 'ipma' with flags set to 0.
#define MAX_PROPERTY_INDEX ((1 << 7) - 1)
// The indices of the properties associated with an item.
typedef struct avifItemPropertyAssociation
{
uint8_t property_index; // 1-indexed
avifBool essential;
} avifItemPropertyAssociation;
AVIF_ARRAY_DECLARE(avifItemPropertyAssociationArray, avifItemPropertyAssociation, association);
// Used to store offsets in meta boxes which need to point at mdat offsets that
// aren't known yet. When an item's mdat payload is written, all registered fixups
// will have this now-known offset "fixed up".
typedef struct avifOffsetFixup
{
size_t offset;
} avifOffsetFixup;
AVIF_ARRAY_DECLARE(avifOffsetFixupArray, avifOffsetFixup, fixup);
static const char alphaURN[] = AVIF_URN_ALPHA0;
static const size_t alphaURNSize = sizeof(alphaURN);
static const char xmpContentType[] = AVIF_CONTENT_TYPE_XMP;
static const size_t xmpContentTypeSize = sizeof(xmpContentType);
static avifResult writeCodecConfig(avifRWStream * s, const avifCodecConfigurationBox * cfg);
static avifResult writeConfigBox(avifRWStream * s, const avifCodecConfigurationBox * cfg, const char * configPropName);
// ---------------------------------------------------------------------------
// avifSetTileConfiguration
static int floorLog2(uint32_t n)
{
assert(n > 0);
int count = 0;
while (n != 0) {
++count;
n >>= 1;
}
return count - 1;
}
// Splits tilesLog2 into *tileDim1Log2 and *tileDim2Log2, considering the ratio of dim1 to dim2.
//
// Precondition:
// dim1 >= dim2
// Postcondition:
// tilesLog2 == *tileDim1Log2 + *tileDim2Log2
// *tileDim1Log2 >= *tileDim2Log2
static void splitTilesLog2(uint32_t dim1, uint32_t dim2, int tilesLog2, int * tileDim1Log2, int * tileDim2Log2)
{
assert(dim1 >= dim2);
uint32_t ratio = dim1 / dim2;
int diffLog2 = floorLog2(ratio);
int subtract = tilesLog2 - diffLog2;
if (subtract < 0) {
subtract = 0;
}
*tileDim2Log2 = subtract / 2;
*tileDim1Log2 = tilesLog2 - *tileDim2Log2;
assert(*tileDim1Log2 >= *tileDim2Log2);
}
// Set the tile configuration: the number of tiles and the tile size.
//
// Tiles improve encoding and decoding speeds when multiple threads are available. However, for
// image coding, the total tile boundary length affects the compression efficiency because intra
// prediction can't go across tile boundaries. So the more tiles there are in an image, the worse
// the compression ratio is. For a given number of tiles, making the tile size close to a square
// tends to reduce the total tile boundary length inside the image. Use more tiles along the longer
// dimension of the image to make the tile size closer to a square.
void avifSetTileConfiguration(int threads, uint32_t width, uint32_t height, int * tileRowsLog2, int * tileColsLog2)
{
*tileRowsLog2 = 0;
*tileColsLog2 = 0;
if (threads > 1) {
// Avoid small tiles because they are particularly bad for image coding.
//
// Use no more tiles than the number of threads. Aim for one tile per thread. Using more
// than one thread inside one tile could be less efficient. Using more tiles than the
// number of threads would result in a compression penalty without much benefit.
const uint32_t kMinTileArea = 512 * 512;
const uint32_t kMaxTiles = 32;
uint32_t imageArea = width * height;
uint32_t tiles = (imageArea + kMinTileArea - 1) / kMinTileArea;
if (tiles > kMaxTiles) {
tiles = kMaxTiles;
}
if (tiles > (uint32_t)threads) {
tiles = threads;
}
int tilesLog2 = floorLog2(tiles);
// If the image's width is greater than the height, use more tile columns than tile rows.
if (width >= height) {
splitTilesLog2(width, height, tilesLog2, tileColsLog2, tileRowsLog2);
} else {
splitTilesLog2(height, width, tilesLog2, tileRowsLog2, tileColsLog2);
}
}
}
// ---------------------------------------------------------------------------
// avifCodecEncodeOutput
avifCodecEncodeOutput * avifCodecEncodeOutputCreate(void)
{
avifCodecEncodeOutput * encodeOutput = (avifCodecEncodeOutput *)avifAlloc(sizeof(avifCodecEncodeOutput));
if (encodeOutput == NULL) {
return NULL;
}
memset(encodeOutput, 0, sizeof(avifCodecEncodeOutput));
if (!avifArrayCreate(&encodeOutput->samples, sizeof(avifEncodeSample), 1)) {
avifCodecEncodeOutputDestroy(encodeOutput);
return NULL;
}
return encodeOutput;
}
avifResult avifCodecEncodeOutputAddSample(avifCodecEncodeOutput * encodeOutput, const uint8_t * data, size_t len, avifBool sync)
{
avifEncodeSample * sample = (avifEncodeSample *)avifArrayPush(&encodeOutput->samples);
AVIF_CHECKERR(sample, AVIF_RESULT_OUT_OF_MEMORY);
const avifResult result = avifRWDataSet(&sample->data, data, len);
if (result != AVIF_RESULT_OK) {
avifArrayPop(&encodeOutput->samples);
return result;
}
sample->sync = sync;
return AVIF_RESULT_OK;
}
void avifCodecEncodeOutputDestroy(avifCodecEncodeOutput * encodeOutput)
{
for (uint32_t sampleIndex = 0; sampleIndex < encodeOutput->samples.count; ++sampleIndex) {
avifRWDataFree(&encodeOutput->samples.sample[sampleIndex].data);
}
avifArrayDestroy(&encodeOutput->samples);
avifFree(encodeOutput);
}
// ---------------------------------------------------------------------------
// avifEncoderItem
// one "item" worth for encoder
typedef struct avifEncoderItem
{
uint16_t id;
uint8_t type[4]; // 4-character 'item_type' field in the 'infe' (item info entry) box
avifCodec * codec; // only present on image items
avifCodecEncodeOutput * encodeOutput; // AV1 sample data
avifRWData metadataPayload; // Exif/XMP data
avifCodecConfigurationBox av1C; // Harvested in avifEncoderFinish(), if encodeOutput has samples
// TODO(yguyon): Rename or add av2C
uint32_t cellIndex; // Which row-major cell index corresponds to this item. only present on image items
avifItemCategory itemCategory; // Category of item being encoded
avifBool hiddenImage; // A hidden image item has (flags & 1) equal to 1 in its ItemInfoEntry.
const char * infeName;
size_t infeNameSize;
const char * infeContentType;
size_t infeContentTypeSize;
avifOffsetFixupArray mdatFixups;
uint16_t irefToID; // if non-zero, make an iref from this id -> irefToID
const char * irefType;
uint32_t gridCols; // if non-zero (legal range [1-256]), this is a grid item
uint32_t gridRows; // if non-zero (legal range [1-256]), this is a grid item
// the reconstructed image of a grid item will be trimmed to these dimensions (only present on grid items)
uint32_t gridWidth;
uint32_t gridHeight;
uint32_t extraLayerCount; // if non-zero (legal range [1-(AVIF_MAX_AV1_LAYER_COUNT-1)]), this is a layered AV1 image
uint16_t dimgFromID; // if non-zero, make an iref from dimgFromID -> this id
avifItemPropertyAssociationArray associations; // 'ipma'
} avifEncoderItem;
AVIF_ARRAY_DECLARE(avifEncoderItemArray, avifEncoderItem, item);
// ---------------------------------------------------------------------------
// avifEncoderItemReference
// pointer to one "item" interested in
typedef avifEncoderItem * avifEncoderItemReference;
AVIF_ARRAY_DECLARE(avifEncoderItemReferenceArray, avifEncoderItemReference, ref);
// ---------------------------------------------------------------------------
// avifEncoderFrame
typedef struct avifEncoderFrame
{
uint64_t durationInTimescales;
} avifEncoderFrame;
AVIF_ARRAY_DECLARE(avifEncoderFrameArray, avifEncoderFrame, frame);
// ---------------------------------------------------------------------------
// avifEncoderData
AVIF_ARRAY_DECLARE(avifEncoderItemIdArray, uint16_t, itemID);
typedef struct avifEncoderData
{
avifEncoderItemArray items;
avifEncoderFrameArray frames;
// Map the encoder settings quality and qualityAlpha to quantizer and quantizerAlpha
int quantizer;
int quantizerAlpha;
int quantizerGainMap;
// tileRowsLog2 and tileColsLog2 are the actual tiling values after automatic tiling is handled
int tileRowsLog2;
int tileColsLog2;
avifEncoder lastEncoder;
// lastQuantizer and lastQuantizerAlpha are the quantizer and quantizerAlpha values used last
// time
int lastQuantizer;
int lastQuantizerAlpha;
// lastTileRowsLog2 and lastTileColsLog2 are the actual tiling values used last time
int lastTileRowsLog2;
int lastTileColsLog2;
avifImage * imageMetadata;
// For convenience, holds metadata derived from the avifGainMap struct (when present) about the
// altenate image
avifImage * altImageMetadata;
uint16_t lastItemID;
uint16_t primaryItemID;
avifEncoderItemIdArray alternativeItemIDs; // list of item ids for an 'altr' box (group of alternatives to each other)
avifBool singleImage; // if true, the AVIF_ADD_IMAGE_FLAG_SINGLE flag was set on the first call to avifEncoderAddImage()
avifBool alphaPresent;
size_t gainMapSizeBytes;
// Fields specific to AV1/AV2
const char * imageItemType; // "av01" for AV1 ("av02" for AV2 if AVIF_CODEC_AVM)
const char * configPropName; // "av1C" for AV1 ("av2C" for AV2 if AVIF_CODEC_AVM)
} avifEncoderData;
static void avifEncoderDataDestroy(avifEncoderData * data);
// Returns NULL if a memory allocation failed.
static avifEncoderData * avifEncoderDataCreate(void)
{
avifEncoderData * data = (avifEncoderData *)avifAlloc(sizeof(avifEncoderData));
if (!data) {
return NULL;
}
memset(data, 0, sizeof(avifEncoderData));
data->imageMetadata = avifImageCreateEmpty();
if (!data->imageMetadata) {
goto error;
}
data->altImageMetadata = avifImageCreateEmpty();
if (!data->altImageMetadata) {
goto error;
}
if (!avifArrayCreate(&data->items, sizeof(avifEncoderItem), 8)) {
goto error;
}
if (!avifArrayCreate(&data->frames, sizeof(avifEncoderFrame), 1)) {
goto error;
}
if (!avifArrayCreate(&data->alternativeItemIDs, sizeof(uint16_t), 1)) {
goto error;
}
return data;
error:
avifEncoderDataDestroy(data);
return NULL;
}
static avifEncoderItem * avifEncoderDataCreateItem(avifEncoderData * data, const char * type, const char * infeName, size_t infeNameSize, uint32_t cellIndex)
{
avifEncoderItem * item = (avifEncoderItem *)avifArrayPush(&data->items);
if (item == NULL) {
return NULL;
}
++data->lastItemID;
item->id = data->lastItemID;
memcpy(item->type, type, sizeof(item->type));
item->infeName = infeName;
item->infeNameSize = infeNameSize;
item->encodeOutput = avifCodecEncodeOutputCreate();
if (item->encodeOutput == NULL) {
goto error;
}
item->cellIndex = cellIndex;
if (!avifArrayCreate(&item->mdatFixups, sizeof(avifOffsetFixup), 4)) {
goto error;
}
if (!avifArrayCreate(&item->associations, sizeof(avifItemPropertyAssociation), 4)) {
goto error;
}
return item;
error:
if (item->encodeOutput != NULL) {
avifCodecEncodeOutputDestroy(item->encodeOutput);
}
avifArrayDestroy(&item->mdatFixups);
--data->lastItemID;
avifArrayPop(&data->items);
return NULL;
}
static avifEncoderItem * avifEncoderDataFindItemByID(avifEncoderData * data, uint16_t id)
{
for (uint32_t itemIndex = 0; itemIndex < data->items.count; ++itemIndex) {
avifEncoderItem * item = &data->items.item[itemIndex];
if (item->id == id) {
return item;
}
}
return NULL;
}
static void avifEncoderDataDestroy(avifEncoderData * data)
{
for (uint32_t i = 0; i < data->items.count; ++i) {
avifEncoderItem * item = &data->items.item[i];
if (item->codec) {
avifCodecDestroy(item->codec);
}
avifCodecEncodeOutputDestroy(item->encodeOutput);
avifRWDataFree(&item->metadataPayload);
avifArrayDestroy(&item->mdatFixups);
avifArrayDestroy(&item->associations);
}
if (data->imageMetadata) {
avifImageDestroy(data->imageMetadata);
}
if (data->altImageMetadata) {
avifImageDestroy(data->altImageMetadata);
}
avifArrayDestroy(&data->items);
avifArrayDestroy(&data->frames);
avifArrayDestroy(&data->alternativeItemIDs);
avifFree(data);
}
static avifResult avifEncoderItemAddMdatFixup(avifEncoderItem * item, const avifRWStream * s)
{
avifOffsetFixup * fixup = (avifOffsetFixup *)avifArrayPush(&item->mdatFixups);
AVIF_CHECKERR(fixup != NULL, AVIF_RESULT_OUT_OF_MEMORY);
fixup->offset = avifRWStreamOffset(s);
return AVIF_RESULT_OK;
}
// ---------------------------------------------------------------------------
// avifItemPropertyDedup - Provides ipco deduplication
typedef struct avifItemProperty
{
uint8_t index;
size_t offset;
size_t size;
} avifItemProperty;
AVIF_ARRAY_DECLARE(avifItemPropertyArray, avifItemProperty, property);
typedef struct avifItemPropertyDedup
{
avifItemPropertyArray properties;
avifRWStream s; // Temporary stream for each new property, checked against already-written boxes for deduplications
avifRWData buffer; // Temporary storage for 's'
uint8_t nextIndex; // 1-indexed, incremented every time another unique property is finished
} avifItemPropertyDedup;
static avifItemPropertyDedup * avifItemPropertyDedupCreate(void)
{
avifItemPropertyDedup * dedup = (avifItemPropertyDedup *)avifAlloc(sizeof(avifItemPropertyDedup));
if (dedup == NULL) {
return NULL;
}
memset(dedup, 0, sizeof(avifItemPropertyDedup));
if (!avifArrayCreate(&dedup->properties, sizeof(avifItemProperty), 8)) {
avifFree(dedup);
return NULL;
}
if (avifRWDataRealloc(&dedup->buffer, 2048) != AVIF_RESULT_OK) {
avifArrayDestroy(&dedup->properties);
avifFree(dedup);
return NULL;
}
return dedup;
}
static void avifItemPropertyDedupDestroy(avifItemPropertyDedup * dedup)
{
avifArrayDestroy(&dedup->properties);
avifRWDataFree(&dedup->buffer);
avifFree(dedup);
}
// Resets the dedup's temporary write stream in preparation for a single item property's worth of writing
static void avifItemPropertyDedupStart(avifItemPropertyDedup * dedup)
{
avifRWStreamStart(&dedup->s, &dedup->buffer);
}
// This compares the newly written item property (in the dedup's temporary storage buffer) to
// already-written properties (whose offsets/sizes in outputStream are recorded in the dedup). If a
// match is found, the previous property's index is used. If this new property is unique, it is
// assigned the next available property index, written to the output stream, and its offset/size in
// the output stream is recorded in the dedup for future comparisons.
//
// On success, this function adds to the given ipma box a property association linking the reused
// or newly created property with the item.
static avifResult avifItemPropertyDedupFinish(avifItemPropertyDedup * dedup,
avifRWStream * outputStream,
avifItemPropertyAssociationArray * associations,
avifBool essential)
{
uint8_t propertyIndex = 0;
const size_t newPropertySize = avifRWStreamOffset(&dedup->s);
for (size_t i = 0; i < dedup->properties.count; ++i) {
avifItemProperty * property = &dedup->properties.property[i];
if ((property->size == newPropertySize) &&
!memcmp(&outputStream->raw->data[property->offset], dedup->buffer.data, newPropertySize)) {
// We've already written this exact property, reuse it
propertyIndex = property->index;
AVIF_ASSERT_OR_RETURN(propertyIndex != 0);
break;
}
}
if (propertyIndex == 0) {
// Write a new property, and remember its location in the output stream for future deduplication
avifItemProperty * property = (avifItemProperty *)avifArrayPush(&dedup->properties);
AVIF_CHECKERR(property != NULL, AVIF_RESULT_OUT_OF_MEMORY);
AVIF_CHECKERR(dedup->nextIndex < MAX_PROPERTY_INDEX, AVIF_RESULT_INVALID_ARGUMENT);
property->index = ++dedup->nextIndex; // preincrement so the first new index is 1 (as ipma is 1-indexed)
property->size = newPropertySize;
property->offset = avifRWStreamOffset(outputStream);
AVIF_CHECKRES(avifRWStreamWrite(outputStream, dedup->buffer.data, newPropertySize));
propertyIndex = property->index;
}
avifItemPropertyAssociation * association = (avifItemPropertyAssociation *)avifArrayPush(associations);
AVIF_CHECKERR(association != NULL, AVIF_RESULT_OUT_OF_MEMORY);
association->property_index = propertyIndex;
association->essential = essential;
return AVIF_RESULT_OK;
}
// ---------------------------------------------------------------------------
static const avifScalingMode noScaling = { { 1, 1 }, { 1, 1 } };
avifEncoder * avifEncoderCreate(void)
{
avifEncoder * encoder = (avifEncoder *)avifAlloc(sizeof(avifEncoder));
if (!encoder) {
return NULL;
}
memset(encoder, 0, sizeof(avifEncoder));
encoder->codecChoice = AVIF_CODEC_CHOICE_AUTO;
encoder->maxThreads = 1;
encoder->speed = AVIF_SPEED_DEFAULT;
encoder->keyframeInterval = 0;
encoder->timescale = 1;
encoder->repetitionCount = AVIF_REPETITION_COUNT_INFINITE;
encoder->quality = AVIF_QUALITY_DEFAULT;
encoder->qualityAlpha = AVIF_QUALITY_DEFAULT;
encoder->qualityGainMap = AVIF_QUALITY_DEFAULT;
encoder->minQuantizer = AVIF_QUANTIZER_BEST_QUALITY;
encoder->maxQuantizer = AVIF_QUANTIZER_WORST_QUALITY;
encoder->minQuantizerAlpha = AVIF_QUANTIZER_BEST_QUALITY;
encoder->maxQuantizerAlpha = AVIF_QUANTIZER_WORST_QUALITY;
encoder->tileRowsLog2 = 0;
encoder->tileColsLog2 = 0;
encoder->autoTiling = AVIF_FALSE;
encoder->scalingMode = noScaling;
encoder->data = avifEncoderDataCreate();
encoder->csOptions = avifCodecSpecificOptionsCreate();
if (!encoder->data || !encoder->csOptions) {
avifEncoderDestroy(encoder);
return NULL;
}
encoder->headerFormat = AVIF_HEADER_FULL;
#if defined(AVIF_ENABLE_EXPERIMENTAL_SAMPLE_TRANSFORM)
encoder->sampleTransformRecipe = AVIF_SAMPLE_TRANSFORM_NONE;
#endif
return encoder;
}
void avifEncoderDestroy(avifEncoder * encoder)
{
if (encoder->csOptions) {
avifCodecSpecificOptionsDestroy(encoder->csOptions);
}
if (encoder->data) {
avifEncoderDataDestroy(encoder->data);
}
avifFree(encoder);
}
avifResult avifEncoderSetCodecSpecificOption(avifEncoder * encoder, const char * key, const char * value)
{
return avifCodecSpecificOptionsSet(encoder->csOptions, key, value);
}
static void avifEncoderBackupSettings(avifEncoder * encoder)
{
avifEncoder * lastEncoder = &encoder->data->lastEncoder;
// lastEncoder->data is only used to mark that lastEncoder is initialized. lastEncoder->data
// must not be dereferenced.
lastEncoder->data = encoder->data;
lastEncoder->codecChoice = encoder->codecChoice;
lastEncoder->maxThreads = encoder->maxThreads;
lastEncoder->speed = encoder->speed;
lastEncoder->keyframeInterval = encoder->keyframeInterval;
lastEncoder->timescale = encoder->timescale;
lastEncoder->repetitionCount = encoder->repetitionCount;
lastEncoder->extraLayerCount = encoder->extraLayerCount;
lastEncoder->minQuantizer = encoder->minQuantizer;
lastEncoder->maxQuantizer = encoder->maxQuantizer;
lastEncoder->minQuantizerAlpha = encoder->minQuantizerAlpha;
lastEncoder->maxQuantizerAlpha = encoder->maxQuantizerAlpha;
encoder->data->lastQuantizer = encoder->data->quantizer;
encoder->data->lastQuantizerAlpha = encoder->data->quantizerAlpha;
encoder->data->lastTileRowsLog2 = encoder->data->tileRowsLog2;
encoder->data->lastTileColsLog2 = encoder->data->tileColsLog2;
lastEncoder->scalingMode = encoder->scalingMode;
#if defined(AVIF_ENABLE_EXPERIMENTAL_SAMPLE_TRANSFORM)
lastEncoder->sampleTransformRecipe = encoder->sampleTransformRecipe;
#endif
}
// This function detects changes made on avifEncoder. It returns true on success (i.e., if every
// change is valid), or false on failure (i.e., if any setting that can't change was changed). It
// reports a bitwise-OR of detected changes in encoderChanges.
static avifBool avifEncoderDetectChanges(const avifEncoder * encoder, avifEncoderChanges * encoderChanges)
{
const avifEncoder * lastEncoder = &encoder->data->lastEncoder;
*encoderChanges = 0;
if (!lastEncoder->data) {
// lastEncoder is not initialized.
return AVIF_TRUE;
}
if ((lastEncoder->codecChoice != encoder->codecChoice) || (lastEncoder->maxThreads != encoder->maxThreads) ||
(lastEncoder->speed != encoder->speed) || (lastEncoder->keyframeInterval != encoder->keyframeInterval) ||
(lastEncoder->timescale != encoder->timescale) || (lastEncoder->repetitionCount != encoder->repetitionCount) ||
(lastEncoder->extraLayerCount != encoder->extraLayerCount)) {
return AVIF_FALSE;
}
if (encoder->data->lastQuantizer != encoder->data->quantizer) {
*encoderChanges |= AVIF_ENCODER_CHANGE_QUANTIZER;
}
if (encoder->data->lastQuantizerAlpha != encoder->data->quantizerAlpha) {
*encoderChanges |= AVIF_ENCODER_CHANGE_QUANTIZER_ALPHA;
}
if (lastEncoder->minQuantizer != encoder->minQuantizer) {
*encoderChanges |= AVIF_ENCODER_CHANGE_MIN_QUANTIZER;
}
if (lastEncoder->maxQuantizer != encoder->maxQuantizer) {
*encoderChanges |= AVIF_ENCODER_CHANGE_MAX_QUANTIZER;
}
if (lastEncoder->minQuantizerAlpha != encoder->minQuantizerAlpha) {
*encoderChanges |= AVIF_ENCODER_CHANGE_MIN_QUANTIZER_ALPHA;
}
if (lastEncoder->maxQuantizerAlpha != encoder->maxQuantizerAlpha) {
*encoderChanges |= AVIF_ENCODER_CHANGE_MAX_QUANTIZER_ALPHA;
}
if (encoder->data->lastTileRowsLog2 != encoder->data->tileRowsLog2) {
*encoderChanges |= AVIF_ENCODER_CHANGE_TILE_ROWS_LOG2;
}
if (encoder->data->lastTileColsLog2 != encoder->data->tileColsLog2) {
*encoderChanges |= AVIF_ENCODER_CHANGE_TILE_COLS_LOG2;
}
if (memcmp(&lastEncoder->scalingMode, &encoder->scalingMode, sizeof(avifScalingMode)) != 0) {
*encoderChanges |= AVIF_ENCODER_CHANGE_SCALING_MODE;
}
if (encoder->csOptions->count > 0) {
*encoderChanges |= AVIF_ENCODER_CHANGE_CODEC_SPECIFIC;
}
#if defined(AVIF_ENABLE_EXPERIMENTAL_SAMPLE_TRANSFORM)
if (lastEncoder->sampleTransformRecipe != encoder->sampleTransformRecipe) {
return AVIF_FALSE;
}
#endif
return AVIF_TRUE;
}
// Same as 'avifEncoderWriteColorProperties' but for the colr nclx box only.
static avifResult avifEncoderWriteNclxProperty(avifRWStream * dedupStream,
avifRWStream * outputStream,
const avifImage * imageMetadata,
avifItemPropertyAssociationArray * associations,
avifItemPropertyDedup * dedup)
{
if (dedup) {
avifItemPropertyDedupStart(dedup);
}
avifBoxMarker colr;
AVIF_CHECKRES(avifRWStreamWriteBox(dedupStream, "colr", AVIF_BOX_SIZE_TBD, &colr));
AVIF_CHECKRES(avifRWStreamWriteChars(dedupStream, "nclx", 4)); // unsigned int(32) colour_type;
AVIF_CHECKRES(avifRWStreamWriteU16(dedupStream, imageMetadata->colorPrimaries)); // unsigned int(16) colour_primaries;
AVIF_CHECKRES(avifRWStreamWriteU16(dedupStream, imageMetadata->transferCharacteristics)); // unsigned int(16) transfer_characteristics;
AVIF_CHECKRES(avifRWStreamWriteU16(dedupStream, imageMetadata->matrixCoefficients)); // unsigned int(16) matrix_coefficients;
AVIF_CHECKRES(avifRWStreamWriteBits(dedupStream, (imageMetadata->yuvRange == AVIF_RANGE_FULL) ? 1 : 0, /*bitCount=*/1)); // unsigned int(1) full_range_flag;
AVIF_CHECKRES(avifRWStreamWriteBits(dedupStream, 0, /*bitCount=*/7)); // unsigned int(7) reserved = 0;
avifRWStreamFinishBox(dedupStream, colr);
if (dedup) {
AVIF_CHECKRES(avifItemPropertyDedupFinish(dedup, outputStream, associations, /*essential=*/AVIF_FALSE));
}
return AVIF_RESULT_OK;
}
static avifResult avifEncoderWritePaspProperty(avifRWStream * dedupStream,
avifRWStream * outputStream,
const avifImage * imageMetadata,
avifItemPropertyAssociationArray * associations,
avifItemPropertyDedup * dedup);
static avifResult avifEncoderWriteTransformativeProperties(avifRWStream * dedupStream,
avifRWStream * outputStream,
const avifImage * imageMetadata,
avifItemPropertyAssociationArray * associations,
avifItemPropertyDedup * dedup);
// This function is used in two codepaths:
// * writing color *item* properties
// * writing color *track* properties
//
// Item properties must have property associations with them and can be deduplicated (by reusing
// these associations), so this function leverages the ipma and dedup arguments to do this.
//
// Track properties, however, are implicitly associated by the track in which they are contained, so
// there is no need to build a property association box (ipma), and no way to deduplicate/reuse a
// property. In this case, the ipma and dedup properties should/will be set to NULL, and this
// function will avoid using them.
static avifResult avifEncoderWriteColorProperties(avifRWStream * outputStream,
const avifImage * imageMetadata,
avifItemPropertyAssociationArray * associations,
avifItemPropertyDedup * dedup)
{
// outputStream is the final bitstream that will be output by the libavif encoder API.
// dedupStream is either equal to outputStream or to &dedup->s which is a temporary stream used
// to store parts of the final bitstream; these parts may be discarded if they are a duplicate
// of an already stored property.
avifRWStream * dedupStream = outputStream;
if (dedup) {
AVIF_ASSERT_OR_RETURN(associations);
// Use the dedup's temporary stream for box writes.
dedupStream = &dedup->s;
}
if (imageMetadata->icc.size > 0) {
if (dedup) {
avifItemPropertyDedupStart(dedup);
}
avifBoxMarker colr;
AVIF_CHECKRES(avifRWStreamWriteBox(dedupStream, "colr", AVIF_BOX_SIZE_TBD, &colr));
AVIF_CHECKRES(avifRWStreamWriteChars(dedupStream, "prof", 4)); // unsigned int(32) colour_type;
AVIF_CHECKRES(avifRWStreamWrite(dedupStream, imageMetadata->icc.data, imageMetadata->icc.size));
avifRWStreamFinishBox(dedupStream, colr);
if (dedup) {
AVIF_CHECKRES(avifItemPropertyDedupFinish(dedup, outputStream, associations, /*essential=*/AVIF_FALSE));
}
}
// HEIF 6.5.5.1, from Amendment 3 allows multiple colr boxes: "at most one for a given value of colour type"
// Therefore, *always* writing an nclx box, even if a prof box was already written above.
AVIF_CHECKRES(avifEncoderWriteNclxProperty(dedupStream, outputStream, imageMetadata, associations, dedup));
AVIF_CHECKRES(avifEncoderWritePaspProperty(dedupStream, outputStream, imageMetadata, associations, dedup));
return AVIF_RESULT_OK;
}
static avifResult avifEncoderWriteContentLightLevelInformation(avifRWStream * outputStream,
const avifContentLightLevelInformationBox * clli)
{
AVIF_CHECKRES(avifRWStreamWriteBits(outputStream, clli->maxCLL, 16)); // unsigned int(16) max_content_light_level;
AVIF_CHECKRES(avifRWStreamWriteBits(outputStream, clli->maxPALL, 16)); // unsigned int(16) max_pic_average_light_level;
return AVIF_RESULT_OK;
}
// Same as 'avifEncoderWriteColorProperties' but for properties related to High Dynamic Range only.
static avifResult avifEncoderWriteHDRProperties(avifRWStream * dedupStream,
avifRWStream * outputStream,
const avifImage * imageMetadata,
avifItemPropertyAssociationArray * associations,
avifItemPropertyDedup * dedup)
{
// Write Content Light Level Information, if present
if (imageMetadata->clli.maxCLL || imageMetadata->clli.maxPALL) {
if (dedup) {
avifItemPropertyDedupStart(dedup);
}
avifBoxMarker clli;
AVIF_CHECKRES(avifRWStreamWriteBox(dedupStream, "clli", AVIF_BOX_SIZE_TBD, &clli));
AVIF_CHECKRES(avifEncoderWriteContentLightLevelInformation(dedupStream, &imageMetadata->clli));
avifRWStreamFinishBox(dedupStream, clli);
if (dedup) {
AVIF_CHECKRES(avifItemPropertyDedupFinish(dedup, outputStream, associations, /*essential=*/AVIF_FALSE));
}
}
// TODO(maryla): add other HDR boxes: mdcv, cclv, etc. (in avifEncoderWriteMiniHDRProperties() too)
return AVIF_RESULT_OK;
}
#if defined(AVIF_ENABLE_EXPERIMENTAL_MINI)
static avifResult avifEncoderWriteMiniHDRProperties(avifRWStream * outputStream, const avifImage * imageMetadata)
{
const avifBool hasClli = imageMetadata->clli.maxCLL != 0 || imageMetadata->clli.maxPALL != 0;
const avifBool hasMdcv = AVIF_FALSE;
const avifBool hasCclv = AVIF_FALSE;
const avifBool hasAmve = AVIF_FALSE;
const avifBool hasReve = AVIF_FALSE;
const avifBool hasNdwt = AVIF_FALSE;
AVIF_CHECKRES(avifRWStreamWriteBits(outputStream, hasClli, 1)); // bit(1) clli_flag;
AVIF_CHECKRES(avifRWStreamWriteBits(outputStream, hasMdcv, 1)); // bit(1) mdcv_flag;
AVIF_CHECKRES(avifRWStreamWriteBits(outputStream, hasCclv, 1)); // bit(1) cclv_flag;
AVIF_CHECKRES(avifRWStreamWriteBits(outputStream, hasAmve, 1)); // bit(1) amve_flag;
AVIF_CHECKRES(avifRWStreamWriteBits(outputStream, hasReve, 1)); // bit(1) reve_flag;
AVIF_CHECKRES(avifRWStreamWriteBits(outputStream, hasNdwt, 1)); // bit(1) ndwt_flag;
if (hasClli) {
// ContentLightLevel clli;
AVIF_CHECKRES(avifEncoderWriteContentLightLevelInformation(outputStream, &imageMetadata->clli));
}
if (hasMdcv) {
// MasteringDisplayColourVolume mdcv;
}
if (hasCclv) {
// ContentColourVolume cclv;
}
if (hasAmve) {
// AmbientViewingEnvironment amve;
}
if (hasReve) {
// ReferenceViewingEnvironment reve;
}
if (hasNdwt) {
// NominalDiffuseWhite ndwt;
}
return AVIF_RESULT_OK;
}
#endif // AVIF_ENABLE_EXPERIMENTAL_MINI
static avifResult avifEncoderWritePaspProperty(avifRWStream * dedupStream,
avifRWStream * outputStream,
const avifImage * imageMetadata,
avifItemPropertyAssociationArray * associations,
avifItemPropertyDedup * dedup)
{
if (imageMetadata->transformFlags & AVIF_TRANSFORM_PASP) {
if (dedup) {
avifItemPropertyDedupStart(dedup);
}
avifBoxMarker pasp;
AVIF_CHECKRES(avifRWStreamWriteBox(dedupStream, "pasp", AVIF_BOX_SIZE_TBD, &pasp));
AVIF_CHECKRES(avifRWStreamWriteU32(dedupStream, imageMetadata->pasp.hSpacing)); // unsigned int(32) hSpacing;
AVIF_CHECKRES(avifRWStreamWriteU32(dedupStream, imageMetadata->pasp.vSpacing)); // unsigned int(32) vSpacing;
avifRWStreamFinishBox(dedupStream, pasp);
if (dedup) {
AVIF_CHECKRES(avifItemPropertyDedupFinish(dedup, outputStream, associations, /*essential=*/AVIF_FALSE));
}
}
return AVIF_RESULT_OK;
}
static avifResult avifEncoderWriteTransformativeProperties(avifRWStream * dedupStream,
avifRWStream * outputStream,
const avifImage * imageMetadata,
avifItemPropertyAssociationArray * associations,
avifItemPropertyDedup * dedup)
{
if (imageMetadata->transformFlags & AVIF_TRANSFORM_CLAP) {
if (dedup) {
avifItemPropertyDedupStart(dedup);
}
avifBoxMarker clap;
AVIF_CHECKRES(avifRWStreamWriteBox(dedupStream, "clap", AVIF_BOX_SIZE_TBD, &clap));
AVIF_CHECKRES(avifRWStreamWriteU32(dedupStream, imageMetadata->clap.widthN)); // unsigned int(32) cleanApertureWidthN;
AVIF_CHECKRES(avifRWStreamWriteU32(dedupStream, imageMetadata->clap.widthD)); // unsigned int(32) cleanApertureWidthD;
AVIF_CHECKRES(avifRWStreamWriteU32(dedupStream, imageMetadata->clap.heightN)); // unsigned int(32) cleanApertureHeightN;
AVIF_CHECKRES(avifRWStreamWriteU32(dedupStream, imageMetadata->clap.heightD)); // unsigned int(32) cleanApertureHeightD;
AVIF_CHECKRES(avifRWStreamWriteU32(dedupStream, imageMetadata->clap.horizOffN)); // unsigned int(32) horizOffN;
AVIF_CHECKRES(avifRWStreamWriteU32(dedupStream, imageMetadata->clap.horizOffD)); // unsigned int(32) horizOffD;
AVIF_CHECKRES(avifRWStreamWriteU32(dedupStream, imageMetadata->clap.vertOffN)); // unsigned int(32) vertOffN;
AVIF_CHECKRES(avifRWStreamWriteU32(dedupStream, imageMetadata->clap.vertOffD)); // unsigned int(32) vertOffD;
avifRWStreamFinishBox(dedupStream, clap);
if (dedup) {
AVIF_CHECKRES(avifItemPropertyDedupFinish(dedup, outputStream, associations, /*essential=*/AVIF_TRUE));
}
}
if (imageMetadata->transformFlags & AVIF_TRANSFORM_IROT) {
if (dedup) {
avifItemPropertyDedupStart(dedup);
}
avifBoxMarker irot;
AVIF_CHECKRES(avifRWStreamWriteBox(dedupStream, "irot", AVIF_BOX_SIZE_TBD, &irot));
AVIF_CHECKRES(avifRWStreamWriteBits(dedupStream, 0, /*bitCount=*/6)); // unsigned int (6) reserved = 0;
AVIF_CHECKRES(avifRWStreamWriteBits(dedupStream, imageMetadata->irot.angle & 0x3, /*bitCount=*/2)); // unsigned int (2) angle;
avifRWStreamFinishBox(dedupStream, irot);
if (dedup) {
AVIF_CHECKRES(avifItemPropertyDedupFinish(dedup, outputStream, associations, /*essential=*/AVIF_TRUE));
}
}
if (imageMetadata->transformFlags & AVIF_TRANSFORM_IMIR) {
if (dedup) {
avifItemPropertyDedupStart(dedup);
}
avifBoxMarker imir;
AVIF_CHECKRES(avifRWStreamWriteBox(dedupStream, "imir", AVIF_BOX_SIZE_TBD, &imir));
AVIF_CHECKRES(avifRWStreamWriteBits(dedupStream, 0, /*bitCount=*/7)); // unsigned int(7) reserved = 0;
AVIF_CHECKRES(avifRWStreamWriteBits(dedupStream, imageMetadata->imir.axis ? 1 : 0, /*bitCount=*/1)); // unsigned int(1) axis;
avifRWStreamFinishBox(dedupStream, imir);
if (dedup) {
AVIF_CHECKRES(avifItemPropertyDedupFinish(dedup, outputStream, associations, /*essential=*/AVIF_TRUE));
}
}
return AVIF_RESULT_OK;
}
static avifResult avifRWStreamWriteHandlerBox(avifRWStream * s, const char handlerType[4])
{
avifBoxMarker hdlr;
AVIF_CHECKRES(avifRWStreamWriteFullBox(s, "hdlr", AVIF_BOX_SIZE_TBD, 0, 0, &hdlr));
AVIF_CHECKRES(avifRWStreamWriteU32(s, 0)); // unsigned int(32) pre_defined = 0;
AVIF_CHECKRES(avifRWStreamWriteChars(s, handlerType, 4)); // unsigned int(32) handler_type;
AVIF_CHECKRES(avifRWStreamWriteZeros(s, 12)); // const unsigned int(32)[3] reserved = 0;
AVIF_CHECKRES(avifRWStreamWriteChars(s, "", 1)); // string name; (writing null terminator)
avifRWStreamFinishBox(s, hdlr);
return AVIF_RESULT_OK;
}
// Write unassociated metadata items (EXIF, XMP) to a small meta box inside of a trak box.
// These items are implicitly associated with the track they are contained within.
static avifResult avifEncoderWriteTrackMetaBox(avifEncoder * encoder, avifRWStream * s)
{
// Count how many non-image items (such as EXIF/XMP) are being written
uint32_t metadataItemCount = 0;
for (uint32_t itemIndex = 0; itemIndex < encoder->data->items.count; ++itemIndex) {
avifEncoderItem * item = &encoder->data->items.item[itemIndex];
if (memcmp(item->type, encoder->data->imageItemType, 4) != 0) {
++metadataItemCount;
}
}
if (metadataItemCount == 0) {
// Don't even bother writing the trak meta box
return AVIF_RESULT_OK;
}
avifBoxMarker meta;
AVIF_CHECKRES(avifRWStreamWriteFullBox(s, "meta", AVIF_BOX_SIZE_TBD, 0, 0, &meta));
AVIF_CHECKRES(avifRWStreamWriteHandlerBox(s, "pict"));
avifBoxMarker iloc;
AVIF_CHECKRES(avifRWStreamWriteFullBox(s, "iloc", AVIF_BOX_SIZE_TBD, 0, 0, &iloc));
AVIF_CHECKRES(avifRWStreamWriteBits(s, 4, /*bitCount=*/4)); // unsigned int(4) offset_size;
AVIF_CHECKRES(avifRWStreamWriteBits(s, 4, /*bitCount=*/4)); // unsigned int(4) length_size;
AVIF_CHECKRES(avifRWStreamWriteBits(s, 0, /*bitCount=*/4)); // unsigned int(4) base_offset_size;
AVIF_CHECKRES(avifRWStreamWriteBits(s, 0, /*bitCount=*/4)); // unsigned int(4) reserved;
AVIF_CHECKRES(avifRWStreamWriteU16(s, (uint16_t)metadataItemCount)); // unsigned int(16) item_count;
for (uint32_t trakItemIndex = 0; trakItemIndex < encoder->data->items.count; ++trakItemIndex) {
avifEncoderItem * item = &encoder->data->items.item[trakItemIndex];
if (memcmp(item->type, encoder->data->imageItemType, 4) == 0) {
// Skip over all non-metadata items
continue;
}
AVIF_CHECKRES(avifRWStreamWriteU16(s, item->id)); // unsigned int(16) item_ID;
AVIF_CHECKRES(avifRWStreamWriteU16(s, 0)); // unsigned int(16) data_reference_index;
AVIF_CHECKRES(avifRWStreamWriteU16(s, 1)); // unsigned int(16) extent_count;
AVIF_CHECKRES(avifEncoderItemAddMdatFixup(item, s)); //
AVIF_CHECKRES(avifRWStreamWriteU32(s, 0 /* set later */)); // unsigned int(offset_size*8) extent_offset;
AVIF_CHECKRES(avifRWStreamWriteU32(s, (uint32_t)item->metadataPayload.size)); // unsigned int(length_size*8) extent_length;
}
avifRWStreamFinishBox(s, iloc);
avifBoxMarker iinf;
AVIF_CHECKRES(avifRWStreamWriteFullBox(s, "iinf", AVIF_BOX_SIZE_TBD, 0, 0, &iinf));
AVIF_CHECKRES(avifRWStreamWriteU16(s, (uint16_t)metadataItemCount)); // unsigned int(16) entry_count;
for (uint32_t trakItemIndex = 0; trakItemIndex < encoder->data->items.count; ++trakItemIndex) {
avifEncoderItem * item = &encoder->data->items.item[trakItemIndex];
if (memcmp(item->type, encoder->data->imageItemType, 4) == 0) {
continue;
}
AVIF_ASSERT_OR_RETURN(!item->hiddenImage);
avifBoxMarker infe;
AVIF_CHECKRES(avifRWStreamWriteFullBox(s, "infe", AVIF_BOX_SIZE_TBD, 2, 0, &infe));
AVIF_CHECKRES(avifRWStreamWriteU16(s, item->id)); // unsigned int(16) item_ID;
AVIF_CHECKRES(avifRWStreamWriteU16(s, 0)); // unsigned int(16) item_protection_index;
AVIF_CHECKRES(avifRWStreamWrite(s, item->type, 4)); // unsigned int(32) item_type;
AVIF_CHECKRES(avifRWStreamWriteChars(s, item->infeName, item->infeNameSize)); // string item_name; (writing null terminator)
if (item->infeContentType && item->infeContentTypeSize) { // string content_type; (writing null terminator)
AVIF_CHECKRES(avifRWStreamWriteChars(s, item->infeContentType, item->infeContentTypeSize));
}
avifRWStreamFinishBox(s, infe);
}
avifRWStreamFinishBox(s, iinf);
avifRWStreamFinishBox(s, meta);
return AVIF_RESULT_OK;
}
static avifResult avifWriteGridPayload(avifRWData * data, uint32_t gridCols, uint32_t gridRows, uint32_t gridWidth, uint32_t gridHeight)
{
// ISO/IEC 23008-12 6.6.2.3.2
// aligned(8) class ImageGrid {
// unsigned int(8) version = 0;
// unsigned int(8) flags;
// FieldLength = ((flags & 1) + 1) * 16;
// unsigned int(8) rows_minus_one;
// unsigned int(8) columns_minus_one;
// unsigned int(FieldLength) output_width;
// unsigned int(FieldLength) output_height;
// }
uint8_t gridFlags = ((gridWidth > 65535) || (gridHeight > 65535)) ? 1 : 0;
avifRWStream s;
avifRWStreamStart(&s, data);
AVIF_CHECKRES(avifRWStreamWriteU8(&s, 0)); // unsigned int(8) version = 0;
AVIF_CHECKRES(avifRWStreamWriteU8(&s, gridFlags)); // unsigned int(8) flags;
AVIF_CHECKRES(avifRWStreamWriteU8(&s, (uint8_t)(gridRows - 1))); // unsigned int(8) rows_minus_one;
AVIF_CHECKRES(avifRWStreamWriteU8(&s, (uint8_t)(gridCols - 1))); // unsigned int(8) columns_minus_one;
if (gridFlags & 1) {
AVIF_CHECKRES(avifRWStreamWriteU32(&s, gridWidth)); // unsigned int(FieldLength) output_width;
AVIF_CHECKRES(avifRWStreamWriteU32(&s, gridHeight)); // unsigned int(FieldLength) output_height;
} else {
uint16_t tmpWidth = (uint16_t)gridWidth;
uint16_t tmpHeight = (uint16_t)gridHeight;
AVIF_CHECKRES(avifRWStreamWriteU16(&s, tmpWidth)); // unsigned int(FieldLength) output_width;
AVIF_CHECKRES(avifRWStreamWriteU16(&s, tmpHeight)); // unsigned int(FieldLength) output_height;
}
avifRWStreamFinishWrite(&s);
return AVIF_RESULT_OK;
}
static avifBool avifGainMapIdenticalChannels(const avifGainMap * gainMap)
{
return gainMap->gainMapMin[0].n == gainMap->gainMapMin[1].n && gainMap->gainMapMin[0].n == gainMap->gainMapMin[2].n &&
gainMap->gainMapMin[0].d == gainMap->gainMapMin[1].d && gainMap->gainMapMin[0].d == gainMap->gainMapMin[2].d &&
gainMap->gainMapMax[0].n == gainMap->gainMapMax[1].n && gainMap->gainMapMax[0].n == gainMap->gainMapMax[2].n &&
gainMap->gainMapMax[0].d == gainMap->gainMapMax[1].d && gainMap->gainMapMax[0].d == gainMap->gainMapMax[2].d &&
gainMap->gainMapGamma[0].n == gainMap->gainMapGamma[1].n && gainMap->gainMapGamma[0].n == gainMap->gainMapGamma[2].n &&
gainMap->gainMapGamma[0].d == gainMap->gainMapGamma[1].d && gainMap->gainMapGamma[0].d == gainMap->gainMapGamma[2].d &&
gainMap->baseOffset[0].n == gainMap->baseOffset[1].n && gainMap->baseOffset[0].n == gainMap->baseOffset[2].n &&
gainMap->baseOffset[0].d == gainMap->baseOffset[1].d && gainMap->baseOffset[0].d == gainMap->baseOffset[2].d &&
gainMap->alternateOffset[0].n == gainMap->alternateOffset[1].n &&
gainMap->alternateOffset[0].n == gainMap->alternateOffset[2].n &&
gainMap->alternateOffset[0].d == gainMap->alternateOffset[1].d &&
gainMap->alternateOffset[0].d == gainMap->alternateOffset[2].d;
}
// Returns the number of bytes written by avifWriteGainmapMetadata().
static avifBool avifGainMapMetadataSize(const avifGainMap * gainMap)
{
const uint8_t channelCount = avifGainMapIdenticalChannels(gainMap) ? 1u : 3u;
return sizeof(uint16_t) * 2 + sizeof(uint8_t) + sizeof(uint32_t) * 4 + channelCount * sizeof(uint32_t) * 10;
}
static avifResult avifWriteGainmapMetadata(avifRWStream * s, const avifGainMap * gainMap, avifDiagnostics * diag)
{
AVIF_CHECKRES(avifGainMapValidateMetadata(gainMap, diag));
const size_t offset = avifRWStreamOffset(s);
// GainMapMetadata syntax as per clause C.2.2 of ISO 21496-1:
// GainMapVersion syntax as per clause C.2.2 of ISO 21496-1:
const uint16_t minimumVersion = 0;
AVIF_CHECKRES(avifRWStreamWriteBits(s, minimumVersion, 16)); // unsigned int(16) minimum_version;
const uint16_t writerVersion = 0;
AVIF_CHECKRES(avifRWStreamWriteBits(s, writerVersion, 16)); // unsigned int(16) writer_version;
if (minimumVersion == 0) {
const uint8_t channelCount = avifGainMapIdenticalChannels(gainMap) ? 1u : 3u;
AVIF_CHECKRES(avifRWStreamWriteBits(s, channelCount == 3, 1)); // unsigned int(1) is_multichannel;
AVIF_CHECKRES(avifRWStreamWriteBits(s, gainMap->useBaseColorSpace, 1)); // unsigned int(1) use_base_colour_space;