-
Notifications
You must be signed in to change notification settings - Fork 0
/
heif.go
1509 lines (1275 loc) · 41.7 KB
/
heif.go
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
/*
* GO interface to libheif
* Copyright (c) 2018 Dirk Farin <dirk.farin@gmail.com>
*
* This file is part of heif, an example application using libheif.
*
* libheif is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* libheif is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with libheif. If not, see <http://www.gnu.org/licenses/>.
*/
package heif
/*
#cgo pkg-config: libheif
#include <stdlib.h>
#include <string.h> // We use 'memcpy'
#include <libheif/heif.h>
*/
import "C"
import (
"fmt"
"image"
"image/color"
"io"
"io/ioutil"
"runtime"
"unsafe"
)
func GetVersion() string {
return C.GoString(C.heif_get_version())
}
type Compression C.enum_heif_compression_format
const (
CompressionUndefined = C.heif_compression_undefined
CompressionHEVC = C.heif_compression_HEVC
CompressionAV1 = C.heif_compression_AV1
CompressionAVC = C.heif_compression_AVC
CompressionJPEG = C.heif_compression_JPEG
CompressionJPEG2000 = C.heif_compression_JPEG2000
CompressionVVC = C.heif_compression_VVC
CompressionEVC = C.heif_compression_EVC
CompressionUncompressed = C.heif_compression_uncompressed
CompressionMask = C.heif_compression_mask
)
type Chroma C.enum_heif_chroma
const (
ChromaUndefined = C.heif_chroma_undefined
ChromaMonochrome = C.heif_chroma_monochrome
Chroma420 = C.heif_chroma_420
Chroma422 = C.heif_chroma_422
Chroma444 = C.heif_chroma_444
ChromaInterleavedRGB = C.heif_chroma_interleaved_RGB
ChromaInterleavedRGBA = C.heif_chroma_interleaved_RGBA
ChromaInterleavedRRGGBBAA_BE = C.heif_chroma_interleaved_RRGGBBAA_BE
ChromaInterleavedRRGGBBAA_LE = C.heif_chroma_interleaved_RRGGBBAA_LE
ChromaInterleavedRRGGBB_BE = C.heif_chroma_interleaved_RRGGBB_BE
ChromaInterleavedRRGGBB_LE = C.heif_chroma_interleaved_RRGGBB_LE
ChromaInterleaved24Bit = C.heif_chroma_interleaved_24bit
ChromaInterleaved32Bit = C.heif_chroma_interleaved_32bit
)
type ChromaDownsamplingAlgorithm C.enum_heif_chroma_downsampling_algorithm
const (
ChromaDownsamplingAverage = C.heif_chroma_downsampling_average
ChromaDownsamplingNearestNeighbor = C.heif_chroma_downsampling_nearest_neighbor
ChromaDownsamplingSharpYUV = C.heif_chroma_downsampling_sharp_yuv
)
type ChromaUpsamplingAlgorithm C.enum_heif_chroma_upsampling_algorithm
const (
ChromaUpsamplingNearestNeighbor = C.heif_chroma_upsampling_nearest_neighbor
ChromaUpsamplingBilinear = C.heif_chroma_upsampling_bilinear
)
type Colorspace C.enum_heif_colorspace
const (
ColorspaceUndefined = C.heif_colorspace_undefined
ColorspaceYCbCr = C.heif_colorspace_YCbCr
ColorspaceRGB = C.heif_colorspace_RGB
ColorspaceMonochrome = C.heif_colorspace_monochrome
)
type Channel C.enum_heif_channel
const (
ChannelY = C.heif_channel_Y
ChannelCb = C.heif_channel_Cb
ChannelCr = C.heif_channel_Cr
ChannelR = C.heif_channel_R
ChannelG = C.heif_channel_G
ChannelB = C.heif_channel_B
ChannelAlpha = C.heif_channel_Alpha
ChannelInterleaved = C.heif_channel_interleaved
)
type ProgressStep C.enum_heif_progress_step
const (
ProgressStepTotal = C.heif_progress_step_total
ProgressStepLoadTile = C.heif_progress_step_load_tile
)
type LosslessMode int
const (
LosslessModeDisabled LosslessMode = iota
LosslessModeEnabled
)
type LoggingLevel int
const (
LoggingLevelNone LoggingLevel = iota
LoggingLevelBasic
LoggingLevelAdvanced
LoggingLevelFull
)
// --- HeifError
type ErrorCode C.enum_heif_error_code
const (
ErrorOK = C.heif_error_Ok
// Input file does not exist.
ErrorInputDoesNotExist = C.heif_error_Input_does_not_exist
// Error in input file. Corrupted or invalid content.
errorInvalidInput = C.heif_error_Invalid_input
// Input file type is not supported.
ErrorUnsupportedFiletype = C.heif_error_Unsupported_filetype
// Image requires an unsupported decoder feature.
ErrorUnsupportedFeature = C.heif_error_Unsupported_feature
// Library API has been used in an invalid way.
ErrorUsage = C.heif_error_Usage_error
// Could not allocate enough memory.
ErrorMemoryAllocation = C.heif_error_Memory_allocation_error
// The decoder plugin generated an error
ErrorDecoderPlugin = C.heif_error_Decoder_plugin_error
// The decoder plugin generated an error
ErrorEncoderPlugin = C.heif_error_Encoder_plugin_error
// Error during encoding or when writing to the output
ErrorEncoding = C.heif_error_Encoding_error
// Application has asked for a color profile type that does not exist
ErrorColorProfileDoesNotExist = C.heif_error_Color_profile_does_not_exist
ErrorPluginLoadingError = C.heif_error_Plugin_loading_error
)
type ErrorSubcode C.enum_heif_suberror_code
const (
// no further information available
SuberrorUnspecified = C.heif_suberror_Unspecified
// --- Invalid_input ---
// End of data reached unexpectedly.
SuberrorEndOfData = C.heif_suberror_End_of_data
// Size of box (defined in header) is wrong
SuberrorInvalidBoxSize = C.heif_suberror_Invalid_box_size
// Mandatory 'ftyp' box is missing
SuberrorNoFtypBox = C.heif_suberror_No_ftyp_box
SuberrorNoIdatBox = C.heif_suberror_No_idat_box
SuberrorNoMetaBox = C.heif_suberror_No_meta_box
SuberrorNoHdlrBox = C.heif_suberror_No_hdlr_box
SuberrorNoHvcCBox = C.heif_suberror_No_hvcC_box
SuberrorNoPitmBox = C.heif_suberror_No_pitm_box
SuberrorNoIpcoBox = C.heif_suberror_No_ipco_box
SuberrorNoIpmaBox = C.heif_suberror_No_ipma_box
SuberrorNoIlocBox = C.heif_suberror_No_iloc_box
SuberrorNoIinfBox = C.heif_suberror_No_iinf_box
SuberrorNoIprpBox = C.heif_suberror_No_iprp_box
SuberrorNoIrefBox = C.heif_suberror_No_iref_box
SuberrorNoPictHandler = C.heif_suberror_No_pict_handler
// An item property referenced in the 'ipma' box is not existing in the 'ipco' container.
SuberrorIpmaBoxReferencesNonexistingProperty = C.heif_suberror_Ipma_box_references_nonexisting_property
// No properties have been assigned to an item.
SuberrorNoPropertiesAssignedToItem = C.heif_suberror_No_properties_assigned_to_item
// Image has no (compressed) data
SuberrorNoItemData = C.heif_suberror_No_item_data
// Invalid specification of image grid (tiled image)
SuberrorInvalidGridData = C.heif_suberror_Invalid_grid_data
// Tile-images in a grid image are missing
SuberrorMissingGridImages = C.heif_suberror_Missing_grid_images
SuberrorNoAV1CBox = C.heif_suberror_No_av1C_box
SuberrorInvalidCleanAperture = C.heif_suberror_Invalid_clean_aperture
// Invalid specification of overlay image
SuberrorInvalidOverlayData = C.heif_suberror_Invalid_overlay_data
// Overlay image completely outside of visible canvas area
SuberrorOverlayImageOutsideOfCanvas = C.heif_suberror_Overlay_image_outside_of_canvas
SuberrorPluginIsNotLoaded = C.heif_suberror_Plugin_is_not_loaded
SuberrorPluginLoadingError = C.heif_suberror_Plugin_loading_error
SuberrorAuxiliaryImageTypeUnspecified = C.heif_suberror_Auxiliary_image_type_unspecified
SuberrorCannotReadPluginDirectory = C.heif_suberror_Cannot_read_plugin_directory
SuberrorNoOrInvalidPrimaryItem = C.heif_suberror_No_or_invalid_primary_item
SuberrorNoInfeBox = C.heif_suberror_No_infe_box
SuberrorUnknownColorProfileType = C.heif_suberror_Unknown_color_profile_type
SuberrorWrongTileImageChromaFormat = C.heif_suberror_Wrong_tile_image_chroma_format
SuberrorInvalidFractionalNumber = C.heif_suberror_Invalid_fractional_number
SuberrorInvalidImageSize = C.heif_suberror_Invalid_image_size
// --- Memory_allocation_error ---
// A security limit preventing unreasonable memory allocations was exceeded by the input file.
// Please check whether the file is valid. If it is, contact us so that we could increase the
// security limits further.
SuberrorSecurityLimitExceeded = C.heif_suberror_Security_limit_exceeded
// --- Usage_error ---
// An item ID was used that is not present in the file.
SuberrorNonexistingItemReferenced = C.heif_suberror_Nonexisting_item_referenced // also used for Invalid_input
// An API argument was given a NULL pointer, which is not allowed for that function.
SuberrorNullPointerArgument = C.heif_suberror_Null_pointer_argument
// Image channel referenced that does not exist in the image
SuberrorNonexistingImageChannelReferenced = C.heif_suberror_Nonexisting_image_channel_referenced
// The version of the passed plugin is not supported.
SuberrorUnsupportedPluginVersion = C.heif_suberror_Unsupported_plugin_version
// The version of the passed writer is not supported.
SuberrorUnsupportedWriterVersion = C.heif_suberror_Unsupported_writer_version
// The given (encoder) parameter name does not exist.
SuberrorUnsupportedParameter = C.heif_suberror_Unsupported_parameter
// The value for the given parameter is not in the valid range.
SuberrorInvalidParameterValue = C.heif_suberror_Invalid_parameter_value
SuberrorInvalidProperty = C.heif_suberror_Invalid_property
SuberrorItemReferenceCycle = C.heif_suberror_Item_reference_cycle
SuberrorInvalidPixiBox = C.heif_suberror_Invalid_pixi_box
SuberrorInvalidRegionData = C.heif_suberror_Invalid_region_data
SuberrorWrongTileImagePixelDepth = C.heif_suberror_Wrong_tile_image_pixel_depth
SuberrorUnknownNCLXColorPrimaries = C.heif_suberror_Unknown_NCLX_color_primaries
SuberrorUnknownNCLXTransferCharacteristics = C.heif_suberror_Unknown_NCLX_transfer_characteristics
SuberrorUnknownNCLXMatrixCoefficients = C.heif_suberror_Unknown_NCLX_matrix_coefficients
// --- Unsupported_feature ---
// Image was coded with an unsupported compression method.
SuberrorUnsupportedCodec = C.heif_suberror_Unsupported_codec
// Image is specified in an unknown way, e.g. as tiled grid image (which is supported)
SuberrorUnsupportedImageType = C.heif_suberror_Unsupported_image_type
SuberrorUnsupportedDataVersion = C.heif_suberror_Unsupported_data_version
// The conversion of the source image to the requested chroma / colorspace is not supported.
SuberrorUnsupportedColorConversion = C.heif_suberror_Unsupported_color_conversion
SuberrorUnsupportedItemConstructionMethod = C.heif_suberror_Unsupported_item_construction_method
SuberrorUnsupportedHeaderCompressionMethod = C.heif_suberror_Unsupported_header_compression_method
// --- Encoder_plugin_error ---
SuberrorUnsupportedBitDepth = C.heif_suberror_Unsupported_bit_depth
// --- Encoding_error ---
SuberrorCannotWriteOutputData = C.heif_suberror_Cannot_write_output_data
SuberrorEncoderInitialization = C.heif_suberror_Encoder_initialization
SuberrorEncoderEncoding = C.heif_suberror_Encoder_encoding
SuberrorEncoderCleanup = C.heif_suberror_Encoder_cleanup
SuberrorTooManyRegions = C.heif_suberror_Too_many_regions
)
type HeifError struct {
Code ErrorCode
Subcode ErrorSubcode
Message string
}
func (e *HeifError) Error() string {
return e.Message
}
func convertHeifError(cerror C.struct_heif_error) error {
if cerror.code == ErrorOK {
return nil
}
return &HeifError{
Code: ErrorCode(cerror.code),
Subcode: ErrorSubcode(cerror.subcode),
Message: C.GoString(cerror.message),
}
}
func convertItemIDs(ids []C.heif_item_id, count int) []int {
result := make([]int, count)
for i := 0; i < count; i++ {
result[i] = int(ids[i])
}
return result
}
// --- Context
type Context struct {
context *C.struct_heif_context
}
func NewContext() (*Context, error) {
ctx := &Context{
context: C.heif_context_alloc(),
}
if ctx.context == nil {
return nil, fmt.Errorf("Could not allocate context")
}
runtime.SetFinalizer(ctx, freeHeifContext)
return ctx, nil
}
func freeHeifContext(c *Context) {
C.heif_context_free(c.context)
c.context = nil
}
func (c *Context) ReadFromFile(filename string) error {
c_filename := C.CString(filename)
defer C.free(unsafe.Pointer(c_filename))
err := C.heif_context_read_from_file(c.context, c_filename, nil)
runtime.KeepAlive(c)
return convertHeifError(err)
}
func (c *Context) ReadFromMemory(data []byte) error {
// TODO: Use reader API internally.
err := C.heif_context_read_from_memory(c.context, unsafe.Pointer(&data[0]), C.size_t(len(data)), nil)
runtime.KeepAlive(c)
return convertHeifError(err)
}
type Encoder struct {
encoder *C.struct_heif_encoder
id string
name string
}
func (e *Encoder) ID() string {
return e.id
}
func (e *Encoder) Name() string {
return e.name
}
func (e *Encoder) SetQuality(q int) error {
err := C.heif_encoder_set_lossy_quality(e.encoder, C.int(q))
runtime.KeepAlive(e)
return convertHeifError(err)
}
func (e *Encoder) SetLossless(l LosslessMode) error {
err := C.heif_encoder_set_lossless(e.encoder, C.int(l))
runtime.KeepAlive(e)
return convertHeifError(err)
}
func (e *Encoder) SetLoggingLevel(l LoggingLevel) error {
err := C.heif_encoder_set_logging_level(e.encoder, C.int(l))
runtime.KeepAlive(e)
return convertHeifError(err)
}
func freeHeifEncoder(enc *Encoder) {
C.heif_encoder_release(enc.encoder)
enc.encoder = nil
}
func (c *Context) convertEncoderDescriptor(d *C.struct_heif_encoder_descriptor) (*Encoder, error) {
cid := C.heif_encoder_descriptor_get_id_name(d)
cname := C.heif_encoder_descriptor_get_name(d)
enc := &Encoder{
id: C.GoString(cid),
name: C.GoString(cname),
}
err := C.heif_context_get_encoder(c.context, d, &enc.encoder)
runtime.KeepAlive(c)
if err := convertHeifError(err); err != nil {
return nil, err
}
runtime.SetFinalizer(enc, freeHeifEncoder)
return enc, nil
}
func (c *Context) NewEncoder(compression Compression) (*Encoder, error) {
const max = 1
descriptors := make([]*C.struct_heif_encoder_descriptor, max)
num := int(C.heif_context_get_encoder_descriptors(c.context, uint32(compression), nil, &descriptors[0], C.int(max)))
runtime.KeepAlive(c)
if num == 0 {
return nil, fmt.Errorf("no encoder for compression %v", compression)
}
return c.convertEncoderDescriptor(descriptors[0])
}
func (c *Context) WriteToFile(filename string) error {
err := C.heif_context_write_to_file(c.context, C.CString(filename))
runtime.KeepAlive(c)
return convertHeifError(err)
}
func (c *Context) GetNumberOfTopLevelImages() int {
i := int(C.heif_context_get_number_of_top_level_images(c.context))
runtime.KeepAlive(c)
return i
}
func (c *Context) IsTopLevelImageID(ID int) bool {
ok := C.heif_context_is_top_level_image_ID(c.context, C.heif_item_id(ID)) != 0
runtime.KeepAlive(c)
return ok
}
func (c *Context) GetListOfTopLevelImageIDs() []int {
num := int(C.heif_context_get_number_of_top_level_images(c.context))
runtime.KeepAlive(c)
if num == 0 {
return []int{}
}
origIDs := make([]C.heif_item_id, num)
C.heif_context_get_list_of_top_level_image_IDs(c.context, &origIDs[0], C.int(num))
runtime.KeepAlive(c)
return convertItemIDs(origIDs, num)
}
func (c *Context) GetPrimaryImageID() (int, error) {
var id C.heif_item_id
err := C.heif_context_get_primary_image_ID(c.context, &id)
runtime.KeepAlive(c)
if err := convertHeifError(err); err != nil {
return 0, err
}
return int(id), nil
}
// --- ImageHandle
type ImageHandle struct {
handle *C.struct_heif_image_handle
}
func freeHeifImageHandle(c *ImageHandle) {
C.heif_image_handle_release(c.handle)
c.handle = nil
}
func (c *Context) GetPrimaryImageHandle() (*ImageHandle, error) {
var handle ImageHandle
err := C.heif_context_get_primary_image_handle(c.context, &handle.handle)
runtime.KeepAlive(c)
if err := convertHeifError(err); err != nil {
return nil, err
}
runtime.SetFinalizer(&handle, freeHeifImageHandle)
return &handle, convertHeifError(err)
}
func (c *Context) GetImageHandle(id int) (*ImageHandle, error) {
var handle ImageHandle
err := C.heif_context_get_image_handle(c.context, C.heif_item_id(id), &handle.handle)
runtime.KeepAlive(c)
if err := convertHeifError(err); err != nil {
return nil, err
}
runtime.SetFinalizer(&handle, freeHeifImageHandle)
return &handle, nil
}
func (h *ImageHandle) IsPrimaryImage() bool {
ok := C.heif_image_handle_is_primary_image(h.handle) != 0
runtime.KeepAlive(h)
return ok
}
func (h *ImageHandle) GetWidth() int {
i := int(C.heif_image_handle_get_width(h.handle))
runtime.KeepAlive(h)
return i
}
func (h *ImageHandle) GetHeight() int {
i := int(C.heif_image_handle_get_height(h.handle))
runtime.KeepAlive(h)
return i
}
func (h *ImageHandle) HasAlphaChannel() bool {
ok := C.heif_image_handle_has_alpha_channel(h.handle) != 0
runtime.KeepAlive(h)
return ok
}
func (h *ImageHandle) HasDepthImage() bool {
ok := C.heif_image_handle_has_depth_image(h.handle) != 0
runtime.KeepAlive(h)
return ok
}
func (h *ImageHandle) GetNumberOfDepthImages() int {
i := int(C.heif_image_handle_get_number_of_depth_images(h.handle))
runtime.KeepAlive(h)
return i
}
func (h *ImageHandle) GetListOfDepthImageIDs() []int {
num := int(C.heif_image_handle_get_number_of_depth_images(h.handle))
runtime.KeepAlive(h)
if num == 0 {
return []int{}
}
origIDs := make([]C.heif_item_id, num)
C.heif_image_handle_get_list_of_depth_image_IDs(h.handle, &origIDs[0], C.int(num))
runtime.KeepAlive(h)
return convertItemIDs(origIDs, num)
}
func (h *ImageHandle) GetDepthImageHandle(depth_image_id int) (*ImageHandle, error) {
var handle ImageHandle
err := C.heif_image_handle_get_depth_image_handle(h.handle, C.heif_item_id(depth_image_id), &handle.handle)
runtime.KeepAlive(h)
if err := convertHeifError(err); err != nil {
return nil, err
}
runtime.SetFinalizer(&handle, freeHeifImageHandle)
return &handle, nil
}
func (h *ImageHandle) GetNumberOfThumbnails() int {
i := int(C.heif_image_handle_get_number_of_thumbnails(h.handle))
runtime.KeepAlive(h)
return i
}
func (h *ImageHandle) GetListOfThumbnailIDs() []int {
num := int(C.heif_image_handle_get_number_of_thumbnails(h.handle))
runtime.KeepAlive(h)
if num == 0 {
return []int{}
}
origIDs := make([]C.heif_item_id, num)
C.heif_image_handle_get_list_of_thumbnail_IDs(h.handle, &origIDs[0], C.int(num))
runtime.KeepAlive(h)
return convertItemIDs(origIDs, num)
}
func (h *ImageHandle) GetThumbnail(thumbnail_id int) (*ImageHandle, error) {
var handle ImageHandle
err := C.heif_image_handle_get_thumbnail(h.handle, C.heif_item_id(thumbnail_id), &handle.handle)
runtime.KeepAlive(h)
runtime.SetFinalizer(&handle, freeHeifImageHandle)
return &handle, convertHeifError(err)
}
// TODO: EXIF metadata
func (h *ImageHandle) GetICCProfle() ([]byte, error) {
size := C.heif_image_handle_get_raw_color_profile_size(h.handle)
if size > 0 {
data := make([]byte, size)
err := C.heif_image_handle_get_raw_color_profile(h.handle, unsafe.Pointer(&data[0]))
return data, convertHeifError(err)
}
return nil, nil
}
func (h *ImageHandle) GetExif() ([]byte, error) {
var exif_id C.heif_item_id
c_meta_type := C.CString("Exif")
defer C.free(unsafe.Pointer(c_meta_type))
n := C.heif_image_handle_get_list_of_metadata_block_IDs(h.handle, c_meta_type, &exif_id, C.int(1))
if n == 1 {
exifSize := C.heif_image_handle_get_metadata_size(h.handle, exif_id)
data := make([]byte, int(exifSize))
err := C.heif_image_handle_get_metadata(h.handle, exif_id, unsafe.Pointer(&data[0]))
return data, convertHeifError(err)
}
return nil, nil
}
// --- Image
type DecodingOptions struct {
options *C.struct_heif_decoding_options
}
func NewDecodingOptions() (*DecodingOptions, error) {
options := &DecodingOptions{
options: C.heif_decoding_options_alloc(),
}
if options.options == nil {
return nil, fmt.Errorf("Could not allocate decoding options")
}
runtime.SetFinalizer(options, freeHeifDecodingOptions)
return options, nil
}
func freeHeifDecodingOptions(options *DecodingOptions) {
C.heif_decoding_options_free(options.options)
options.options = nil
}
type Image struct {
image *C.struct_heif_image
}
func NewImage(width, height int, colorspace Colorspace, chroma Chroma) (*Image, error) {
var image Image
err := C.heif_image_create(C.int(width), C.int(height), uint32(colorspace), uint32(chroma), &image.image)
if err := convertHeifError(err); err != nil {
return nil, err
}
runtime.SetFinalizer(&image, freeHeifImage)
return &image, nil
}
func freeHeifImage(image *Image) {
C.heif_image_release(image.image)
image.image = nil
}
func (h *ImageHandle) DecodeImage(colorspace Colorspace, chroma Chroma, options *DecodingOptions) (*Image, error) {
var image Image
var opt *C.struct_heif_decoding_options
if options != nil {
opt = options.options
}
err := C.heif_decode_image(h.handle, &image.image, uint32(colorspace), uint32(chroma), opt)
runtime.KeepAlive(h)
if err := convertHeifError(err); err != nil {
return nil, err
}
runtime.SetFinalizer(&image, freeHeifImage)
return &image, nil
}
func (img *Image) GetColorspace() Colorspace {
cs := Colorspace(C.heif_image_get_colorspace(img.image))
runtime.KeepAlive(img)
return cs
}
func (img *Image) GetChromaFormat() Chroma {
c := Chroma(C.heif_image_get_chroma_format(img.image))
runtime.KeepAlive(img)
return c
}
func (img *Image) GetWidth(channel Channel) int {
i := int(C.heif_image_get_width(img.image, uint32(channel)))
runtime.KeepAlive(img)
return i
}
func (img *Image) GetHeight(channel Channel) int {
i := int(C.heif_image_get_height(img.image, uint32(channel)))
runtime.KeepAlive(img)
return i
}
func (img *Image) GetBitsPerPixel(channel Channel) int {
i := int(C.heif_image_get_bits_per_pixel(img.image, uint32(channel)))
runtime.KeepAlive(img)
return i
}
func (img *Image) GetBitsPerPixelRange(channel Channel) int {
i := int(C.heif_image_get_bits_per_pixel_range(img.image, uint32(channel)))
runtime.KeepAlive(img)
return i
}
func (img *Image) GetImage() (image.Image, error) {
var i image.Image
cf := img.GetChromaFormat()
switch cs := img.GetColorspace(); cs {
case ColorspaceYCbCr:
var subsample image.YCbCrSubsampleRatio
switch cf {
case Chroma420:
subsample = image.YCbCrSubsampleRatio420
case Chroma422:
subsample = image.YCbCrSubsampleRatio422
case Chroma444:
subsample = image.YCbCrSubsampleRatio444
default:
return nil, fmt.Errorf("Unsupported YCbCr chroma format: %v", cf)
}
y, err := img.GetPlane(ChannelY)
if err != nil {
return nil, err
}
cb, err := img.GetPlane(ChannelCb)
if err != nil {
return nil, err
}
cr, err := img.GetPlane(ChannelCr)
if err != nil {
return nil, err
}
i = &image.YCbCr{
Y: y.Plane,
Cb: cb.Plane,
Cr: cr.Plane,
YStride: y.Stride,
CStride: cb.Stride,
SubsampleRatio: subsample,
Rect: image.Rectangle{
Min: image.Point{
X: 0,
Y: 0,
},
Max: image.Point{
X: img.GetWidth(ChannelY),
Y: img.GetHeight(ChannelY),
},
},
}
case ColorspaceRGB:
switch cf {
case Chroma444:
r, err := img.GetPlane(ChannelR)
if err != nil {
return nil, err
}
g, err := img.GetPlane(ChannelG)
if err != nil {
return nil, err
}
b, err := img.GetPlane(ChannelB)
if err != nil {
return nil, err
}
width := img.GetWidth(ChannelR)
height := img.GetHeight(ChannelR)
read_pos_r := 0
read_pos_g := 0
read_pos_b := 0
write_pos := 0
var rgba []byte
var stride int
if bpp := img.GetBitsPerPixelRange(ChannelR); bpp > 8 {
// NOTE: We only support the same bits per pixel on all components.
stride = width * 8
rgba = make([]byte, height*stride)
stride_add_r := r.Stride - width*2
stride_add_g := g.Stride - width*2
stride_add_b := b.Stride - width*2
if bpp == 16 {
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
rgba[write_pos] = r.Plane[read_pos_r]
rgba[write_pos+1] = r.Plane[read_pos_r+1]
rgba[write_pos+2] = g.Plane[read_pos_g]
rgba[write_pos+3] = g.Plane[read_pos_g+1]
rgba[write_pos+4] = b.Plane[read_pos_b]
rgba[write_pos+5] = b.Plane[read_pos_b+1]
rgba[write_pos+6] = 0xff
rgba[write_pos+7] = 0xff
read_pos_r += 2
read_pos_g += 2
read_pos_b += 2
write_pos += 8
}
read_pos_r += stride_add_r
read_pos_g += stride_add_g
read_pos_b += stride_add_b
}
} else {
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
r_value := (int16(r.Plane[read_pos_r+1]) << 8) | int16(r.Plane[read_pos_r])
r_value = (r_value << (16 - uint(bpp))) | (r_value >> (2*uint(bpp) - 16))
rgba[write_pos] = byte(r_value >> 8)
rgba[write_pos+1] = byte(r_value & 0xff)
g_value := (int16(g.Plane[read_pos_g+1]) << 8) | int16(g.Plane[read_pos_g])
g_value = (g_value << (16 - uint(bpp))) | (g_value >> (2*uint(bpp) - 16))
rgba[write_pos+2] = byte(g_value >> 8)
rgba[write_pos+3] = byte(g_value & 0xff)
b_value := (int16(b.Plane[read_pos_b+1]) << 8) | int16(b.Plane[read_pos_b])
b_value = (b_value << (16 - uint(bpp))) | (b_value >> (2*uint(bpp) - 16))
rgba[write_pos+4] = byte(b_value >> 8)
rgba[write_pos+5] = byte(b_value & 0xff)
rgba[write_pos+6] = 0xff
rgba[write_pos+7] = 0xff
read_pos_r += 2
read_pos_g += 2
read_pos_b += 2
write_pos += 8
}
read_pos_r += stride_add_r
read_pos_g += stride_add_g
read_pos_b += stride_add_b
}
}
i = &image.RGBA64{
Pix: rgba,
Stride: stride,
Rect: image.Rectangle{
Min: image.Point{
X: 0,
Y: 0,
},
Max: image.Point{
X: width,
Y: height,
},
},
}
} else {
stride = width * 4
rgba = make([]byte, height*stride)
stride_add_r := r.Stride - width
stride_add_g := g.Stride - width
stride_add_b := b.Stride - width
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
rgba[write_pos] = r.Plane[read_pos_r]
rgba[write_pos+1] = g.Plane[read_pos_g]
rgba[write_pos+2] = b.Plane[read_pos_b]
rgba[write_pos+3] = 0xff
read_pos_r++
read_pos_g++
read_pos_b++
write_pos += 4
}
read_pos_r += stride_add_r
read_pos_g += stride_add_g
read_pos_b += stride_add_b
}
i = &image.RGBA{
Pix: rgba,
Stride: stride,
Rect: image.Rectangle{
Min: image.Point{
X: 0,
Y: 0,
},
Max: image.Point{
X: width,
Y: height,
},
},
}
}
case ChromaInterleavedRGB:
rgb, err := img.GetPlane(ChannelInterleaved)
if err != nil {
return nil, err
}
width := img.GetWidth(ChannelInterleaved)
height := img.GetHeight(ChannelInterleaved)
rgba := make([]byte, width*height*4)
read_pos := 0
write_pos := 0
stride_add := rgb.Stride - width*3
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
rgba[write_pos] = rgb.Plane[read_pos]
rgba[write_pos+1] = rgb.Plane[read_pos+1]
rgba[write_pos+2] = rgb.Plane[read_pos+2]
rgba[write_pos+3] = 0xff
read_pos += 3
write_pos += 4
}
read_pos += stride_add
}
i = &image.RGBA{
Pix: rgba,
Stride: width * 4,
Rect: image.Rectangle{
Min: image.Point{
X: 0,
Y: 0,
},
Max: image.Point{
X: width,
Y: height,
},
},
}
case ChromaInterleavedRGBA:
rgba, err := img.GetPlane(ChannelInterleaved)
if err != nil {
return nil, err
}
i = &image.RGBA{
Pix: rgba.Plane,
Stride: rgba.Stride,
Rect: image.Rectangle{
Min: image.Point{
X: 0,
Y: 0,
},
Max: image.Point{
X: img.GetWidth(ChannelInterleaved),
Y: img.GetHeight(ChannelInterleaved),
},
},
}
case ChromaInterleavedRRGGBB_BE:
rgb, err := img.GetPlane(ChannelInterleaved)
if err != nil {
return nil, err
}
width := img.GetWidth(ChannelInterleaved)
height := img.GetHeight(ChannelInterleaved)
rgba := make([]byte, width*height*8)
read_pos := 0