File: heif.cc

package info (click to toggle)
exactimage 1.2.1-3
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 3,048 kB
  • sloc: cpp: 35,940; ansic: 1,952; xml: 1,447; makefile: 338; perl: 138; sh: 110; python: 45; php: 37; ruby: 12
file content (255 lines) | stat: -rw-r--r-- 7,476 bytes parent folder | download | duplicates (2)
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
/*
 * Copyright (C) 2023 - 2024 René Rebe, ExactCODE GmbH
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 2. A copy of the GNU General
 * Public License can be found in the file LICENSE.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANT-
 * ABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
 * Public License for more details.
 *
 * Alternatively, commercial licensing options are available from the
 * copyright holder ExactCODE GmbH Germany.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <iostream>
#include <sstream>
#include <vector>

#include <libheif/heif.h>

#include "heif.hh"

/* TODO:
 * dpi
 * exif
 * icc
 * mutli images
 * writing
 */

extern "C" {
  static int64_t heif_get_position(void* userdata) {
    std::istream* stream = (std::istream*)userdata;
    //std::cerr << __FUNCTION__ << std::endl;
    if (!stream->good())
      stream->clear();
    return stream->tellg();
  }
  
  static int heif_read(void* data, size_t size, void* userdata) {
    std::istream* stream = (std::istream*)userdata;
    //std::cerr << __FUNCTION__ << " " << size << std::endl;
    stream->read((char*)data, size);
    if (stream->good()) {
      return heif_error_code::heif_error_Ok;
    } else {
      stream->clear();
      return heif_error_code::heif_error_Invalid_input;
    }
  }
  
  static int heif_seek(int64_t position, void* userdata) {
    std::istream* stream = (std::istream*)userdata;
    //std::cerr << __FUNCTION__ << std::endl;
    stream->seekg(position);
    if (stream->good()) {
      return heif_error_code::heif_error_Ok;
    } else {
      stream->clear();
      return heif_error_code::heif_error_Invalid_input;
    }
  }
  
  enum heif_reader_grow_status heif_wait_for_file_size(int64_t target_size, void* userdata) {
    std::istream* stream = (std::istream*)userdata;
    
    size_t pos = stream->tellg();
    //std::cerr << __FUNCTION__ << " " << " " << target_size << " (at: " << pos << std::endl;
    stream->seekg(target_size);
    heif_reader_grow_status ret = heif_reader_grow_status_size_reached;
    if (!stream->good()) {
      stream->clear();
      ret = heif_reader_grow_status_size_beyond_eof;
    }
    
    stream->seekg(pos);
    
    return ret;
  }
}

bool HEIFCodec::initialized = false;

HEIFCodec::HEIFCodec () {
  registerCodec ("heic", this);
};

HEIFCodec::~HEIFCodec () {
  if (initialized) {
    heif_deinit();
    initialized = false;
  }
};

int HEIFCodec::readImage(std::istream* stream, Image& image, const std::string& decompress)
{
  if (!initialized) {
    heif_init(nullptr);
    initialized = true;
  }

  if (true) {
    char magic[12];
    
    stream->read(magic, sizeof(magic));
    stream->seekg(0);
    
    enum heif_filetype_result filetype_check =
      heif_check_filetype((uint8_t*)magic, 12);
    
    if ((filetype_check == heif_filetype_no) ||
	(filetype_check == heif_filetype_yes_unsupported)) {
      fprintf(stderr, "Input file is not an HEIF/AVIF file or unsupported\n");
      return false;
    }
  }
  
  heif_context* ctx = heif_context_alloc();
  if (!ctx) {
    fprintf(stderr, "Could not create context object\n");
    return false;
  }
  
  heif_reader reader = {
    1,
    heif_get_position,
    heif_read,
    heif_seek,
    heif_wait_for_file_size,
  };

  heif_error err;
  err = heif_context_read_from_reader(ctx, &reader, stream, nullptr);
  if (err.code != 0) {
    std::cerr << "Could not read HEIF/AVIF file: " << err.message << "\n";
    return false;
  }

  int num_images = heif_context_get_number_of_top_level_images(ctx);
  if (num_images == 0) {
    fprintf(stderr, "File doesn't contain any images\n");
    return false;
  }

  //std::cout << "File contains " << num_images << " images\n";
  
  std::vector<heif_item_id> image_IDs(num_images);
  num_images = heif_context_get_list_of_top_level_image_IDs(ctx, image_IDs.data(), num_images);

  for (int idx = 0; idx < num_images; ++idx) {
    heif_image_handle* handle;
    err = heif_context_get_image_handle(ctx, image_IDs[idx], &handle);
    if (err.code) {
      std::cerr << "Could not read HEIF/AVIF image " << idx << ": "
                << err.message << "\n";
      return false;
    }

    int has_alpha = heif_image_handle_has_alpha_channel(handle);
    heif_decoding_options* decode_options = heif_decoding_options_alloc();
    //encoder->UpdateDecodingOptions(handle, decode_options);

    //decode_options->strict_decoding = strict_decoding;
    //decode_options->decoder_id = decoder_id;

    //decode_options->color_conversion_options.preferred_chroma_upsampling_algorithm = heif_chroma_upsampling_nearest_neighbor;
    //decode_options->color_conversion_options.preferred_chroma_upsampling_algorithm = heif_chroma_upsampling_bilinear;
    //decode_options->color_conversion_options.only_use_preferred_chroma_algorithm = true;
    
    int bit_depth = heif_image_handle_get_luma_bits_per_pixel(handle);
    if (bit_depth < 0) {
      heif_decoding_options_free(decode_options);
      heif_image_handle_release(handle);
      std::cerr << "Input image has undefined bit-depth\n";
      return false;
    }

    heif_chroma chroma = has_alpha ? heif_chroma_interleaved_RGBA : heif_chroma_interleaved_RGB;
    if (bit_depth > 8)
      chroma = has_alpha ? heif_chroma_interleaved_RRGGBBAA_BE : heif_chroma_interleaved_RRGGBB_BE;
    
    
    heif_image* himage = 0;
    err = heif_decode_image(handle,
			    &himage,
			    heif_colorspace_RGB,
			    chroma,
			    decode_options);
    heif_decoding_options_free(decode_options);
    if (err.code) {
      heif_image_handle_release(handle);
      std::cerr << "Could not decode image: " << idx << ": " << err.message << "\n";
      return false;
    }

    // show decoding warnings
    for (int i = 0;; i++) {
      int n = heif_image_get_decoding_warnings(himage, i, &err, 1);
      if (n == 0) {
        break;
      }
      
      std::cerr << "Warning: " << err.message << "\n";
    }
    
    if (himage) {
      bool withAlpha = (heif_image_get_chroma_format(himage) == heif_chroma_interleaved_RGBA ||
			heif_image_get_chroma_format(himage) == heif_chroma_interleaved_RRGGBBAA_BE);
      
      int width = heif_image_get_width(himage, heif_channel_interleaved);
      int height = heif_image_get_height(himage, heif_channel_interleaved);
      
      int bitDepth = 8;
      int input_bpp = heif_image_get_bits_per_pixel_range(himage, heif_channel_interleaved);
      if (input_bpp > 8)
	bitDepth = 16;
      
      image.spp = withAlpha ? 4 : 3;
      image.bps = bitDepth;
      image.resize(width, height);
      image.setResolution(72, 72);
      
      const int stride = image.stride();
      uint8_t* data = image.getRawData();
      int stride_rgb = 0;
      const uint8_t* row_rgb =
	heif_image_get_plane_readonly(himage,
				      heif_channel_interleaved, &stride_rgb);
      for (int y = 0; y < height; ++y) {
	memcpy(data + stride * y, row_rgb + stride_rgb * y, stride);
      }
      
      heif_image_release(himage);
      heif_image_handle_release(handle);
    }
  }
  
  return true;
}


bool HEIFCodec::writeImage(std::ostream* stream, Image& image, int quality,
			     const std::string& compress)
{
  return false;
}

HEIFCodec heif_loader;