Debian Codegraph @

go/heif/heif.go

raw
1 /*
2 * GO interface to libheif
3 *
4 * MIT License
5 *
6 * Copyright (c) 2018 Dirk Farin <[email protected]>
7 * Copyright (c) 2018 Joachim Bauch <[email protected]>
8 *
9 * Permission is hereby granted, free of charge, to any person obtaining a copy
10 * of this software and associated documentation files (the "Software"), to deal
11 * in the Software without restriction, including without limitation the rights
12 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 * copies of the Software, and to permit persons to whom the Software is
14 * furnished to do so, subject to the following conditions:
15 *
16 * The above copyright notice and this permission notice shall be included in all
17 * copies or substantial portions of the Software.
18 *
19 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25 * SOFTWARE.
26 */
27
28 package heif
29
30 /*
31 #cgo pkg-config: libheif
32 #include <stdlib.h>
33 #include <string.h> // We use 'memcpy'
34 #include <libheif/heif.h>
35 */
36 import "C"
37
38 import (
39 "fmt"
40 "image"
41 "image/color"
42 "io"
43 "io/ioutil"
44 "runtime"
45 "unsafe"
46 )
47
48 func GetVersion() string {
49 return C.GoString(C.heif_get_version())
50 }
51
52 type Compression C.enum_heif_compression_format
53
54 const (
55 CompressionUndefined = C.heif_compression_undefined
56 CompressionHEVC = C.heif_compression_HEVC
57 CompressionAV1 = C.heif_compression_AV1
58 CompressionAVC = C.heif_compression_AVC
59 CompressionJPEG = C.heif_compression_JPEG
60 CompressionJPEG2000 = C.heif_compression_JPEG2000
61 CompressionVVC = C.heif_compression_VVC
62 CompressionEVC = C.heif_compression_EVC
63 CompressionUncompressed = C.heif_compression_uncompressed
64 CompressionMask = C.heif_compression_mask
65 CompressionHTJ2K = C.heif_compression_HTJ2K
66 )
67
68 type Chroma C.enum_heif_chroma
69
70 const (
71 ChromaUndefined = C.heif_chroma_undefined
72 ChromaMonochrome = C.heif_chroma_monochrome
73 Chroma420 = C.heif_chroma_420
74 Chroma422 = C.heif_chroma_422
75 Chroma444 = C.heif_chroma_444
76 ChromaInterleavedRGB = C.heif_chroma_interleaved_RGB
77 ChromaInterleavedRGBA = C.heif_chroma_interleaved_RGBA
78 ChromaInterleavedRRGGBBAA_BE = C.heif_chroma_interleaved_RRGGBBAA_BE
79 ChromaInterleavedRRGGBBAA_LE = C.heif_chroma_interleaved_RRGGBBAA_LE
80 ChromaInterleavedRRGGBB_BE = C.heif_chroma_interleaved_RRGGBB_BE
81 ChromaInterleavedRRGGBB_LE = C.heif_chroma_interleaved_RRGGBB_LE
82
83 ChromaInterleaved24Bit = C.heif_chroma_interleaved_24bit
84 ChromaInterleaved32Bit = C.heif_chroma_interleaved_32bit
85 )
86
87 type ChromaDownsamplingAlgorithm C.enum_heif_chroma_downsampling_algorithm
88
89 const (
90 ChromaDownsamplingAverage = C.heif_chroma_downsampling_average
91 ChromaDownsamplingNearestNeighbor = C.heif_chroma_downsampling_nearest_neighbor
92 ChromaDownsamplingSharpYUV = C.heif_chroma_downsampling_sharp_yuv
93 )
94
95 type ChromaUpsamplingAlgorithm C.enum_heif_chroma_upsampling_algorithm
96
97 const (
98 ChromaUpsamplingNearestNeighbor = C.heif_chroma_upsampling_nearest_neighbor
99 ChromaUpsamplingBilinear = C.heif_chroma_upsampling_bilinear
100 )
101
102 type Colorspace C.enum_heif_colorspace
103
104 const (
105 ColorspaceUndefined = C.heif_colorspace_undefined
106 ColorspaceYCbCr = C.heif_colorspace_YCbCr
107 ColorspaceRGB = C.heif_colorspace_RGB
108 ColorspaceMonochrome = C.heif_colorspace_monochrome
109 ColorspaceNonvisual = C.heif_colorspace_nonvisual
110 )
111
112 type Channel C.enum_heif_channel
113
114 const (
115 ChannelY = C.heif_channel_Y
116 ChannelCb = C.heif_channel_Cb
117 ChannelCr = C.heif_channel_Cr
118 ChannelR = C.heif_channel_R
119 ChannelG = C.heif_channel_G
120 ChannelB = C.heif_channel_B
121 ChannelAlpha = C.heif_channel_Alpha
122 ChannelInterleaved = C.heif_channel_interleaved
123 ChannelFilterArray = C.heif_channel_filter_array
124 ChannelDepth = C.heif_channel_depth
125 ChannelDisparity = C.heif_channel_disparity
126 )
127
128 type ProgressStep C.enum_heif_progress_step
129
130 const (
131 ProgressStepTotal = C.heif_progress_step_total
132 ProgressStepLoadTile = C.heif_progress_step_load_tile
133 )
134
135 type LosslessMode int
136
137 const (
138 LosslessModeDisabled LosslessMode = iota
139 LosslessModeEnabled
140 )
141
142 type LoggingLevel int
143
144 const (
145 LoggingLevelNone LoggingLevel = iota
146 LoggingLevelBasic
147 LoggingLevelAdvanced
148 LoggingLevelFull
149 )
150
151 // --- HeifError
152
153 type ErrorCode C.enum_heif_error_code
154
155 const (
156 ErrorOK = C.heif_error_Ok
157
158 // Input file does not exist.
159 ErrorInputDoesNotExist = C.heif_error_Input_does_not_exist
160
161 // Error in input file. Corrupted or invalid content.
162 errorInvalidInput = C.heif_error_Invalid_input
163
164 // Input file type is not supported.
165 ErrorUnsupportedFiletype = C.heif_error_Unsupported_filetype
166
167 // Image requires an unsupported decoder feature.
168 ErrorUnsupportedFeature = C.heif_error_Unsupported_feature
169
170 // Library API has been used in an invalid way.
171 ErrorUsage = C.heif_error_Usage_error
172
173 // Could not allocate enough memory.
174 ErrorMemoryAllocation = C.heif_error_Memory_allocation_error
175
176 // The decoder plugin generated an error
177 ErrorDecoderPlugin = C.heif_error_Decoder_plugin_error
178
179 // The decoder plugin generated an error
180 ErrorEncoderPlugin = C.heif_error_Encoder_plugin_error
181
182 // Error during encoding or when writing to the output
183 ErrorEncoding = C.heif_error_Encoding_error
184
185 ErrorEndOfSequence = C.heif_error_End_of_sequence
186
187 // Application has asked for a color profile type that does not exist
188 ErrorColorProfileDoesNotExist = C.heif_error_Color_profile_does_not_exist
189
190 ErrorPluginLoadingError = C.heif_error_Plugin_loading_error
191
192 ErrorCanceled = C.heif_error_Canceled
193 )
194
195 type ErrorSubcode C.enum_heif_suberror_code
196
197 const (
198 // no further information available
199 SuberrorUnspecified = C.heif_suberror_Unspecified
200
201 // --- Invalid_input ---
202
203 // End of data reached unexpectedly.
204 SuberrorEndOfData = C.heif_suberror_End_of_data
205
206 // Size of box (defined in header) is wrong
207 SuberrorInvalidBoxSize = C.heif_suberror_Invalid_box_size
208
209 // Mandatory 'ftyp' box is missing
210 SuberrorNoFtypBox = C.heif_suberror_No_ftyp_box
211
212 SuberrorNoIdatBox = C.heif_suberror_No_idat_box
213
214 SuberrorNoMetaBox = C.heif_suberror_No_meta_box
215
216 SuberrorNoMoovBox = C.heif_suberror_No_moov_box
217
218 SuberrorNoHdlrBox = C.heif_suberror_No_hdlr_box
219
220 SuberrorNoHvcCBox = C.heif_suberror_No_hvcC_box
221
222 SuberrorNoPitmBox = C.heif_suberror_No_pitm_box
223
224 SuberrorNoIpcoBox = C.heif_suberror_No_ipco_box
225
226 SuberrorNoIpmaBox = C.heif_suberror_No_ipma_box
227
228 SuberrorNoIlocBox = C.heif_suberror_No_iloc_box
229
230 SuberrorNoIinfBox = C.heif_suberror_No_iinf_box
231
232 SuberrorNoIprpBox = C.heif_suberror_No_iprp_box
233
234 SuberrorNoIrefBox = C.heif_suberror_No_iref_box
235
236 SuberrorNoPictHandler = C.heif_suberror_No_pict_handler
237
238 // An item property referenced in the 'ipma' box is not existing in the 'ipco' container.
239 SuberrorIpmaBoxReferencesNonexistingProperty = C.heif_suberror_Ipma_box_references_nonexisting_property
240
241 // No properties have been assigned to an item.
242 SuberrorNoPropertiesAssignedToItem = C.heif_suberror_No_properties_assigned_to_item
243
244 // Image has no (compressed) data
245 SuberrorNoItemData = C.heif_suberror_No_item_data
246
247 // Invalid specification of image grid (tiled image)
248 SuberrorInvalidGridData = C.heif_suberror_Invalid_grid_data
249
250 // Tile-images in a grid image are missing
251 SuberrorMissingGridImages = C.heif_suberror_Missing_grid_images
252
253 SuberrorNoAV1CBox = C.heif_suberror_No_av1C_box
254
255 SuberrorNoAVCCBox = C.heif_suberror_No_avcC_box
256
257 SuberrorInvalidCleanAperture = C.heif_suberror_Invalid_clean_aperture
258
259 // Invalid specification of overlay image
260 SuberrorInvalidOverlayData = C.heif_suberror_Invalid_overlay_data
261
262 // Overlay image completely outside of visible canvas area
263 SuberrorOverlayImageOutsideOfCanvas = C.heif_suberror_Overlay_image_outside_of_canvas
264
265 SuberrorPluginIsNotLoaded = C.heif_suberror_Plugin_is_not_loaded
266
267 SuberrorPluginLoadingError = C.heif_suberror_Plugin_loading_error
268
269 SuberrorAuxiliaryImageTypeUnspecified = C.heif_suberror_Auxiliary_image_type_unspecified
270
271 SuberrorCannotReadPluginDirectory = C.heif_suberror_Cannot_read_plugin_directory
272
273 SuberrorNoMatchingDecoderInstalled = C.heif_suberror_No_matching_decoder_installed
274
275 SuberrorNoOrInvalidPrimaryItem = C.heif_suberror_No_or_invalid_primary_item
276
277 SuberrorNoInfeBox = C.heif_suberror_No_infe_box
278
279 SuberrorUnknownColorProfileType = C.heif_suberror_Unknown_color_profile_type
280
281 SuberrorWrongTileImageChromaFormat = C.heif_suberror_Wrong_tile_image_chroma_format
282
283 SuberrorInvalidFractionalNumber = C.heif_suberror_Invalid_fractional_number
284
285 SuberrorInvalidImageSize = C.heif_suberror_Invalid_image_size
286
287 SuberrorCameraIntrinsicMatrixUndefined = C.heif_suberror_Camera_intrinsic_matrix_undefined
288
289 SuberrorCameraExtrinsicMatrixUndefined = C.heif_suberror_Camera_extrinsic_matrix_undefined
290
291 SuberrorDecompressionInvalidData = C.heif_suberror_Decompression_invalid_data
292
293 // --- Memory_allocation_error ---
294
295 // A security limit preventing unreasonable memory allocations was exceeded by the input file.
296 // Please check whether the file is valid. If it is, contact us so that we could increase the
297 // security limits further.
298 SuberrorSecurityLimitExceeded = C.heif_suberror_Security_limit_exceeded
299
300 CompressionInitialisationError = C.heif_suberror_Compression_initialisation_error
301
302 // --- Usage_error ---
303
304 // An item ID was used that is not present in the file.
305 SuberrorNonexistingItemReferenced = C.heif_suberror_Nonexisting_item_referenced // also used for Invalid_input
306
307 // An API argument was given a NULL pointer, which is not allowed for that function.
308 SuberrorNullPointerArgument = C.heif_suberror_Null_pointer_argument
309
310 // Image channel referenced that does not exist in the image
311 SuberrorNonexistingImageChannelReferenced = C.heif_suberror_Nonexisting_image_channel_referenced
312
313 // The version of the passed plugin is not supported.
314 SuberrorUnsupportedPluginVersion = C.heif_suberror_Unsupported_plugin_version
315
316 // The version of the passed writer is not supported.
317 SuberrorUnsupportedWriterVersion = C.heif_suberror_Unsupported_writer_version
318
319 // The given (encoder) parameter name does not exist.
320 SuberrorUnsupportedParameter = C.heif_suberror_Unsupported_parameter
321
322 // The value for the given parameter is not in the valid range.
323 SuberrorInvalidParameterValue = C.heif_suberror_Invalid_parameter_value
324
325 SuberrorInvalidProperty = C.heif_suberror_Invalid_property
326
327 SuberrorItemReferenceCycle = C.heif_suberror_Item_reference_cycle
328
329 SuberrorInvalidPixiBox = C.heif_suberror_Invalid_pixi_box
330
331 SuberrorInvalidRegionData = C.heif_suberror_Invalid_region_data
332
333 SuberrorNoIspeProperty = C.heif_suberror_No_ispe_property
334
335 SuberrorWrongTileImagePixelDepth = C.heif_suberror_Wrong_tile_image_pixel_depth
336
337 SuberrorUnknownNCLXColorPrimaries = C.heif_suberror_Unknown_NCLX_color_primaries
338
339 SuberrorUnknownNCLXTransferCharacteristics = C.heif_suberror_Unknown_NCLX_transfer_characteristics
340
341 SuberrorUnknownNCLXMatrixCoefficients = C.heif_suberror_Unknown_NCLX_matrix_coefficients
342
343 SuberrorInvalidJ2KCodestream = C.heif_suberror_Invalid_J2K_codestream
344
345 SuberrorNoVcCBox = C.heif_suberror_No_vvcC_box
346
347 SuberrorNoIcbrBox = C.heif_suberror_No_icbr_box
348
349 SuberrorInvalidMiniBox = C.heif_suberror_Invalid_mini_box
350
351 // --- Unsupported_feature ---
352
353 // Image was coded with an unsupported compression method.
354 SuberrorUnsupportedCodec = C.heif_suberror_Unsupported_codec
355
356 // Image is specified in an unknown way, e.g. as tiled grid image (which is supported)
357 SuberrorUnsupportedImageType = C.heif_suberror_Unsupported_image_type
358
359 SuberrorUnsupportedDataVersion = C.heif_suberror_Unsupported_data_version
360
361 SuberrorUnsupportedGenericCompressionMethod = C.heif_suberror_Unsupported_generic_compression_method
362
363 SuberrorUnsupportedEssentialProperty = C.heif_suberror_Unsupported_essential_property
364
365 // The conversion of the source image to the requested chroma / colorspace is not supported.
366 SuberrorUnsupportedColorConversion = C.heif_suberror_Unsupported_color_conversion
367
368 SuberrorUnsupportedItemConstructionMethod = C.heif_suberror_Unsupported_item_construction_method
369
370 SuberrorUnsupportedHeaderCompressionMethod = C.heif_suberror_Unsupported_header_compression_method
371
372 SubErrorUnsupportedTrackType = C.heif_suberror_Unsupported_track_type
373
374 // --- Encoder_plugin_error ---
375
376 SuberrorUnsupportedBitDepth = C.heif_suberror_Unsupported_bit_depth
377
378 // --- Encoding_error ---
379
380 SuberrorCannotWriteOutputData = C.heif_suberror_Cannot_write_output_data
381
382 SuberrorEncoderInitialization = C.heif_suberror_Encoder_initialization
383
384 SuberrorEncoderEncoding = C.heif_suberror_Encoder_encoding
385
386 SuberrorEncoderCleanup = C.heif_suberror_Encoder_cleanup
387
388 SuberrorTooManyRegions = C.heif_suberror_Too_many_regions
389 )
390
391 type HeifError struct {
392 Code ErrorCode
393 Subcode ErrorSubcode
394 Message string
395 }
396
397 func (e *HeifError) Error() string {
398 return e.Message
399 }
400
401 func convertHeifError(cerror C.struct_heif_error) error {
402 if cerror.code == ErrorOK {
403 return nil
404 }
405
406 return &HeifError{
407 Code: ErrorCode(cerror.code),
408 Subcode: ErrorSubcode(cerror.subcode),
409 Message: C.GoString(cerror.message),
410 }
411 }
412
413 func convertItemIDs(ids []C.heif_item_id, count int) []int {
414 result := make([]int, count)
415 for i := 0; i < count; i++ {
416 result[i] = int(ids[i])
417 }
418 return result
419 }
420
421 // --- Context
422
423 type Context struct {
424 context *C.struct_heif_context
425 }
426
427 func NewContext() (*Context, error) {
428 ctx := &Context{
429 context: C.heif_context_alloc(),
430 }
431 if ctx.context == nil {
432 return nil, fmt.Errorf("Could not allocate context")
433 }
434
435 runtime.SetFinalizer(ctx, freeHeifContext)
436 return ctx, nil
437 }
438
439 func freeHeifContext(c *Context) {
440 C.heif_context_free(c.context)
441 c.context = nil
442 }
443
444 func (c *Context) ReadFromFile(filename string) error {
445 c_filename := C.CString(filename)
446 defer C.free(unsafe.Pointer(c_filename))
447
448 err := C.heif_context_read_from_file(c.context, c_filename, nil)
449 runtime.KeepAlive(c)
450 return convertHeifError(err)
451 }
452
453 func (c *Context) ReadFromMemory(data []byte) error {
454 // TODO: Use reader API internally.
455 err := C.heif_context_read_from_memory(c.context, unsafe.Pointer(&data[0]), C.size_t(len(data)), nil)
456 runtime.KeepAlive(c)
457 return convertHeifError(err)
458 }
459
460 type Encoder struct {
461 encoder *C.struct_heif_encoder
462 id string
463 name string
464 }
465
466 func (e *Encoder) ID() string {
467 return e.id
468 }
469
470 func (e *Encoder) Name() string {
471 return e.name
472 }
473
474 func (e *Encoder) SetQuality(q int) error {
475 err := C.heif_encoder_set_lossy_quality(e.encoder, C.int(q))
476 runtime.KeepAlive(e)
477 return convertHeifError(err)
478 }
479
480 func (e *Encoder) SetLossless(l LosslessMode) error {
481 err := C.heif_encoder_set_lossless(e.encoder, C.int(l))
482 runtime.KeepAlive(e)
483 return convertHeifError(err)
484 }
485
486 func (e *Encoder) SetLoggingLevel(l LoggingLevel) error {
487 err := C.heif_encoder_set_logging_level(e.encoder, C.int(l))
488 runtime.KeepAlive(e)
489 return convertHeifError(err)
490 }
491
492 func freeHeifEncoder(enc *Encoder) {
493 C.heif_encoder_release(enc.encoder)
494 enc.encoder = nil
495 }
496
497 func (c *Context) convertEncoderDescriptor(d *C.struct_heif_encoder_descriptor) (*Encoder, error) {
498 cid := C.heif_encoder_descriptor_get_id_name(d)
499 cname := C.heif_encoder_descriptor_get_name(d)
500 enc := &Encoder{
501 id: C.GoString(cid),
502 name: C.GoString(cname),
503 }
504 err := C.heif_context_get_encoder(c.context, d, &enc.encoder)
505 runtime.KeepAlive(c)
506 if err := convertHeifError(err); err != nil {
507 return nil, err
508 }
509 runtime.SetFinalizer(enc, freeHeifEncoder)
510 return enc, nil
511 }
512
513 func (c *Context) NewEncoder(compression Compression) (*Encoder, error) {
514 const max = 1
515 descriptors := make([]*C.struct_heif_encoder_descriptor, max)
516 num := int(C.heif_context_get_encoder_descriptors(c.context, uint32(compression), nil, &descriptors[0], C.int(max)))
517 runtime.KeepAlive(c)
518 if num == 0 {
519 return nil, fmt.Errorf("no encoder for compression %v", compression)
520 }
521 return c.convertEncoderDescriptor(descriptors[0])
522 }
523
524 func (c *Context) WriteToFile(filename string) error {
525 err := C.heif_context_write_to_file(c.context, C.CString(filename))
526 runtime.KeepAlive(c)
527 return convertHeifError(err)
528 }
529
530 func (c *Context) GetNumberOfTopLevelImages() int {
531 i := int(C.heif_context_get_number_of_top_level_images(c.context))
532 runtime.KeepAlive(c)
533 return i
534 }
535
536 func (c *Context) IsTopLevelImageID(ID int) bool {
537 ok := C.heif_context_is_top_level_image_ID(c.context, C.heif_item_id(ID)) != 0
538 runtime.KeepAlive(c)
539 return ok
540 }
541
542 func (c *Context) GetListOfTopLevelImageIDs() []int {
543 num := int(C.heif_context_get_number_of_top_level_images(c.context))
544 runtime.KeepAlive(c)
545 if num == 0 {
546 return []int{}
547 }
548
549 origIDs := make([]C.heif_item_id, num)
550 C.heif_context_get_list_of_top_level_image_IDs(c.context, &origIDs[0], C.int(num))
551 runtime.KeepAlive(c)
552 return convertItemIDs(origIDs, num)
553 }
554
555 func (c *Context) GetPrimaryImageID() (int, error) {
556 var id C.heif_item_id
557 err := C.heif_context_get_primary_image_ID(c.context, &id)
558 runtime.KeepAlive(c)
559 if err := convertHeifError(err); err != nil {
560 return 0, err
561 }
562 return int(id), nil
563 }
564
565 // --- ImageHandle
566
567 type ImageHandle struct {
568 handle *C.struct_heif_image_handle
569 }
570
571 func freeHeifImageHandle(c *ImageHandle) {
572 C.heif_image_handle_release(c.handle)
573 c.handle = nil
574 }
575
576 func (c *Context) GetPrimaryImageHandle() (*ImageHandle, error) {
577 var handle ImageHandle
578 err := C.heif_context_get_primary_image_handle(c.context, &handle.handle)
579 runtime.KeepAlive(c)
580 if err := convertHeifError(err); err != nil {
581 return nil, err
582 }
583 runtime.SetFinalizer(&handle, freeHeifImageHandle)
584 return &handle, convertHeifError(err)
585 }
586
587 func (c *Context) GetImageHandle(id int) (*ImageHandle, error) {
588 var handle ImageHandle
589 err := C.heif_context_get_image_handle(c.context, C.heif_item_id(id), &handle.handle)
590 runtime.KeepAlive(c)
591 if err := convertHeifError(err); err != nil {
592 return nil, err
593 }
594 runtime.SetFinalizer(&handle, freeHeifImageHandle)
595 return &handle, nil
596 }
597
598 func (h *ImageHandle) IsPrimaryImage() bool {
599 ok := C.heif_image_handle_is_primary_image(h.handle) != 0
600 runtime.KeepAlive(h)
601 return ok
602 }
603
604 func (h *ImageHandle) GetWidth() int {
605 i := int(C.heif_image_handle_get_width(h.handle))
606 runtime.KeepAlive(h)
607 return i
608 }
609
610 func (h *ImageHandle) GetHeight() int {
611 i := int(C.heif_image_handle_get_height(h.handle))
612 runtime.KeepAlive(h)
613 return i
614 }
615
616 func (h *ImageHandle) HasAlphaChannel() bool {
617 ok := C.heif_image_handle_has_alpha_channel(h.handle) != 0
618 runtime.KeepAlive(h)
619 return ok
620 }
621
622 func (h *ImageHandle) HasDepthImage() bool {
623 ok := C.heif_image_handle_has_depth_image(h.handle) != 0
624 runtime.KeepAlive(h)
625 return ok
626 }
627
628 func (h *ImageHandle) GetNumberOfDepthImages() int {
629 i := int(C.heif_image_handle_get_number_of_depth_images(h.handle))
630 runtime.KeepAlive(h)
631 return i
632 }
633
634 func (h *ImageHandle) GetListOfDepthImageIDs() []int {
635 num := int(C.heif_image_handle_get_number_of_depth_images(h.handle))
636 runtime.KeepAlive(h)
637 if num == 0 {
638 return []int{}
639 }
640
641 origIDs := make([]C.heif_item_id, num)
642 C.heif_image_handle_get_list_of_depth_image_IDs(h.handle, &origIDs[0], C.int(num))
643 runtime.KeepAlive(h)
644 return convertItemIDs(origIDs, num)
645 }
646
647 func (h *ImageHandle) GetDepthImageHandle(depth_image_id int) (*ImageHandle, error) {
648 var handle ImageHandle
649 err := C.heif_image_handle_get_depth_image_handle(h.handle, C.heif_item_id(depth_image_id), &handle.handle)
650 runtime.KeepAlive(h)
651 if err := convertHeifError(err); err != nil {
652 return nil, err
653 }
654
655 runtime.SetFinalizer(&handle, freeHeifImageHandle)
656 return &handle, nil
657 }
658
659 func (h *ImageHandle) GetNumberOfThumbnails() int {
660 i := int(C.heif_image_handle_get_number_of_thumbnails(h.handle))
661 runtime.KeepAlive(h)
662 return i
663 }
664
665 func (h *ImageHandle) GetListOfThumbnailIDs() []int {
666 num := int(C.heif_image_handle_get_number_of_thumbnails(h.handle))
667 runtime.KeepAlive(h)
668 if num == 0 {
669 return []int{}
670 }
671
672 origIDs := make([]C.heif_item_id, num)
673 C.heif_image_handle_get_list_of_thumbnail_IDs(h.handle, &origIDs[0], C.int(num))
674 runtime.KeepAlive(h)
675 return convertItemIDs(origIDs, num)
676 }
677
678 func (h *ImageHandle) GetThumbnail(thumbnail_id int) (*ImageHandle, error) {
679 var handle ImageHandle
680 err := C.heif_image_handle_get_thumbnail(h.handle, C.heif_item_id(thumbnail_id), &handle.handle)
681 runtime.KeepAlive(h)
682 runtime.SetFinalizer(&handle, freeHeifImageHandle)
683 return &handle, convertHeifError(err)
684 }
685
686 // TODO: EXIF metadata
687
688 // --- Image
689
690 type DecodingOptions struct {
691 options *C.struct_heif_decoding_options
692 }
693
694 func NewDecodingOptions() (*DecodingOptions, error) {
695 options := &DecodingOptions{
696 options: C.heif_decoding_options_alloc(),
697 }
698 if options.options == nil {
699 return nil, fmt.Errorf("Could not allocate decoding options")
700 }
701
702 runtime.SetFinalizer(options, freeHeifDecodingOptions)
703 return options, nil
704 }
705
706 func freeHeifDecodingOptions(options *DecodingOptions) {
707 C.heif_decoding_options_free(options.options)
708 options.options = nil
709 }
710
711 type Image struct {
712 image *C.struct_heif_image
713 }
714
715 func NewImage(width, height int, colorspace Colorspace, chroma Chroma) (*Image, error) {
716 var image Image
717 err := C.heif_image_create(C.int(width), C.int(height), uint32(colorspace), uint32(chroma), &image.image)
718 if err := convertHeifError(err); err != nil {
719 return nil, err
720 }
721 runtime.SetFinalizer(&image, freeHeifImage)
722 return &image, nil
723 }
724
725 func freeHeifImage(image *Image) {
726 C.heif_image_release(image.image)
727 image.image = nil
728 }
729
730 func (h *ImageHandle) DecodeImage(colorspace Colorspace, chroma Chroma, options *DecodingOptions) (*Image, error) {
731 var image Image
732
733 var opt *C.struct_heif_decoding_options
734 if options != nil {
735 opt = options.options
736 }
737
738 err := C.heif_decode_image(h.handle, &image.image, uint32(colorspace), uint32(chroma), opt)
739 runtime.KeepAlive(h)
740 if err := convertHeifError(err); err != nil {
741 return nil, err
742 }
743
744 runtime.SetFinalizer(&image, freeHeifImage)
745 return &image, nil
746 }
747
748 func (img *Image) GetColorspace() Colorspace {
749 cs := Colorspace(C.heif_image_get_colorspace(img.image))
750 runtime.KeepAlive(img)
751 return cs
752 }
753
754 func (img *Image) GetChromaFormat() Chroma {
755 c := Chroma(C.heif_image_get_chroma_format(img.image))
756 runtime.KeepAlive(img)
757 return c
758 }
759
760 func (img *Image) GetWidth(channel Channel) int {
761 i := int(C.heif_image_get_width(img.image, uint32(channel)))
762 runtime.KeepAlive(img)
763 return i
764 }
765
766 func (img *Image) GetHeight(channel Channel) int {
767 i := int(C.heif_image_get_height(img.image, uint32(channel)))
768 runtime.KeepAlive(img)
769 return i
770 }
771
772 func (img *Image) GetBitsPerPixel(channel Channel) int {
773 i := int(C.heif_image_get_bits_per_pixel(img.image, uint32(channel)))
774 runtime.KeepAlive(img)
775 return i
776 }
777
778 func (img *Image) GetBitsPerPixelRange(channel Channel) int {
779 i := int(C.heif_image_get_bits_per_pixel_range(img.image, uint32(channel)))
780 runtime.KeepAlive(img)
781 return i
782 }
783
784 func (img *Image) GetImage() (image.Image, error) {
785 var i image.Image
786 cf := img.GetChromaFormat()
787 switch cs := img.GetColorspace(); cs {
788 case ColorspaceYCbCr:
789 var subsample image.YCbCrSubsampleRatio
790 switch cf {
791 case Chroma420:
792 subsample = image.YCbCrSubsampleRatio420
793 case Chroma422:
794 subsample = image.YCbCrSubsampleRatio422
795 case Chroma444:
796 subsample = image.YCbCrSubsampleRatio444
797 default:
798 return nil, fmt.Errorf("Unsupported YCbCr chroma format: %v", cf)
799 }
800 y, err := img.GetPlane(ChannelY)
801 if err != nil {
802 return nil, err
803 }
804 cb, err := img.GetPlane(ChannelCb)
805 if err != nil {
806 return nil, err
807 }
808 cr, err := img.GetPlane(ChannelCr)
809 if err != nil {
810 return nil, err
811 }
812 i = &image.YCbCr{
813 Y: y.Plane,
814 Cb: cb.Plane,
815 Cr: cr.Plane,
816 YStride: y.Stride,
817 CStride: cb.Stride,
818 SubsampleRatio: subsample,
819 Rect: image.Rectangle{
820 Min: image.Point{
821 X: 0,
822 Y: 0,
823 },
824 Max: image.Point{
825 X: img.GetWidth(ChannelY),
826 Y: img.GetHeight(ChannelY),
827 },
828 },
829 }
830 case ColorspaceRGB:
831 switch cf {
832 case Chroma444:
833 r, err := img.GetPlane(ChannelR)
834 if err != nil {
835 return nil, err
836 }
837 g, err := img.GetPlane(ChannelG)
838 if err != nil {
839 return nil, err
840 }
841 b, err := img.GetPlane(ChannelB)
842 if err != nil {
843 return nil, err
844 }
845 width := img.GetWidth(ChannelR)
846 height := img.GetHeight(ChannelR)
847 read_pos_r := 0
848 read_pos_g := 0
849 read_pos_b := 0
850 write_pos := 0
851 var rgba []byte
852 var stride int
853 if bpp := img.GetBitsPerPixelRange(ChannelR); bpp > 8 {
854 // NOTE: We only support the same bits per pixel on all components.
855 stride = width * 8
856 rgba = make([]byte, height*stride)
857 stride_add_r := r.Stride - width*2
858 stride_add_g := g.Stride - width*2
859 stride_add_b := b.Stride - width*2
860 if bpp == 16 {
861 for y := 0; y < height; y++ {
862 for x := 0; x < width; x++ {
863 rgba[write_pos] = r.Plane[read_pos_r]
864 rgba[write_pos+1] = r.Plane[read_pos_r+1]
865 rgba[write_pos+2] = g.Plane[read_pos_g]
866 rgba[write_pos+3] = g.Plane[read_pos_g+1]
867 rgba[write_pos+4] = b.Plane[read_pos_b]
868 rgba[write_pos+5] = b.Plane[read_pos_b+1]
869 rgba[write_pos+6] = 0xff
870 rgba[write_pos+7] = 0xff
871 read_pos_r += 2
872 read_pos_g += 2
873 read_pos_b += 2
874 write_pos += 8
875 }
876 read_pos_r += stride_add_r
877 read_pos_g += stride_add_g
878 read_pos_b += stride_add_b
879 }
880 } else {
881 for y := 0; y < height; y++ {
882 for x := 0; x < width; x++ {
883 r_value := (int16(r.Plane[read_pos_r+1]) << 8) | int16(r.Plane[read_pos_r])
884 r_value = (r_value << (16 - uint(bpp))) | (r_value >> (2*uint(bpp) - 16))
885 rgba[write_pos] = byte(r_value >> 8)
886 rgba[write_pos+1] = byte(r_value & 0xff)
887 g_value := (int16(g.Plane[read_pos_g+1]) << 8) | int16(g.Plane[read_pos_g])
888 g_value = (g_value << (16 - uint(bpp))) | (g_value >> (2*uint(bpp) - 16))
889 rgba[write_pos+2] = byte(g_value >> 8)
890 rgba[write_pos+3] = byte(g_value & 0xff)
891 b_value := (int16(b.Plane[read_pos_b+1]) << 8) | int16(b.Plane[read_pos_b])
892 b_value = (b_value << (16 - uint(bpp))) | (b_value >> (2*uint(bpp) - 16))
893 rgba[write_pos+4] = byte(b_value >> 8)
894 rgba[write_pos+5] = byte(b_value & 0xff)
895 rgba[write_pos+6] = 0xff
896 rgba[write_pos+7] = 0xff
897 read_pos_r += 2
898 read_pos_g += 2
899 read_pos_b += 2
900 write_pos += 8
901 }
902 read_pos_r += stride_add_r
903 read_pos_g += stride_add_g
904 read_pos_b += stride_add_b
905 }
906 }
907
908 i = &image.RGBA64{
909 Pix: rgba,
910 Stride: stride,
911 Rect: image.Rectangle{
912 Min: image.Point{
913 X: 0,
914 Y: 0,
915 },
916 Max: image.Point{
917 X: width,
918 Y: height,
919 },
920 },
921 }
922 } else {
923 stride = width * 4
924 rgba = make([]byte, height*stride)
925 stride_add_r := r.Stride - width
926 stride_add_g := g.Stride - width
927 stride_add_b := b.Stride - width
928 for y := 0; y < height; y++ {
929 for x := 0; x < width; x++ {
930 rgba[write_pos] = r.Plane[read_pos_r]
931 rgba[write_pos+1] = g.Plane[read_pos_g]
932 rgba[write_pos+2] = b.Plane[read_pos_b]
933 rgba[write_pos+3] = 0xff
934 read_pos_r++
935 read_pos_g++
936 read_pos_b++
937 write_pos += 4
938 }
939 read_pos_r += stride_add_r
940 read_pos_g += stride_add_g
941 read_pos_b += stride_add_b
942 }
943
944 i = &image.RGBA{
945 Pix: rgba,
946 Stride: stride,
947 Rect: image.Rectangle{
948 Min: image.Point{
949 X: 0,
950 Y: 0,
951 },
952 Max: image.Point{
953 X: width,
954 Y: height,
955 },
956 },
957 }
958 }
959 case ChromaInterleavedRGB:
960 rgb, err := img.GetPlane(ChannelInterleaved)
961 if err != nil {
962 return nil, err
963 }
964 width := img.GetWidth(ChannelInterleaved)
965 height := img.GetHeight(ChannelInterleaved)
966 rgba := make([]byte, width*height*4)
967 read_pos := 0
968 write_pos := 0
969 stride_add := rgb.Stride - width*3
970 for y := 0; y < height; y++ {
971 for x := 0; x < width; x++ {
972 rgba[write_pos] = rgb.Plane[read_pos]
973 rgba[write_pos+1] = rgb.Plane[read_pos+1]
974 rgba[write_pos+2] = rgb.Plane[read_pos+2]
975 rgba[write_pos+3] = 0xff
976 read_pos += 3
977 write_pos += 4
978 }
979 read_pos += stride_add
980 }
981 i = &image.RGBA{
982 Pix: rgba,
983 Stride: width * 4,
984 Rect: image.Rectangle{
985 Min: image.Point{
986 X: 0,
987 Y: 0,
988 },
989 Max: image.Point{
990 X: width,
991 Y: height,
992 },
993 },
994 }
995 case ChromaInterleavedRGBA:
996 rgba, err := img.GetPlane(ChannelInterleaved)
997 if err != nil {
998 return nil, err
999 }
1000 i = &image.RGBA{
1001 Pix: rgba.Plane,
1002 Stride: rgba.Stride,
1003 Rect: image.Rectangle{
1004 Min: image.Point{
1005 X: 0,
1006 Y: 0,
1007 },
1008 Max: image.Point{
1009 X: img.GetWidth(ChannelInterleaved),
1010 Y: img.GetHeight(ChannelInterleaved),
1011 },
1012 },
1013 }
1014 case ChromaInterleavedRRGGBB_BE:
1015 rgb, err := img.GetPlane(ChannelInterleaved)
1016 if err != nil {
1017 return nil, err
1018 }
1019 width := img.GetWidth(ChannelInterleaved)
1020 height := img.GetHeight(ChannelInterleaved)
1021 rgba := make([]byte, width*height*8)
1022 read_pos := 0
1023 write_pos := 0
1024 stride_add := rgb.Stride - width*6
1025 if bpp := img.GetBitsPerPixelRange(ChannelInterleaved); bpp != 16 {
1026 for y := 0; y < height; y++ {
1027 for x := 0; x < width; x++ {
1028 r_value := (int16(rgb.Plane[read_pos]) << 8) | int16(rgb.Plane[read_pos+1])
1029 r_value = (r_value << (16 - uint(bpp))) | (r_value >> (2*uint(bpp) - 16))
1030 rgba[write_pos] = byte(r_value >> 8)
1031 rgba[write_pos+1] = byte(r_value & 0xff)
1032 g_value := (int16(rgb.Plane[read_pos+2]) << 8) | int16(rgb.Plane[read_pos+3])
1033 g_value = (g_value << (16 - uint(bpp))) | (g_value >> (2*uint(bpp) - 16))
1034 rgba[write_pos+2] = byte(g_value >> 8)
1035 rgba[write_pos+3] = byte(g_value & 0xff)
1036 b_value := (int16(rgb.Plane[read_pos+4]) << 8) | int16(rgb.Plane[read_pos+5])
1037 b_value = (b_value << (16 - uint(bpp))) | (b_value >> (2*uint(bpp) - 16))
1038 rgba[write_pos+4] = byte(b_value >> 8)
1039 rgba[write_pos+5] = byte(b_value & 0xff)
1040 rgba[write_pos+6] = 0xff
1041 rgba[write_pos+7] = 0xff
1042 read_pos += 6
1043 write_pos += 8
1044 }
1045 read_pos += stride_add
1046 }
1047 } else {
1048 for y := 0; y < height; y++ {
1049 for x := 0; x < width; x++ {
1050 rgba[write_pos] = rgb.Plane[read_pos]
1051 rgba[write_pos+1] = rgb.Plane[read_pos+1]
1052 rgba[write_pos+2] = rgb.Plane[read_pos+2]
1053 rgba[write_pos+3] = rgb.Plane[read_pos+3]
1054 rgba[write_pos+4] = rgb.Plane[read_pos+4]
1055 rgba[write_pos+5] = rgb.Plane[read_pos+5]
1056 rgba[write_pos+6] = 0xff
1057 rgba[write_pos+7] = 0xff
1058 read_pos += 6
1059 write_pos += 8
1060 }
1061 read_pos += stride_add
1062 }
1063 }
1064 i = &image.RGBA64{
1065 Pix: rgba,
1066 Stride: width * 4,
1067 Rect: image.Rectangle{
1068 Min: image.Point{
1069 X: 0,
1070 Y: 0,
1071 },
1072 Max: image.Point{
1073 X: width,
1074 Y: height,
1075 },
1076 },
1077 }
1078 case ChromaInterleavedRRGGBBAA_BE:
1079 rgba, err := img.GetPlane(ChannelInterleaved)
1080 if err != nil {
1081 return nil, err
1082 }
1083 width := img.GetWidth(ChannelInterleaved)
1084 height := img.GetHeight(ChannelInterleaved)
1085 var plane []byte
1086 if bpp := img.GetBitsPerPixelRange(ChannelInterleaved); bpp != 16 {
1087 read_pos := 0
1088 write_pos := 0
1089 stride_add := rgba.Stride - width*8
1090 plane = make([]byte, width*height*8)
1091 for y := 0; y < height; y++ {
1092 for x := 0; x < width; x++ {
1093 r_value := (int16(rgba.Plane[read_pos]) << 8) | int16(rgba.Plane[read_pos+1])
1094 r_value = (r_value << (16 - uint(bpp))) | (r_value >> (2*uint(bpp) - 16))
1095 plane[write_pos] = byte(r_value >> 8)
1096 plane[write_pos+1] = byte(r_value & 0xff)
1097 g_value := (int16(rgba.Plane[read_pos+2]) << 8) | int16(rgba.Plane[read_pos+3])
1098 g_value = (g_value << (16 - uint(bpp))) | (g_value >> (2*uint(bpp) - 16))
1099 plane[write_pos+2] = byte(g_value >> 8)
1100 plane[write_pos+3] = byte(g_value & 0xff)
1101 b_value := (int16(rgba.Plane[read_pos+4]) << 8) | int16(rgba.Plane[read_pos+5])
1102 b_value = (b_value << (16 - uint(bpp))) | (b_value >> (2*uint(bpp) - 16))
1103 plane[write_pos+4] = byte(b_value >> 8)
1104 plane[write_pos+5] = byte(b_value & 0xff)
1105 a_value := (int16(rgba.Plane[read_pos+6]) << 8) | int16(rgba.Plane[read_pos+7])
1106 a_value = (a_value << (16 - uint(bpp))) | (a_value >> (2*uint(bpp) - 16))
1107 plane[write_pos+6] = byte(a_value >> 8)
1108 plane[write_pos+7] = byte(a_value & 0xff)
1109 read_pos += 8
1110 write_pos += 8
1111 }
1112 read_pos += stride_add
1113 }
1114 } else {
1115 plane = rgba.Plane
1116 }
1117 i = &image.RGBA64{
1118 Pix: plane,
1119 Stride: rgba.Stride,
1120 Rect: image.Rectangle{
1121 Min: image.Point{
1122 X: 0,
1123 Y: 0,
1124 },
1125 Max: image.Point{
1126 X: width,
1127 Y: height,
1128 },
1129 },
1130 }
1131 default:
1132 return nil, fmt.Errorf("Unsupported RGB chroma format: %v", cf)
1133 }
1134 default:
1135 return nil, fmt.Errorf("Unsupported colorspace: %v", cs)
1136 }
1137
1138 return i, nil
1139 }
1140
1141 type ImageAccess struct {
1142 Plane []byte
1143 planePtr unsafe.Pointer
1144 Stride int
1145 height int
1146
1147 image *Image // need this reference to make sure the image is not GC'ed while we access it
1148 }
1149
1150 func (i *ImageAccess) setData(data []byte, stride int) {
1151 // Handle common case directly
1152 if stride == i.Stride {
1153 dstP := uintptr(i.planePtr)
1154 srcP := uintptr(unsafe.Pointer(&data[0]))
1155 C.memcpy(unsafe.Pointer(dstP), unsafe.Pointer(srcP), C.size_t(i.height*stride))
1156 } else {
1157 for y := 0; y < i.height; y++ {
1158 dstP := uintptr(i.planePtr) + uintptr(y*i.Stride)
1159 srcP := uintptr(unsafe.Pointer(&data[0])) + uintptr(y*stride)
1160 C.memcpy(unsafe.Pointer(dstP), unsafe.Pointer(srcP), C.size_t(stride))
1161 }
1162 }
1163 i.Plane = C.GoBytes(i.planePtr, C.int(i.height*i.Stride))
1164 }
1165
1166 func (img *Image) GetPlane(channel Channel) (*ImageAccess, error) {
1167 height := C.heif_image_get_height(img.image, uint32(channel))
1168 runtime.KeepAlive(img)
1169 if height == -1 {
1170 return nil, fmt.Errorf("No such channel %v", channel)
1171 }
1172
1173 var stride C.int
1174 plane := C.heif_image_get_plane(img.image, uint32(channel), &stride)
1175 runtime.KeepAlive(img)
1176 if plane == nil {
1177 return nil, fmt.Errorf("No such channel %v", channel)
1178 }
1179
1180 ptr := unsafe.Pointer(plane)
1181 size := stride * height
1182 access := &ImageAccess{
1183 Plane: C.GoBytes(ptr, size),
1184 planePtr: ptr,
1185 Stride: int(stride),
1186 height: int(height),
1187 image: img,
1188 }
1189 return access, nil
1190 }
1191
1192 func (img *Image) NewPlane(channel Channel, width, height, depth int) (*ImageAccess, error) {
1193 err := C.heif_image_add_plane(img.image, uint32(channel), C.int(width), C.int(height), C.int(depth))
1194 runtime.KeepAlive(img)
1195 if err := convertHeifError(err); err != nil {
1196 return nil, err
1197 }
1198 return img.GetPlane(channel)
1199 }
1200
1201 func (img *Image) ScaleImage(width int, height int) (*Image, error) {
1202 var scaled_image Image
1203 err := C.heif_image_scale_image(img.image, &scaled_image.image, C.int(width), C.int(height), nil)
1204 runtime.KeepAlive(img)
1205 if err := convertHeifError(err); err != nil {
1206 return nil, err
1207 }
1208
1209 runtime.SetFinalizer(&scaled_image, freeHeifImage)
1210 return &scaled_image, nil
1211 }
1212
1213 // --- High-level encoding API.
1214
1215 type EncodingOptions struct {
1216 options *C.struct_heif_encoding_options
1217 }
1218
1219 func NewEncodingOptions() (*EncodingOptions, error) {
1220 options := &EncodingOptions{
1221 options: C.heif_encoding_options_alloc(),
1222 }
1223 if options.options == nil {
1224 return nil, fmt.Errorf("Could not allocate encoding options")
1225 }
1226
1227 runtime.SetFinalizer(options, freeHeifEncodingOptions)
1228 return options, nil
1229 }
1230
1231 func freeHeifEncodingOptions(options *EncodingOptions) {
1232 C.heif_encoding_options_free(options.options)
1233 options.options = nil
1234 }
1235
1236 func imageFromRGBA(i *image.RGBA) (*Image, error) {
1237 min := i.Bounds().Min
1238 max := i.Bounds().Max
1239 w := max.X - min.X
1240 h := max.Y - min.Y
1241
1242 out, err := NewImage(w, h, ColorspaceRGB, ChromaInterleavedRGBA)
1243 if err != nil {
1244 return nil, fmt.Errorf("failed to create image: %v", err)
1245 }
1246
1247 p, err := out.NewPlane(ChannelInterleaved, w, h, 8)
1248 if err != nil {
1249 return nil, fmt.Errorf("failed to add plane: %v", err)
1250 }
1251 p.setData([]byte(i.Pix), w*4)
1252
1253 return out, nil
1254 }
1255
1256 func imageFromRGBA64(i *image.RGBA64) (*Image, error) {
1257 min := i.Bounds().Min
1258 max := i.Bounds().Max
1259 w := max.X - min.X
1260 h := max.Y - min.Y
1261
1262 out, err := NewImage(w, h, ColorspaceRGB, ChromaInterleavedRRGGBBAA_BE)
1263 if err != nil {
1264 return nil, fmt.Errorf("failed to create image: %v", err)
1265 }
1266
1267 p, err := out.NewPlane(ChannelInterleaved, w, h, 10)
1268 if err != nil {
1269 return nil, fmt.Errorf("failed to add plane: %v", err)
1270 }
1271
1272 pix := make([]byte, w*h*8)
1273 read_pos := 0
1274 write_pos := 0
1275 for y := 0; y < h; y++ {
1276 for x := 0; x < w; x++ {
1277 r := (uint16(i.Pix[read_pos]) << 8) | uint16(i.Pix[read_pos+1])
1278 r = r >> 6
1279 pix[write_pos] = byte(r >> 8)
1280 pix[write_pos+1] = byte(r & 0xff)
1281 read_pos += 2
1282 g := (uint16(i.Pix[read_pos]) << 8) | uint16(i.Pix[read_pos+1])
1283 g = g >> 6
1284 pix[write_pos+2] = byte(g >> 8)
1285 pix[write_pos+3] = byte(g & 0xff)
1286 read_pos += 2
1287 b := (uint16(i.Pix[read_pos]) << 8) | uint16(i.Pix[read_pos+1])
1288 b = b >> 6
1289 pix[write_pos+4] = byte(b >> 8)
1290 pix[write_pos+5] = byte(b & 0xff)
1291 read_pos += 2
1292 a := (uint16(i.Pix[read_pos]) << 8) | uint16(i.Pix[read_pos+1])
1293 a = a >> 6
1294 pix[write_pos+6] = byte(a >> 8)
1295 pix[write_pos+7] = byte(a & 0xff)
1296 pix[write_pos+6] = byte(a >> 8)
1297 pix[write_pos+7] = byte(a & 0xff)
1298 read_pos += 2
1299 write_pos += 8
1300 }
1301 }
1302 p.setData(pix, w*8)
1303
1304 return out, nil
1305 }
1306
1307 func imageFromGray(i *image.Gray) (*Image, error) {
1308 min := i.Bounds().Min
1309 max := i.Bounds().Max
1310 w := max.X - min.X
1311 h := max.Y - min.Y
1312
1313 out, err := NewImage(w, h, ColorspaceYCbCr, ChromaMonochrome)
1314 if err != nil {
1315 return nil, fmt.Errorf("failed to create image: %v", err)
1316 }
1317
1318 const depth = 8
1319 pY, err := out.NewPlane(ChannelY, w, h, depth)
1320 if err != nil {
1321 return nil, fmt.Errorf("failed to add Y plane: %v", err)
1322 }
1323 pY.setData([]byte(i.Pix), i.Stride)
1324
1325 return out, nil
1326 }
1327
1328 func imageFromYCbCr(i *image.YCbCr) (*Image, error) {
1329 min := i.Bounds().Min
1330 max := i.Bounds().Max
1331 w := max.X - min.X
1332 h := max.Y - min.Y
1333
1334 var cm Chroma
1335 switch sr := i.SubsampleRatio; sr {
1336 case image.YCbCrSubsampleRatio420:
1337 cm = Chroma420
1338 case image.YCbCrSubsampleRatio422:
1339 cm = Chroma422
1340 case image.YCbCrSubsampleRatio444:
1341 cm = Chroma444
1342 default:
1343 return nil, fmt.Errorf("unsupported subsample ratio: %s", sr.String())
1344 }
1345
1346 out, err := NewImage(w, h, ColorspaceYCbCr, cm)
1347 if err != nil {
1348 return nil, fmt.Errorf("failed to create image: %v", err)
1349 }
1350
1351 const depth = 8
1352 pY, err := out.NewPlane(ChannelY, w, h, depth)
1353 if err != nil {
1354 return nil, fmt.Errorf("failed to add Y plane: %v", err)
1355 }
1356 pY.setData([]byte(i.Y), i.YStride)
1357
1358 // TODO: Might need to be updated for other SubsampleRatio values.
1359 var cw, ch int
1360 switch cm {
1361 case Chroma420:
1362 cw, ch = (w+1)/2, (h+1)/2
1363 case Chroma444:
1364 cw, ch = w, h
1365 case Chroma422:
1366 cw, ch = (w+1)/2, h
1367 default:
1368 return nil, fmt.Errorf("cm not support: %v", cm)
1369 }
1370 pCb, err := out.NewPlane(ChannelCb, cw, ch, depth)
1371 if err != nil {
1372 return nil, fmt.Errorf("failed to add Cb plane: %v", err)
1373 }
1374 pCb.setData([]byte(i.Cb), i.CStride)
1375 pCr, err := out.NewPlane(ChannelCr, cw, ch, depth)
1376 if err != nil {
1377 return nil, fmt.Errorf("failed to add Cr plane: %v", err)
1378 }
1379 pCr.setData([]byte(i.Cr), i.CStride)
1380
1381 return out, nil
1382 }
1383
1384 func EncodeFromImage(img image.Image, compression Compression, quality int, lossless LosslessMode, logging LoggingLevel) (*Context, error) {
1385 var out *Image
1386
1387 switch i := img.(type) {
1388 default:
1389 return nil, fmt.Errorf("unsupported image type: %T", i)
1390 case *image.RGBA:
1391 tmp, err := imageFromRGBA(i)
1392 if err != nil {
1393 return nil, fmt.Errorf("failed to create image: %v", err)
1394 }
1395 out = tmp
1396 case *image.RGBA64:
1397 tmp, err := imageFromRGBA64(i)
1398 if err != nil {
1399 return nil, fmt.Errorf("failed to create image: %v", err)
1400 }
1401 out = tmp
1402 case *image.Gray:
1403 tmp, err := imageFromGray(i)
1404 if err != nil {
1405 return nil, fmt.Errorf("failed to create image: %v", err)
1406 }
1407 out = tmp
1408 case *image.YCbCr:
1409 tmp, err := imageFromYCbCr(i)
1410 if err != nil {
1411 return nil, fmt.Errorf("failed to create image: %v", err)
1412 }
1413 out = tmp
1414 }
1415
1416 ctx, err := NewContext()
1417 if err != nil {
1418 return nil, fmt.Errorf("failed to create HEIF context: %v", err)
1419 }
1420
1421 enc, err := ctx.NewEncoder(compression)
1422 if err != nil {
1423 return nil, fmt.Errorf("failed to create encoder: %v", err)
1424 }
1425
1426 if err := enc.SetQuality(quality); err != nil {
1427 return nil, fmt.Errorf("failed to set quality: %v", err)
1428 }
1429 if err := enc.SetLossless(lossless); err != nil {
1430 return nil, fmt.Errorf("failed to set lossless mode: %v", err)
1431 }
1432 if err := enc.SetLoggingLevel(logging); err != nil {
1433 return nil, fmt.Errorf("failed to set logging level: %v", err)
1434 }
1435
1436 encOpts, err := NewEncodingOptions()
1437 if err != nil {
1438 return nil, fmt.Errorf("failed to get encoding options: %v", err)
1439 }
1440
1441 var handle ImageHandle
1442 err2 := C.heif_context_encode_image(ctx.context, out.image, enc.encoder, encOpts.options, &handle.handle)
1443 runtime.KeepAlive(ctx)
1444 runtime.KeepAlive(out)
1445 runtime.KeepAlive(enc)
1446 runtime.KeepAlive(encOpts)
1447 if err := convertHeifError(err2); err != nil {
1448 return nil, fmt.Errorf("failed to encode image: %v", err)
1449 }
1450 runtime.SetFinalizer(&handle, freeHeifImageHandle)
1451
1452 return ctx, nil
1453 }
1454
1455 // --- High-level decoding API, always decodes primary image (if present).
1456
1457 func decodePrimaryImageFromReader(r io.Reader) (*ImageHandle, error) {
1458 ctx, err := NewContext()
1459 if err != nil {
1460 return nil, err
1461 }
1462
1463 data, err := ioutil.ReadAll(r)
1464 if err != nil {
1465 return nil, err
1466 }
1467
1468 if err := ctx.ReadFromMemory(data); err != nil {
1469 return nil, err
1470 }
1471
1472 handle, err := ctx.GetPrimaryImageHandle()
1473 if err != nil {
1474 return nil, err
1475 }
1476
1477 return handle, nil
1478 }
1479
1480 func decodeImage(r io.Reader) (image.Image, error) {
1481 handle, err := decodePrimaryImageFromReader(r)
1482 if err != nil {
1483 return nil, err
1484 }
1485
1486 img, err := handle.DecodeImage(ColorspaceUndefined, ChromaUndefined, nil)
1487 if err != nil {
1488 return nil, err
1489 }
1490
1491 return img.GetImage()
1492 }
1493
1494 func decodeConfig(r io.Reader) (image.Config, error) {
1495 var config image.Config
1496 handle, err := decodePrimaryImageFromReader(r)
1497 if err != nil {
1498 return config, err
1499 }
1500
1501 config = image.Config{
1502 ColorModel: color.YCbCrModel,
1503 Width: handle.GetWidth(),
1504 Height: handle.GetHeight(),
1505 }
1506 return config, nil
1507 }
1508
1509 func init() {
1510 image.RegisterFormat("heif", "????ftypheic", decodeImage, decodeConfig)
1511 image.RegisterFormat("heif", "????ftypheim", decodeImage, decodeConfig)
1512 image.RegisterFormat("heif", "????ftypheis", decodeImage, decodeConfig)
1513 image.RegisterFormat("heif", "????ftypheix", decodeImage, decodeConfig)
1514 image.RegisterFormat("heif", "????ftyphevc", decodeImage, decodeConfig)
1515 image.RegisterFormat("heif", "????ftyphevm", decodeImage, decodeConfig)
1516 image.RegisterFormat("heif", "????ftyphevs", decodeImage, decodeConfig)
1517 image.RegisterFormat("heif", "????ftypmif1", decodeImage, decodeConfig)
1518 image.RegisterFormat("avif", "????ftypavif", decodeImage, decodeConfig)
1519 image.RegisterFormat("avif", "????ftypavis", decodeImage, decodeConfig)
1520 }