| 1 | /* |
| 2 | * Copyright (C) 2018 The Android Open Source Project |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | #include <image/ColorTransform.h> |
| 18 | #include <image/ImageOps.h> |
| 19 | #include <image/ImageSampler.h> |
| 20 | #include <image/KtxBundle.h> |
| 21 | #include <image/LinearImage.h> |
| 22 | |
| 23 | #ifdef IMAGEIO_SUPPORTS_BLOCK_COMPRESSION |
| 24 | #include <imageio/BlockCompression.h> |
| 25 | #endif |
| 26 | |
| 27 | #include <imageio/ImageDecoder.h> |
| 28 | #include <imageio/ImageEncoder.h> |
| 29 | |
| 30 | #include <utils/Path.h> |
| 31 | |
| 32 | #include <getopt/getopt.h> |
| 33 | |
| 34 | #include <fstream> |
| 35 | #include <iostream> |
| 36 | #include <string> |
| 37 | |
| 38 | using namespace image; |
| 39 | using namespace std; |
| 40 | using namespace utils; |
| 41 | |
| 42 | static ImageEncoder::Format g_format = ImageEncoder::Format::PNG; |
| 43 | static bool g_formatSpecified = false; |
| 44 | static bool g_createGallery = false; |
| 45 | static std::string g_compression = ""; |
| 46 | static Filter g_filter = Filter::DEFAULT; |
| 47 | static bool g_addAlpha = false; |
| 48 | static bool g_stripAlpha = false; |
| 49 | static bool g_grayscale = false; |
| 50 | static bool g_ktxContainer = false; |
| 51 | static bool g_linearized = false; |
| 52 | static bool g_quietMode = false; |
| 53 | static uint32_t g_mipLevelCount = 0; |
| 54 | |
| 55 | static const char* USAGE = R"TXT( |
| 56 | MIPGEN generates mipmaps for an image down to the 1x1 level. |
| 57 | |
| 58 | The <output_pattern> argument is a printf-style pattern. |
| 59 | For example, "mip%2d.png" generates mip01.png, mip02.png, etc. |
| 60 | Miplevel 0 is not generated since it is the original image. |
| 61 | |
| 62 | If the output format is a container format like KTX, then |
| 63 | <output_pattern> is simply a filename. |
| 64 | |
| 65 | Usage: |
| 66 | MIPGEN [options] <input_file> <output_pattern> |
| 67 | |
| 68 | Options: |
| 69 | --help, -h |
| 70 | print this message |
| 71 | --license, -L |
| 72 | print copyright and license information |
| 73 | --linear, -l |
| 74 | assume that image pixels are already linearized |
| 75 | --page, -p |
| 76 | generate HTML page for review purposes (mipmap.html) |
| 77 | --quiet, -q |
| 78 | suppress console output from the mipgen tool |
| 79 | --grayscale, -g |
| 80 | create a single-channel image and do not perform gamma correction |
| 81 | --format=[exr|hdr|rgbm|psd|png|dds|ktx], -f [exr|hdr|rgbm|psd|png|dds|ktx] |
| 82 | specify output file format, inferred from output pattern if omitted |
| 83 | --kernel=[box|nearest|hermite|gaussian|normals|mitchell|lanczos|min], -k [filter] |
| 84 | specify filter kernel type (defaults to lanczos) |
| 85 | the "normals" filter may automatically change the compression scheme |
| 86 | --add-alpha |
| 87 | if the source image has 3 channels, this adds a fourth channel filled with 1.0 |
| 88 | --strip-alpha |
| 89 | ignore the alpha component of the input image |
| 90 | --mip-levels=N, -m N |
| 91 | specifies the number of mip levels to generate |
| 92 | if 0 (default), all levels are generated |
| 93 | --compression=COMPRESSION, -c COMPRESSION |
| 94 | format specific compression: |
| 95 | )TXT" |
| 96 | #ifdef IMAGEIO_SUPPORTS_BLOCK_COMPRESSION |
| 97 | R"TXT( |
| 98 | KTX: |
| 99 | astc_[fast|thorough]_[ldr|hdr]_WxH, where WxH is a valid block size |
| 100 | s3tc_rgb_dxt1, s3tc_rgba_dxt5 |
| 101 | etc_FORMAT_METRIC_EFFORT |
| 102 | FORMAT is r11, signed_r11, rg11, signed_rg11, rgb8, srgb8, rgb8_alpha |
| 103 | srgb8_alpha, rgba8, or srgb8_alpha8 |
| 104 | METRIC is rgba, rgbx, rec709, numeric, or normalxyz |
| 105 | EFFORT is an integer between 0 and 100 |
| 106 | )TXT" |
| 107 | #endif |
| 108 | R"TXT( |
| 109 | PNG: Ignored |
| 110 | Radiance: Ignored |
| 111 | Photoshop: 16 (default), 32 |
| 112 | OpenEXR: RAW, RLE, ZIPS, ZIP, PIZ (default) |
| 113 | DDS: 8, 16 (default), 32 |
| 114 | |
| 115 | Examples: |
| 116 | MIPGEN -g --kernel=hermite grassland.png mip_%03d.png |
| 117 | MIPGEN -f ktx --compression=astc_fast_ldr_4x4 grassland.png mips.ktx |
| 118 | MIPGEN -f ktx --compression=etc_rgb_rgba_40 grassland.png mips.ktx |
| 119 | )TXT"; |
| 120 | |
| 121 | static const char* HTML_PREFIX = R"HTML(<!DOCTYPE html> |
| 122 | <html> |
| 123 | <head> |
| 124 | <style> |
| 125 | img { |
| 126 | image-rendering: pixelated; |
| 127 | border: solid 2px; |
| 128 | padding: 2px; |
| 129 | display: block; |
| 130 | } |
| 131 | </style> |
| 132 | </head> |
| 133 | <body> |
| 134 | )HTML"; |
| 135 | |
| 136 | static const char* HTML_SUFFIX = R"HTML(</body> |
| 137 | </html> |
| 138 | )HTML"; |
| 139 | |
| 140 | static void printUsage(const char* name) { |
| 141 | std::string execName(Path(name).getName()); |
| 142 | const std::string from("MIPGEN"); |
| 143 | std::string usage(USAGE); |
| 144 | for (size_t pos = usage.find(from); pos != std::string::npos; pos = usage.find(from, pos)) { |
| 145 | usage.replace(pos, from.length(), execName); |
| 146 | } |
| 147 | puts(usage.c_str()); |
| 148 | } |
| 149 | |
| 150 | static void license() { |
| 151 | static const char *license[] = { |
| 152 | #include "licenses/licenses.inc" |
| 153 | nullptr |
| 154 | }; |
| 155 | |
| 156 | const char **p = &license[0]; |
| 157 | while (*p) |
| 158 | std::cout << *p++ << std::endl; |
| 159 | } |
| 160 | |
| 161 | static int handleArguments(int argc, char* argv[]) { |
| 162 | static constexpr const char* OPTSTR = "hLlgpf:c:k:saqm:"; |
| 163 | static const struct option OPTIONS[] = { |
| 164 | { "help", no_argument, 0, 'h' }, |
| 165 | { "license", no_argument, 0, 'L' }, |
| 166 | { "linear", no_argument, 0, 'l' }, |
| 167 | { "grayscale", no_argument, 0, 'g' }, |
| 168 | { "page", no_argument, 0, 'p' }, |
| 169 | { "format", required_argument, 0, 'f' }, |
| 170 | { "compression", required_argument, 0, 'c' }, |
| 171 | { "kernel", required_argument, 0, 'k' }, |
| 172 | { "strip-alpha", no_argument, 0, 's' }, |
| 173 | { "add-alpha", no_argument, 0, 'a' }, |
| 174 | { "quiet", no_argument, 0, 'q' }, |
| 175 | { "mip-levels", required_argument, 0, 'm' }, |
| 176 | { 0, 0, 0, 0 } // termination of the option list |
| 177 | }; |
| 178 | |
| 179 | int opt; |
| 180 | int optionIndex = 0; |
| 181 | |
| 182 | while ((opt = getopt_long(argc, argv, OPTSTR, OPTIONS, &optionIndex)) >= 0) { |
| 183 | std::string arg(optarg ? optarg : ""); |
| 184 | switch (opt) { |
| 185 | default: |
| 186 | case 'h': |
| 187 | printUsage(argv[0]); |
| 188 | exit(0); |
| 189 | case 'L': |
| 190 | license(); |
| 191 | exit(0); |
| 192 | case 'l': |
| 193 | g_linearized = true; |
| 194 | break; |
| 195 | case 'g': |
| 196 | g_grayscale = true; |
| 197 | break; |
| 198 | case 'p': |
| 199 | g_createGallery = true; |
| 200 | break; |
| 201 | case 'k': { |
| 202 | g_filter = filterFromString(arg.c_str()); |
| 203 | if (g_filter == Filter::DEFAULT) { |
| 204 | cerr << "Warning: unrecognized filter, falling back to DEFAULT." << endl; |
| 205 | } |
| 206 | break; |
| 207 | } |
| 208 | case 's': |
| 209 | g_stripAlpha = true; |
| 210 | break; |
| 211 | case 'a': |
| 212 | g_addAlpha = true; |
| 213 | break; |
| 214 | case 'q': |
| 215 | g_quietMode = true; |
| 216 | break; |
| 217 | case 'f': |
| 218 | if (arg == "png") { |
| 219 | g_format = ImageEncoder::Format::PNG; |
| 220 | g_formatSpecified = true; |
| 221 | } |
| 222 | if (arg == "hdr") { |
| 223 | g_format = ImageEncoder::Format::HDR; |
| 224 | g_formatSpecified = true; |
| 225 | } |
| 226 | if (arg == "rgbm") { |
| 227 | g_format = ImageEncoder::Format::RGBM; |
| 228 | g_formatSpecified = true; |
| 229 | } |
| 230 | if (arg == "exr") { |
| 231 | g_format = ImageEncoder::Format::EXR; |
| 232 | g_formatSpecified = true; |
| 233 | } |
| 234 | if (arg == "psd") { |
| 235 | g_format = ImageEncoder::Format::PSD; |
| 236 | g_formatSpecified = true; |
| 237 | } |
| 238 | if (arg == "dds") { |
| 239 | g_format = ImageEncoder::Format::DDS_LINEAR; |
| 240 | g_formatSpecified = true; |
| 241 | } |
| 242 | if (arg == "ktx") { |
| 243 | g_ktxContainer = true; |
| 244 | g_formatSpecified = true; |
| 245 | } |
| 246 | break; |
| 247 | case 'c': |
| 248 | g_compression = arg; |
| 249 | break; |
| 250 | case 'm': |
| 251 | try { |
| 252 | g_mipLevelCount = std::stoi(arg); |
| 253 | } catch (std::invalid_argument &e) { |
| 254 | // keep default value |
| 255 | } |
| 256 | break; |
| 257 | } |
| 258 | } |
| 259 | |
| 260 | return optind; |
| 261 | } |
| 262 | |
| 263 | int main(int argc, char* argv[]) { |
| 264 | int optionIndex = handleArguments(argc, argv); |
| 265 | int numArgs = argc - optionIndex; |
| 266 | if (numArgs < 2) { |
| 267 | printUsage(argv[0]); |
| 268 | return 1; |
| 269 | } |
| 270 | Path inputPath(argv[optionIndex++]); |
| 271 | std::string outputPattern(argv[optionIndex]); |
| 272 | if (Path(outputPattern).getExtension() == "ktx") { |
| 273 | g_ktxContainer = true; |
| 274 | g_formatSpecified = true; |
| 275 | } else if (!g_formatSpecified) { |
| 276 | g_format = ImageEncoder::chooseFormat(outputPattern, g_linearized); |
| 277 | } |
| 278 | |
| 279 | if (!g_quietMode) { |
| 280 | puts("Reading image..."); |
| 281 | } |
| 282 | |
| 283 | ifstream inputStream(inputPath.getPath(), ios::binary); |
| 284 | LinearImage sourceImage = ImageDecoder::decode(inputStream, inputPath.getPath(), |
| 285 | g_linearized ? ImageDecoder::ColorSpace::LINEAR : ImageDecoder::ColorSpace::SRGB); |
| 286 | if (!sourceImage.isValid()) { |
| 287 | cerr << "Unable to open image: " << inputPath.getPath() << endl; |
| 288 | return 1; |
| 289 | } |
| 290 | if (g_stripAlpha && sourceImage.getChannels() == 4) { |
| 291 | auto r = extractChannel(sourceImage, 0); |
| 292 | auto g = extractChannel(sourceImage, 1); |
| 293 | auto b = extractChannel(sourceImage, 2); |
| 294 | sourceImage = combineChannels({r, g, b}); |
| 295 | } |
| 296 | if (g_addAlpha && sourceImage.getChannels() == 3) { |
| 297 | auto r = extractChannel(sourceImage, 0); |
| 298 | auto g = extractChannel(sourceImage, 1); |
| 299 | auto b = extractChannel(sourceImage, 2); |
| 300 | auto a = LinearImage(sourceImage.getWidth(), sourceImage.getHeight(), 1); |
| 301 | clearToValue(a, 1.0f); |
| 302 | sourceImage = combineChannels({r, g, b, a}); |
| 303 | } |
| 304 | if (g_grayscale) { |
| 305 | sourceImage = extractChannel(sourceImage, 0); |
| 306 | } |
| 307 | |
| 308 | if (g_filter == Filter::GAUSSIAN_NORMALS) { |
| 309 | sourceImage = colorsToVectors(sourceImage); |
| 310 | } |
| 311 | |
| 312 | if (!g_quietMode) { |
| 313 | puts("Generating miplevels..."); |
| 314 | } |
| 315 | |
| 316 | uint32_t count = getMipmapCount(sourceImage); |
| 317 | count = g_mipLevelCount == 0 ? count : min(g_mipLevelCount - 1, count); |
| 318 | vector<LinearImage> miplevels(count); |
| 319 | generateMipmaps(sourceImage, g_filter, miplevels.data(), count); |
| 320 | |
| 321 | if (g_ktxContainer) { |
| 322 | if (!g_quietMode) { |
| 323 | puts("Writing KTX file to disk..."); |
| 324 | } |
| 325 | |
| 326 | // The libimage API does not include the original image in the mip array, |
| 327 | // which might make sense when generating individual files, but for a KTX |
| 328 | // bundle, we want to include level 0, so add 1 to the KTX level count. |
| 329 | KtxBundle container(1 + miplevels.size(), 1, false); |
| 330 | auto& info = container.info(); |
| 331 | info = { |
| 332 | .endianness = KtxBundle::ENDIAN_DEFAULT, |
| 333 | .glType = KtxBundle::UNSIGNED_BYTE, |
| 334 | .glTypeSize = 1, |
| 335 | .pixelWidth = sourceImage.getWidth(), |
| 336 | .pixelHeight = sourceImage.getHeight(), |
| 337 | .pixelDepth = 0, |
| 338 | }; |
| 339 | size_t componentCount = sourceImage.getChannels(); |
| 340 | if (componentCount == 1) { |
| 341 | info.glFormat = info.glBaseInternalFormat = KtxBundle::RED; |
| 342 | info.glInternalFormat = KtxBundle::R8; |
| 343 | } else if (componentCount == 3) { |
| 344 | info.glFormat = info.glBaseInternalFormat = KtxBundle::RGB; |
| 345 | info.glInternalFormat = KtxBundle::RGB8; |
| 346 | } else if (componentCount == 4) { |
| 347 | info.glFormat = info.glBaseInternalFormat = KtxBundle::RGBA; |
| 348 | info.glInternalFormat = KtxBundle::RGBA8; |
| 349 | } |
| 350 | #ifdef IMAGEIO_SUPPORTS_BLOCK_COMPRESSION |
| 351 | CompressionConfig config {}; |
| 352 | if (!g_compression.empty()) { |
| 353 | bool valid = parseOptionString(g_compression, &config); |
| 354 | if (!valid) { |
| 355 | cerr << "Unrecognized compression: " << g_compression << endl; |
| 356 | return 1; |
| 357 | } |
| 358 | // The KTX spec says the following for compressed textures: glTypeSize should 1, |
| 359 | // glFormat should be 0, and glBaseInternalFormat should be RED, RG, RGB, or RGBA. |
| 360 | // The glInternalFormat field is the only field that specifies the actual format. |
| 361 | info.glFormat = 0; |
| 362 | } |
| 363 | #else |
| 364 | if (!g_compression.empty()) { |
| 365 | cerr << "Compression not supported in this build." << endl; |
| 366 | return 1; |
| 367 | } |
| 368 | #endif |
| 369 | uint32_t mip = 0; |
| 370 | auto addLevel = [&](LinearImage image) { |
| 371 | if (g_filter == Filter::GAUSSIAN_NORMALS) { |
| 372 | image = vectorsToColors(image); |
| 373 | } |
| 374 | std::unique_ptr<uint8_t[]> data; |
| 375 | #ifdef IMAGEIO_SUPPORTS_BLOCK_COMPRESSION |
| 376 | if (config.type != CompressionConfig::INVALID) { |
| 377 | // Some encoders call exit(1) upon failure, so it's very useful to print some |
| 378 | // source image information here for when this is invoked from a build script. |
| 379 | // Note that some encoders also have limitations in terms of image size. |
| 380 | if (!g_quietMode) { |
| 381 | printf("Starting compression for %s (%dx%d)\n", inputPath.getName().c_str(), |
| 382 | image.getWidth(), image.getHeight()); |
| 383 | } |
| 384 | CompressedTexture tex = compressTexture(config, image); |
| 385 | container.setBlob({mip++}, tex.data.get(), tex.size); |
| 386 | info.glInternalFormat = (uint32_t) tex.format; |
| 387 | return; |
| 388 | } |
| 389 | #endif |
| 390 | if (g_grayscale && g_linearized) { |
| 391 | data = fromLinearToGrayscale<uint8_t>(image); |
| 392 | } else if (g_grayscale) { |
| 393 | data = fromLinearTosRGB<uint8_t, 1>(image); |
| 394 | } else if (g_linearized) { |
| 395 | if (componentCount == 3) { |
| 396 | data = fromLinearToRGB<uint8_t, 3>(image); |
| 397 | } else { |
| 398 | data = fromLinearToRGB<uint8_t, 4>(image); |
| 399 | } |
| 400 | } else { |
| 401 | if (componentCount == 3) { |
| 402 | data = fromLinearTosRGB<uint8_t, 3>(image); |
| 403 | } else { |
| 404 | data = fromLinearTosRGB<uint8_t, 4>(image); |
| 405 | } |
| 406 | } |
| 407 | container.setBlob({mip++, 0, 0}, data.get(), image.getWidth() * image.getHeight() * |
| 408 | container.info().glTypeSize * componentCount); |
| 409 | }; |
| 410 | addLevel(sourceImage); |
| 411 | for (auto image : miplevels) { |
| 412 | addLevel(image); |
| 413 | } |
| 414 | vector<uint8_t> fileContents(container.getSerializedLength()); |
| 415 | container.serialize(fileContents.data(), fileContents.size()); |
| 416 | Path(outputPattern).getParent().mkdirRecursive(); |
| 417 | ofstream outputStream(outputPattern, ios::out | ios::binary); |
| 418 | outputStream.write((const char*) fileContents.data(), fileContents.size()); |
| 419 | outputStream.close(); |
| 420 | if (!g_quietMode) { |
| 421 | puts("Done."); |
| 422 | } |
| 423 | return 0; |
| 424 | } |
| 425 | |
| 426 | if (!g_quietMode) { |
| 427 | puts("Writing image files to disk..."); |
| 428 | } |
| 429 | |
| 430 | char path[256]; |
| 431 | uint32_t mip = 1; // start at 1 because 0 is the original image |
| 432 | for (auto image : miplevels) { |
| 433 | int result = snprintf(path, sizeof(path), outputPattern.c_str(), mip++); |
| 434 | if (result < 0 || result >= sizeof(path)) { |
| 435 | cerr << "Output pattern is too long." << endl; |
| 436 | return 1; |
| 437 | } |
| 438 | Path(path).getParent().mkdirRecursive(); |
| 439 | ofstream outputStream(path, ios::binary | ios::trunc); |
| 440 | if (!outputStream) { |
| 441 | cerr << "The output file cannot be opened: " << path << endl; |
| 442 | } else { |
| 443 | if (!ImageEncoder::encode(outputStream, g_format, image, g_compression, path)) { |
| 444 | cerr << "An error occurred while encoding the image." << endl; |
| 445 | return 1; |
| 446 | } |
| 447 | outputStream.close(); |
| 448 | if (!outputStream) { |
| 449 | cerr << "An error occurred while writing the output file: " << path << endl; |
| 450 | return 1; |
| 451 | } |
| 452 | } |
| 453 | } |
| 454 | |
| 455 | if (g_createGallery) { |
| 456 | if (!g_quietMode) { |
| 457 | puts("Generating mipmaps.html..."); |
| 458 | } |
| 459 | |
| 460 | char tag[256]; |
| 461 | mip = 1; |
| 462 | const char* pattern = R"(<image src="%s" width="%dpx" height="%dpx">)"; |
| 463 | const uint32_t width = sourceImage.getWidth(); |
| 464 | const uint32_t height = sourceImage.getHeight(); |
| 465 | ofstream html("mipmaps.html", ios::trunc); |
| 466 | html << HTML_PREFIX; |
| 467 | int result = snprintf(tag, sizeof(tag), pattern, inputPath.c_str(), width, height); |
| 468 | if (result < 0 || result >= sizeof(tag)) { |
| 469 | cerr << "Output pattern is too long." << endl; |
| 470 | return 1; |
| 471 | } |
| 472 | html << tag << std::endl; |
| 473 | for (auto image: miplevels) { |
| 474 | snprintf(path, sizeof(path), outputPattern.c_str(), mip++); |
| 475 | result = snprintf(tag, sizeof(tag), pattern, path, width, height); |
| 476 | if (result < 0 || result >= sizeof(tag)) { |
| 477 | cerr << "Output pattern is too long." << endl; |
| 478 | return 1; |
| 479 | } |
| 480 | html << tag << std::endl; |
| 481 | } |
| 482 | html << HTML_SUFFIX; |
| 483 | } |
| 484 | |
| 485 | if (!g_quietMode) { |
| 486 | puts("Done."); |
| 487 | } |
| 488 | } |