| 1 |
/* |
| 2 |
* Copyright 2016 Google Inc. |
| 3 |
* |
| 4 |
* Use of this source code is governed by a BSD-style license that can be |
| 5 |
* found in the LICENSE file. |
| 6 |
*/ |
| 7 |
|
| 8 |
#include "src/codec/SkRawCodec.h" |
| 9 |
|
| 10 |
#include "include/codec/SkCodec.h" |
| 11 |
#include "include/codec/SkRawDecoder.h" |
| 12 |
#include "include/core/SkColorSpace.h" |
| 13 |
#include "include/core/SkData.h" |
| 14 |
#include "include/core/SkImageInfo.h" |
| 15 |
#include "include/core/SkRefCnt.h" |
| 16 |
#include "include/core/SkStream.h" |
| 17 |
#include "include/core/SkTypes.h" |
| 18 |
#include "include/private/SkEncodedInfo.h" |
| 19 |
#include "include/private/base/SkDebug.h" |
| 20 |
#include "include/private/base/SkMutex.h" |
| 21 |
#include "include/private/base/SkTArray.h" |
| 22 |
#include "include/private/base/SkTemplates.h" |
| 23 |
#include "modules/skcms/skcms.h" |
| 24 |
#include "src/codec/SkCodecPriv.h" |
| 25 |
#include "src/codec/SkJpegCodec.h" |
| 26 |
#include "src/core/SkStreamPriv.h" |
| 27 |
#include "src/core/SkTaskGroup.h" |
| 28 |
|
| 29 |
#include <algorithm> |
| 30 |
#include <cmath> |
| 31 |
#include <cstdint> |
| 32 |
#include <functional> |
| 33 |
#include <limits> |
| 34 |
#include <memory> |
| 35 |
#include <type_traits> |
| 36 |
#include <utility> |
| 37 |
#include <vector> |
| 38 |
|
| 39 |
#include "dng_area_task.h" // NO_G3_REWRITE |
| 40 |
#include "dng_color_space.h" // NO_G3_REWRITE |
| 41 |
#include "dng_errors.h" // NO_G3_REWRITE |
| 42 |
#include "dng_exceptions.h" // NO_G3_REWRITE |
| 43 |
#include "dng_host.h" // NO_G3_REWRITE |
| 44 |
#include "dng_image.h" // NO_G3_REWRITE |
| 45 |
#include "dng_info.h" // NO_G3_REWRITE |
| 46 |
#include "dng_memory.h" // NO_G3_REWRITE |
| 47 |
#include "dng_mosaic_info.h" // NO_G3_REWRITE |
| 48 |
#include "dng_negative.h" // NO_G3_REWRITE |
| 49 |
#include "dng_pixel_buffer.h" // NO_G3_REWRITE |
| 50 |
#include "dng_point.h" // NO_G3_REWRITE |
| 51 |
#include "dng_rational.h" // NO_G3_REWRITE |
| 52 |
#include "dng_rect.h" // NO_G3_REWRITE |
| 53 |
#include "dng_render.h" // NO_G3_REWRITE |
| 54 |
#include "dng_sdk_limits.h" // NO_G3_REWRITE |
| 55 |
#include "dng_stream.h" // NO_G3_REWRITE |
| 56 |
#include "dng_tag_types.h" // NO_G3_REWRITE |
| 57 |
#include "dng_types.h" // NO_G3_REWRITE |
| 58 |
#include "dng_utils.h" // NO_G3_REWRITE |
| 59 |
|
| 60 |
#include "src/piex.h" // NO_G3_REWRITE |
| 61 |
#include "src/piex_types.h" // NO_G3_REWRITE |
| 62 |
|
| 63 |
#ifndef SK_DNG_VERSION |
| 64 |
#define SK_DNG_VERSION 0x01040000 |
| 65 |
#endif |
| 66 |
|
| 67 |
#if SK_DNG_VERSION <= 0x01040000 |
| 68 |
#define OPT_PROGRESS_ARG |
| 69 |
#else |
| 70 |
#define OPT_PROGRESS_ARG ,dng_area_task_progress* |
| 71 |
#endif |
| 72 |
|
| 73 |
using namespace skia_private; |
| 74 |
|
| 75 |
template <typename T> struct sk_is_trivially_relocatable; |
| 76 |
template <> struct sk_is_trivially_relocatable<dng_exception> : std::true_type {}; |
| 77 |
|
| 78 |
namespace { |
| 79 |
|
| 80 |
// Calculates the number of tiles of tile_size that fit into the area in vertical and horizontal |
| 81 |
// directions. |
| 82 |
dng_point num_tiles_in_area(const dng_point &areaSize, |
| 83 |
const dng_point_real64 &tileSize) { |
| 84 |
// FIXME: Add a ceil_div() helper in SkCodecPriv.h |
| 85 |
return dng_point(static_cast<int32>((areaSize.v + tileSize.v - 1) / tileSize.v), |
| 86 |
static_cast<int32>((areaSize.h + tileSize.h - 1) / tileSize.h)); |
| 87 |
} |
| 88 |
|
| 89 |
int num_tasks_required(const dng_point& tilesInTask, |
| 90 |
const dng_point& tilesInArea) { |
| 91 |
return ((tilesInArea.v + tilesInTask.v - 1) / tilesInTask.v) * |
| 92 |
((tilesInArea.h + tilesInTask.h - 1) / tilesInTask.h); |
| 93 |
} |
| 94 |
|
| 95 |
// Calculate the number of tiles to process per task, taking into account the maximum number of |
| 96 |
// tasks. It prefers to increase horizontally for better locality of reference. |
| 97 |
dng_point num_tiles_per_task(const int maxTasks, |
| 98 |
const dng_point &tilesInArea) { |
| 99 |
dng_point tilesInTask = {1, 1}; |
| 100 |
while (num_tasks_required(tilesInTask, tilesInArea) > maxTasks) { |
| 101 |
if (tilesInTask.h < tilesInArea.h) { |
| 102 |
++tilesInTask.h; |
| 103 |
} else if (tilesInTask.v < tilesInArea.v) { |
| 104 |
++tilesInTask.v; |
| 105 |
} else { |
| 106 |
ThrowProgramError("num_tiles_per_task calculation is wrong."); |
| 107 |
} |
| 108 |
} |
| 109 |
return tilesInTask; |
| 110 |
} |
| 111 |
|
| 112 |
std::vector<dng_rect> compute_task_areas(const int maxTasks, const dng_rect& area, |
| 113 |
const dng_point& tileSize) { |
| 114 |
std::vector<dng_rect> taskAreas; |
| 115 |
const dng_point tilesInArea = num_tiles_in_area(area.Size(), tileSize); |
| 116 |
const dng_point tilesPerTask = num_tiles_per_task(maxTasks, tilesInArea); |
| 117 |
const dng_point taskAreaSize = {tilesPerTask.v * tileSize.v, |
| 118 |
tilesPerTask.h * tileSize.h}; |
| 119 |
for (int v = 0; v < tilesInArea.v; v += tilesPerTask.v) { |
| 120 |
for (int h = 0; h < tilesInArea.h; h += tilesPerTask.h) { |
| 121 |
dng_rect taskArea; |
| 122 |
taskArea.t = area.t + v * tileSize.v; |
| 123 |
taskArea.l = area.l + h * tileSize.h; |
| 124 |
taskArea.b = Min_int32(taskArea.t + taskAreaSize.v, area.b); |
| 125 |
taskArea.r = Min_int32(taskArea.l + taskAreaSize.h, area.r); |
| 126 |
|
| 127 |
taskAreas.push_back(taskArea); |
| 128 |
} |
| 129 |
} |
| 130 |
return taskAreas; |
| 131 |
} |
| 132 |
|
| 133 |
class SkDngHost : public dng_host { |
| 134 |
public: |
| 135 |
explicit SkDngHost(dng_memory_allocator* allocater) : dng_host(allocater) {} |
| 136 |
|
| 137 |
void PerformAreaTask(dng_area_task& task, const dng_rect& area OPT_PROGRESS_ARG) override { |
| 138 |
SkTaskGroup taskGroup; |
| 139 |
|
| 140 |
// tileSize is typically 256x256 |
| 141 |
const dng_point tileSize(task.FindTileSize(area)); |
| 142 |
const std::vector<dng_rect> taskAreas = compute_task_areas(this->PerformAreaTaskThreads(), |
| 143 |
area, tileSize); |
| 144 |
const int numTasks = static_cast<int>(taskAreas.size()); |
| 145 |
|
| 146 |
SkMutex mutex; |
| 147 |
TArray<dng_exception> exceptions; |
| 148 |
#if SK_DNG_VERSION <= 0x01040000 |
| 149 |
task.Start(numTasks, tileSize, &Allocator(), Sniffer()); |
| 150 |
#else |
| 151 |
task.Start(numTasks, area, tileSize, &Allocator(), Sniffer()); |
| 152 |
#endif |
| 153 |
for (int taskIndex = 0; taskIndex < numTasks; ++taskIndex) { |
| 154 |
taskGroup.add([&mutex, &exceptions, &task, this, taskIndex, taskAreas, tileSize] { |
| 155 |
try { |
| 156 |
#if SK_DNG_VERSION <= 0x01040000 |
| 157 |
task.ProcessOnThread(taskIndex, taskAreas[taskIndex], tileSize, this->Sniffer()); |
| 158 |
#else |
| 159 |
task.ProcessOnThread(taskIndex, taskAreas[taskIndex], tileSize, this->Sniffer(), nullptr); |
| 160 |
#endif |
| 161 |
} catch (dng_exception& exception) { |
| 162 |
SkAutoMutexExclusive lock(mutex); |
| 163 |
exceptions.push_back(exception); |
| 164 |
} catch (...) { |
| 165 |
SkAutoMutexExclusive lock(mutex); |
| 166 |
exceptions.push_back(dng_exception(dng_error_unknown)); |
| 167 |
} |
| 168 |
}); |
| 169 |
} |
| 170 |
|
| 171 |
taskGroup.wait(); |
| 172 |
task.Finish(numTasks); |
| 173 |
|
| 174 |
// We only re-throw the first exception. |
| 175 |
if (!exceptions.empty()) { |
| 176 |
Throw_dng_error(exceptions.front().ErrorCode(), nullptr, nullptr); |
| 177 |
} |
| 178 |
} |
| 179 |
|
| 180 |
uint32 PerformAreaTaskThreads() override { |
| 181 |
#ifdef SK_BUILD_FOR_ANDROID |
| 182 |
// Only use 1 thread. DNGs with the warp effect require a lot of memory, |
| 183 |
// and the amount of memory required scales linearly with the number of |
| 184 |
// threads. The sample used in CTS requires over 500 MB, so even two |
| 185 |
// threads is significantly expensive. There is no good way to tell |
| 186 |
// whether the image has the warp effect. |
| 187 |
return 1; |
| 188 |
#else |
| 189 |
return kMaxMPThreads; |
| 190 |
#endif |
| 191 |
} |
| 192 |
|
| 193 |
private: |
| 194 |
using INHERITED = dng_host; |
| 195 |
}; |
| 196 |
|
| 197 |
// T must be unsigned type. |
| 198 |
template <class T> |
| 199 |
bool safe_add_to_size_t(T arg1, T arg2, size_t* result) { |
| 200 |
SkASSERT(arg1 >= 0); |
| 201 |
SkASSERT(arg2 >= 0); |
| 202 |
if (arg1 >= 0 && arg2 <= std::numeric_limits<T>::max() - arg1) { |
| 203 |
T sum = arg1 + arg2; |
| 204 |
if (sum <= std::numeric_limits<size_t>::max()) { |
| 205 |
*result = static_cast<size_t>(sum); |
| 206 |
return true; |
| 207 |
} |
| 208 |
} |
| 209 |
return false; |
| 210 |
} |
| 211 |
|
| 212 |
bool is_asset_stream(const SkStream& stream) { |
| 213 |
return stream.hasLength() && stream.hasPosition(); |
| 214 |
} |
| 215 |
|
| 216 |
} // namespace |
| 217 |
|
| 218 |
class SkRawStream { |
| 219 |
public: |
| 220 |
virtual ~SkRawStream() {} |
| 221 |
|
| 222 |
/* |
| 223 |
* Gets the length of the stream. Depending on the type of stream, this may require reading to |
| 224 |
* the end of the stream. |
| 225 |
*/ |
| 226 |
virtual uint64 getLength() = 0; |
| 227 |
|
| 228 |
virtual bool read(void* data, size_t offset, size_t length) = 0; |
| 229 |
|
| 230 |
/* |
| 231 |
* Creates an SkMemoryStream from the offset with size. |
| 232 |
* Note: for performance reason, this function is destructive to the SkRawStream. One should |
| 233 |
* abandon current object after the function call. |
| 234 |
*/ |
| 235 |
virtual std::unique_ptr<SkMemoryStream> transferBuffer(size_t offset, size_t size) = 0; |
| 236 |
}; |
| 237 |
|
| 238 |
class SkRawLimitedDynamicMemoryWStream : public SkDynamicMemoryWStream { |
| 239 |
public: |
| 240 |
~SkRawLimitedDynamicMemoryWStream() override {} |
| 241 |
|
| 242 |
bool write(const void* buffer, size_t size) override { |
| 243 |
size_t newSize; |
| 244 |
if (!safe_add_to_size_t(this->bytesWritten(), size, &newSize) || |
| 245 |
newSize > kMaxStreamSize) |
| 246 |
{ |
| 247 |
SkCodecPrintf("Error: Stream size exceeds the limit.\n"); |
| 248 |
return false; |
| 249 |
} |
| 250 |
return this->INHERITED::write(buffer, size); |
| 251 |
} |
| 252 |
|
| 253 |
private: |
| 254 |
// Most of valid RAW images will not be larger than 100MB. This limit is helpful to avoid |
| 255 |
// streaming too large data chunk. We can always adjust the limit here if we need. |
| 256 |
const size_t kMaxStreamSize = 100 * 1024 * 1024; // 100MB |
| 257 |
|
| 258 |
using INHERITED = SkDynamicMemoryWStream; |
| 259 |
}; |
| 260 |
|
| 261 |
// Note: the maximum buffer size is 100MB (limited by SkRawLimitedDynamicMemoryWStream). |
| 262 |
class SkRawBufferedStream : public SkRawStream { |
| 263 |
public: |
| 264 |
explicit SkRawBufferedStream(std::unique_ptr<SkStream> stream) |
| 265 |
: fStream(std::move(stream)) |
| 266 |
, fWholeStreamRead(false) |
| 267 |
{ |
| 268 |
// Only use SkRawBufferedStream when the stream is not an asset stream. |
| 269 |
SkASSERT(!is_asset_stream(*fStream)); |
| 270 |
} |
| 271 |
|
| 272 |
~SkRawBufferedStream() override {} |
| 273 |
|
| 274 |
uint64 getLength() override { |
| 275 |
if (!this->bufferMoreData(kReadToEnd)) { // read whole stream |
| 276 |
ThrowReadFile(); |
| 277 |
} |
| 278 |
return fStreamBuffer.bytesWritten(); |
| 279 |
} |
| 280 |
|
| 281 |
bool read(void* data, size_t offset, size_t length) override { |
| 282 |
if (length == 0) { |
| 283 |
return true; |
| 284 |
} |
| 285 |
|
| 286 |
size_t sum; |
| 287 |
if (!safe_add_to_size_t(offset, length, &sum)) { |
| 288 |
return false; |
| 289 |
} |
| 290 |
|
| 291 |
return this->bufferMoreData(sum) && fStreamBuffer.read(data, offset, length); |
| 292 |
} |
| 293 |
|
| 294 |
std::unique_ptr<SkMemoryStream> transferBuffer(size_t offset, size_t size) override { |
| 295 |
sk_sp<SkData> data(SkData::MakeUninitialized(size)); |
| 296 |
if (offset > fStreamBuffer.bytesWritten()) { |
| 297 |
// If the offset is not buffered, read from fStream directly and skip the buffering. |
| 298 |
const size_t skipLength = offset - fStreamBuffer.bytesWritten(); |
| 299 |
if (fStream->skip(skipLength) != skipLength) { |
| 300 |
return nullptr; |
| 301 |
} |
| 302 |
const size_t bytesRead = fStream->read(data->writable_data(), size); |
| 303 |
if (bytesRead < size) { |
| 304 |
data = SkData::MakeSubset(data.get(), 0, bytesRead); |
| 305 |
} |
| 306 |
} else { |
| 307 |
const size_t alreadyBuffered = std::min(fStreamBuffer.bytesWritten() - offset, size); |
| 308 |
if (alreadyBuffered > 0 && |
| 309 |
!fStreamBuffer.read(data->writable_data(), offset, alreadyBuffered)) { |
| 310 |
return nullptr; |
| 311 |
} |
| 312 |
|
| 313 |
const size_t remaining = size - alreadyBuffered; |
| 314 |
if (remaining) { |
| 315 |
auto* dst = static_cast<uint8_t*>(data->writable_data()) + alreadyBuffered; |
| 316 |
const size_t bytesRead = fStream->read(dst, remaining); |
| 317 |
size_t newSize; |
| 318 |
if (bytesRead < remaining) { |
| 319 |
if (!safe_add_to_size_t(alreadyBuffered, bytesRead, &newSize)) { |
| 320 |
return nullptr; |
| 321 |
} |
| 322 |
data = SkData::MakeSubset(data.get(), 0, newSize); |
| 323 |
} |
| 324 |
} |
| 325 |
} |
| 326 |
return SkMemoryStream::Make(data); |
| 327 |
} |
| 328 |
|
| 329 |
private: |
| 330 |
// Note: if the newSize == kReadToEnd (0), this function will read to the end of stream. |
| 331 |
bool bufferMoreData(size_t newSize) { |
| 332 |
if (newSize == kReadToEnd) { |
| 333 |
if (fWholeStreamRead) { // already read-to-end. |
| 334 |
return true; |
| 335 |
} |
| 336 |
|
| 337 |
// TODO: optimize for the special case when the input is SkMemoryStream. |
| 338 |
return SkStreamPriv::Copy(&fStreamBuffer, fStream.get()); |
| 339 |
} |
| 340 |
|
| 341 |
if (newSize <= fStreamBuffer.bytesWritten()) { // already buffered to newSize |
| 342 |
return true; |
| 343 |
} |
| 344 |
if (fWholeStreamRead) { // newSize is larger than the whole stream. |
| 345 |
return false; |
| 346 |
} |
| 347 |
|
| 348 |
// Try to read at least 8192 bytes to avoid to many small reads. |
| 349 |
const size_t kMinSizeToRead = 8192; |
| 350 |
const size_t sizeRequested = newSize - fStreamBuffer.bytesWritten(); |
| 351 |
const size_t sizeToRead = std::max(kMinSizeToRead, sizeRequested); |
| 352 |
AutoSTMalloc<kMinSizeToRead, uint8> tempBuffer(sizeToRead); |
| 353 |
const size_t bytesRead = fStream->read(tempBuffer.get(), sizeToRead); |
| 354 |
if (bytesRead < sizeRequested) { |
| 355 |
return false; |
| 356 |
} |
| 357 |
return fStreamBuffer.write(tempBuffer.get(), bytesRead); |
| 358 |
} |
| 359 |
|
| 360 |
std::unique_ptr<SkStream> fStream; |
| 361 |
bool fWholeStreamRead; |
| 362 |
|
| 363 |
// Use a size-limited stream to avoid holding too huge buffer. |
| 364 |
SkRawLimitedDynamicMemoryWStream fStreamBuffer; |
| 365 |
|
| 366 |
const size_t kReadToEnd = 0; |
| 367 |
}; |
| 368 |
|
| 369 |
class SkRawAssetStream : public SkRawStream { |
| 370 |
public: |
| 371 |
explicit SkRawAssetStream(std::unique_ptr<SkStream> stream) |
| 372 |
: fStream(std::move(stream)) |
| 373 |
{ |
| 374 |
// Only use SkRawAssetStream when the stream is an asset stream. |
| 375 |
SkASSERT(is_asset_stream(*fStream)); |
| 376 |
} |
| 377 |
|
| 378 |
~SkRawAssetStream() override {} |
| 379 |
|
| 380 |
uint64 getLength() override { |
| 381 |
return fStream->getLength(); |
| 382 |
} |
| 383 |
|
| 384 |
|
| 385 |
bool read(void* data, size_t offset, size_t length) override { |
| 386 |
if (length == 0) { |
| 387 |
return true; |
| 388 |
} |
| 389 |
|
| 390 |
size_t sum; |
| 391 |
if (!safe_add_to_size_t(offset, length, &sum)) { |
| 392 |
return false; |
| 393 |
} |
| 394 |
|
| 395 |
return fStream->seek(offset) && (fStream->read(data, length) == length); |
| 396 |
} |
| 397 |
|
| 398 |
std::unique_ptr<SkMemoryStream> transferBuffer(size_t offset, size_t size) override { |
| 399 |
if (fStream->getLength() < offset) { |
| 400 |
return nullptr; |
| 401 |
} |
| 402 |
|
| 403 |
size_t sum; |
| 404 |
if (!safe_add_to_size_t(offset, size, &sum)) { |
| 405 |
return nullptr; |
| 406 |
} |
| 407 |
|
| 408 |
// This will allow read less than the requested "size", because the JPEG codec wants to |
| 409 |
// handle also a partial JPEG file. |
| 410 |
const size_t bytesToRead = std::min(sum, fStream->getLength()) - offset; |
| 411 |
if (bytesToRead == 0) { |
| 412 |
return nullptr; |
| 413 |
} |
| 414 |
|
| 415 |
if (fStream->getMemoryBase()) { // directly copy if getMemoryBase() is available. |
| 416 |
sk_sp<SkData> data(SkData::MakeWithCopy( |
| 417 |
static_cast<const uint8_t*>(fStream->getMemoryBase()) + offset, bytesToRead)); |
| 418 |
fStream.reset(); |
| 419 |
return SkMemoryStream::Make(data); |
| 420 |
} else { |
| 421 |
sk_sp<SkData> data(SkData::MakeUninitialized(bytesToRead)); |
| 422 |
if (!fStream->seek(offset)) { |
| 423 |
return nullptr; |
| 424 |
} |
| 425 |
const size_t bytesRead = fStream->read(data->writable_data(), bytesToRead); |
| 426 |
if (bytesRead < bytesToRead) { |
| 427 |
data = SkData::MakeSubset(data.get(), 0, bytesRead); |
| 428 |
} |
| 429 |
return SkMemoryStream::Make(data); |
| 430 |
} |
| 431 |
} |
| 432 |
private: |
| 433 |
std::unique_ptr<SkStream> fStream; |
| 434 |
}; |
| 435 |
|
| 436 |
class SkPiexStream : public ::piex::StreamInterface { |
| 437 |
public: |
| 438 |
// Will NOT take the ownership of the stream. |
| 439 |
explicit SkPiexStream(SkRawStream* stream) : fStream(stream) {} |
| 440 |
|
| 441 |
~SkPiexStream() override {} |
| 442 |
|
| 443 |
::piex::Error GetData(const size_t offset, const size_t length, |
| 444 |
uint8* data) override { |
| 445 |
return fStream->read(static_cast<void*>(data), offset, length) ? |
| 446 |
::piex::Error::kOk : ::piex::Error::kFail; |
| 447 |
} |
| 448 |
|
| 449 |
private: |
| 450 |
SkRawStream* fStream; |
| 451 |
}; |
| 452 |
|
| 453 |
class SkDngStream : public dng_stream { |
| 454 |
public: |
| 455 |
// Will NOT take the ownership of the stream. |
| 456 |
SkDngStream(SkRawStream* stream) |
| 457 |
// The default constructor sets offsetInOriginalFile to invalid (-1), however |
| 458 |
// this results in dng_negative hitting a bug path that causes a crash due to |
| 459 |
// unsigned overflow occuring. This offset doesn't seem to serve any purpose, |
| 460 |
// so just pretend we're always at the start of the file to avoid the crash |
| 461 |
: dng_stream((dng_abort_sniffer*) nullptr, dng_stream::kDefaultBufferSize, 0) |
| 462 |
, fStream(stream) {} |
| 463 |
|
| 464 |
~SkDngStream() override {} |
| 465 |
|
| 466 |
uint64 DoGetLength() override { return fStream->getLength(); } |
| 467 |
|
| 468 |
void DoRead(void* data, uint32 count, uint64 offset) override { |
| 469 |
size_t sum; |
| 470 |
if (!safe_add_to_size_t(static_cast<uint64>(count), offset, &sum) || |
| 471 |
!fStream->read(data, static_cast<size_t>(offset), static_cast<size_t>(count))) { |
| 472 |
ThrowReadFile(); |
| 473 |
} |
| 474 |
} |
| 475 |
|
| 476 |
private: |
| 477 |
SkRawStream* fStream; |
| 478 |
}; |
| 479 |
|
| 480 |
class SkDngImage { |
| 481 |
public: |
| 482 |
/* |
| 483 |
* Initializes the object with the information from Piex in a first attempt. This way it can |
| 484 |
* save time and storage to obtain the DNG dimensions and color filter array (CFA) pattern |
| 485 |
* which is essential for the demosaicing of the sensor image. |
| 486 |
* Note: this will take the ownership of the stream. |
| 487 |
*/ |
| 488 |
static SkDngImage* NewFromStream(SkRawStream* stream) { |
| 489 |
std::unique_ptr<SkDngImage> dngImage(new SkDngImage(stream)); |
| 490 |
#if defined(SK_BUILD_FOR_LIBFUZZER) |
| 491 |
// Libfuzzer easily runs out of memory after here. To avoid that |
| 492 |
// We just pretend all streams are invalid. Our AFL-fuzzer |
| 493 |
// should still exercise this code; it's more resistant to OOM. |
| 494 |
return nullptr; |
| 495 |
#else |
| 496 |
if (!dngImage->initFromPiex() && !dngImage->readDng()) { |
| 497 |
return nullptr; |
| 498 |
} |
| 499 |
|
| 500 |
return dngImage.release(); |
| 501 |
#endif |
| 502 |
} |
| 503 |
|
| 504 |
/* |
| 505 |
* Renders the DNG image to the size. The DNG SDK only allows scaling close to integer factors |
| 506 |
* down to 80 pixels on the short edge. The rendered image will be close to the specified size, |
| 507 |
* but there is no guarantee that any of the edges will match the requested size. E.g. |
| 508 |
* 100% size: 4000 x 3000 |
| 509 |
* requested size: 1600 x 1200 |
| 510 |
* returned size could be: 2000 x 1500 |
| 511 |
*/ |
| 512 |
dng_image* render(int width, int height) { |
| 513 |
if (!fHost || !fInfo || !fNegative || !fDngStream) { |
| 514 |
if (!this->readDng()) { |
| 515 |
return nullptr; |
| 516 |
} |
| 517 |
} |
| 518 |
|
| 519 |
// DNG SDK preserves the aspect ratio, so it only needs to know the longer dimension. |
| 520 |
const int preferredSize = std::max(width, height); |
| 521 |
try { |
| 522 |
// render() takes ownership of fHost, fInfo, fNegative and fDngStream when available. |
| 523 |
std::unique_ptr<dng_host> host(fHost.release()); |
| 524 |
std::unique_ptr<dng_info> info(fInfo.release()); |
| 525 |
std::unique_ptr<dng_negative> negative(fNegative.release()); |
| 526 |
std::unique_ptr<dng_stream> dngStream(fDngStream.release()); |
| 527 |
|
| 528 |
host->SetPreferredSize(preferredSize); |
| 529 |
host->ValidateSizes(); |
| 530 |
|
| 531 |
negative->ReadStage1Image(*host, *dngStream, *info); |
| 532 |
|
| 533 |
if (info->fMaskIndex != -1) { |
| 534 |
negative->ReadTransparencyMask(*host, *dngStream, *info); |
| 535 |
} |
| 536 |
|
| 537 |
negative->ValidateRawImageDigest(*host); |
| 538 |
if (negative->IsDamaged()) { |
| 539 |
return nullptr; |
| 540 |
} |
| 541 |
|
| 542 |
const int32 kMosaicPlane = -1; |
| 543 |
negative->BuildStage2Image(*host); |
| 544 |
negative->BuildStage3Image(*host, kMosaicPlane); |
| 545 |
|
| 546 |
dng_render render(*host, *negative); |
| 547 |
render.SetFinalSpace(dng_space_sRGB::Get()); |
| 548 |
render.SetFinalPixelType(ttByte); |
| 549 |
|
| 550 |
dng_point stage3_size = negative->Stage3Image()->Size(); |
| 551 |
render.SetMaximumSize(std::max(stage3_size.h, stage3_size.v)); |
| 552 |
|
| 553 |
return render.Render(); |
| 554 |
} catch (...) { |
| 555 |
return nullptr; |
| 556 |
} |
| 557 |
} |
| 558 |
|
| 559 |
int width() const { |
| 560 |
return fWidth; |
| 561 |
} |
| 562 |
|
| 563 |
int height() const { |
| 564 |
return fHeight; |
| 565 |
} |
| 566 |
|
| 567 |
bool isScalable() const { |
| 568 |
return fIsScalable; |
| 569 |
} |
| 570 |
|
| 571 |
bool isXtransImage() const { |
| 572 |
return fIsXtransImage; |
| 573 |
} |
| 574 |
|
| 575 |
// Quick check if the image contains a valid TIFF header as requested by DNG format. |
| 576 |
// Does not affect ownership of stream. |
| 577 |
static bool IsTiffHeaderValid(SkRawStream* stream) { |
| 578 |
const size_t kHeaderSize = 4; |
| 579 |
unsigned char header[kHeaderSize]; |
| 580 |
if (!stream->read(header, 0 /* offset */, kHeaderSize)) { |
| 581 |
return false; |
| 582 |
} |
| 583 |
|
| 584 |
// Check if the header is valid (endian info and magic number "42"). |
| 585 |
bool littleEndian; |
| 586 |
if (!SkCodecPriv::IsValidEndianMarker(header, &littleEndian)) { |
| 587 |
return false; |
| 588 |
} |
| 589 |
|
| 590 |
return 0x2A == SkCodecPriv::GetEndianShort(header + 2, littleEndian); |
| 591 |
} |
| 592 |
|
| 593 |
private: |
| 594 |
bool init(int width, int height, const dng_point& cfaPatternSize) { |
| 595 |
fWidth = width; |
| 596 |
fHeight = height; |
| 597 |
|
| 598 |
// The DNG SDK scales only during demosaicing, so scaling is only possible when |
| 599 |
// a mosaic info is available. |
| 600 |
fIsScalable = cfaPatternSize.v != 0 && cfaPatternSize.h != 0; |
| 601 |
fIsXtransImage = fIsScalable ? (cfaPatternSize.v == 6 && cfaPatternSize.h == 6) : false; |
| 602 |
|
| 603 |
return width > 0 && height > 0; |
| 604 |
} |
| 605 |
|
| 606 |
bool initFromPiex() { |
| 607 |
// Does not take the ownership of rawStream. |
| 608 |
SkPiexStream piexStream(fStream.get()); |
| 609 |
::piex::PreviewImageData imageData; |
| 610 |
if (::piex::IsRaw(&piexStream) |
| 611 |
&& ::piex::GetPreviewImageData(&piexStream, &imageData) == ::piex::Error::kOk) |
| 612 |
{ |
| 613 |
dng_point cfaPatternSize(imageData.cfa_pattern_dim[1], imageData.cfa_pattern_dim[0]); |
| 614 |
return this->init(static_cast<int>(imageData.full_width), |
| 615 |
static_cast<int>(imageData.full_height), cfaPatternSize); |
| 616 |
} |
| 617 |
return false; |
| 618 |
} |
| 619 |
|
| 620 |
bool readDng() { |
| 621 |
try { |
| 622 |
// Due to the limit of DNG SDK, we need to reset host and info. |
| 623 |
fHost = std::make_unique<SkDngHost>(&fAllocator); |
| 624 |
fInfo = std::make_unique<dng_info>(); |
| 625 |
fDngStream = std::make_unique<SkDngStream>(fStream.get()); |
| 626 |
|
| 627 |
fHost->ValidateSizes(); |
| 628 |
fInfo->Parse(*fHost, *fDngStream); |
| 629 |
fInfo->PostParse(*fHost); |
| 630 |
if (!fInfo->IsValidDNG()) { |
| 631 |
return false; |
| 632 |
} |
| 633 |
|
| 634 |
fNegative.reset(fHost->Make_dng_negative()); |
| 635 |
fNegative->Parse(*fHost, *fDngStream, *fInfo); |
| 636 |
fNegative->PostParse(*fHost, *fDngStream, *fInfo); |
| 637 |
fNegative->SynchronizeMetadata(); |
| 638 |
|
| 639 |
dng_point cfaPatternSize(0, 0); |
| 640 |
if (fNegative->GetMosaicInfo() != nullptr) { |
| 641 |
cfaPatternSize = fNegative->GetMosaicInfo()->fCFAPatternSize; |
| 642 |
} |
| 643 |
return this->init(static_cast<int>(fNegative->DefaultCropSizeH().As_real64()), |
| 644 |
static_cast<int>(fNegative->DefaultCropSizeV().As_real64()), |
| 645 |
cfaPatternSize); |
| 646 |
} catch (...) { |
| 647 |
return false; |
| 648 |
} |
| 649 |
} |
| 650 |
|
| 651 |
SkDngImage(SkRawStream* stream) |
| 652 |
: fStream(stream) |
| 653 |
{} |
| 654 |
|
| 655 |
dng_memory_allocator fAllocator; |
| 656 |
std::unique_ptr<SkRawStream> fStream; |
| 657 |
std::unique_ptr<dng_host> fHost; |
| 658 |
std::unique_ptr<dng_info> fInfo; |
| 659 |
std::unique_ptr<dng_negative> fNegative; |
| 660 |
std::unique_ptr<dng_stream> fDngStream; |
| 661 |
|
| 662 |
int fWidth; |
| 663 |
int fHeight; |
| 664 |
bool fIsScalable; |
| 665 |
bool fIsXtransImage; |
| 666 |
}; |
| 667 |
|
| 668 |
/* |
| 669 |
* Tries to handle the image with PIEX. If PIEX returns kOk and finds the preview image, create a |
| 670 |
* SkJpegCodec. If PIEX returns kFail, then the file is invalid, return nullptr. In other cases, |
| 671 |
* fallback to create SkRawCodec for DNG images. |
| 672 |
*/ |
| 673 |
std::unique_ptr<SkCodec> SkRawCodec::MakeFromStream(std::unique_ptr<SkStream> stream, |
| 674 |
Result* result) { |
| 675 |
SkASSERT(result); |
| 676 |
if (!stream) { |
| 677 |
*result = SkCodec::kInvalidInput; |
| 678 |
return nullptr; |
| 679 |
} |
| 680 |
std::unique_ptr<SkRawStream> rawStream; |
| 681 |
if (is_asset_stream(*stream)) { |
| 682 |
rawStream = std::make_unique<SkRawAssetStream>(std::move(stream)); |
| 683 |
} else { |
| 684 |
rawStream = std::make_unique<SkRawBufferedStream>(std::move(stream)); |
| 685 |
} |
| 686 |
|
| 687 |
// Does not take the ownership of rawStream. |
| 688 |
SkPiexStream piexStream(rawStream.get()); |
| 689 |
::piex::PreviewImageData imageData; |
| 690 |
if (::piex::IsRaw(&piexStream)) { |
| 691 |
::piex::Error error = ::piex::GetPreviewImageData(&piexStream, &imageData); |
| 692 |
if (error == ::piex::Error::kFail) { |
| 693 |
*result = kInvalidInput; |
| 694 |
return nullptr; |
| 695 |
} |
| 696 |
|
| 697 |
std::unique_ptr<SkCodecs::ColorProfile> profile; |
| 698 |
if (imageData.color_space == ::piex::PreviewImageData::kAdobeRgb) { |
| 699 |
profile = SkCodecs::ColorProfile::Make( |
| 700 |
SkNamedTransferFn::k2Dot2, SkNamedGamut::kAdobeRGB); |
| 701 |
} |
| 702 |
|
| 703 |
// Theoretically PIEX can return JPEG compressed image or uncompressed RGB image. We only |
| 704 |
// handle the JPEG compressed preview image here. |
| 705 |
if (error == ::piex::Error::kOk && imageData.preview.length > 0 && |
| 706 |
imageData.preview.format == ::piex::Image::kJpegCompressed) |
| 707 |
{ |
| 708 |
// transferBuffer() is destructive to the rawStream. Abandon the rawStream after this |
| 709 |
// function call. |
| 710 |
// FIXME: one may avoid the copy of memoryStream and use the buffered rawStream. |
| 711 |
auto memoryStream = rawStream->transferBuffer(imageData.preview.offset, |
| 712 |
imageData.preview.length); |
| 713 |
if (!memoryStream) { |
| 714 |
*result = kInvalidInput; |
| 715 |
return nullptr; |
| 716 |
} |
| 717 |
return SkJpegCodec::MakeFromStream(std::move(memoryStream), result, |
| 718 |
std::move(profile)); |
| 719 |
} |
| 720 |
} |
| 721 |
|
| 722 |
if (!SkDngImage::IsTiffHeaderValid(rawStream.get())) { |
| 723 |
*result = kUnimplemented; |
| 724 |
return nullptr; |
| 725 |
} |
| 726 |
|
| 727 |
// Takes the ownership of the rawStream. |
| 728 |
std::unique_ptr<SkDngImage> dngImage(SkDngImage::NewFromStream(rawStream.release())); |
| 729 |
if (!dngImage) { |
| 730 |
*result = kInvalidInput; |
| 731 |
return nullptr; |
| 732 |
} |
| 733 |
|
| 734 |
*result = kSuccess; |
| 735 |
return std::unique_ptr<SkCodec>(new SkRawCodec(dngImage.release())); |
| 736 |
} |
| 737 |
|
| 738 |
SkCodec::Result SkRawCodec::onGetPixels(const SkImageInfo& dstInfo, void* dst, |
| 739 |
size_t dstRowBytes, const Options& options, |
| 740 |
int* rowsDecoded) { |
| 741 |
const int width = dstInfo.width(); |
| 742 |
const int height = dstInfo.height(); |
| 743 |
std::unique_ptr<dng_image> image(fDngImage->render(width, height)); |
| 744 |
if (!image) { |
| 745 |
return kInvalidInput; |
| 746 |
} |
| 747 |
|
| 748 |
// Because the DNG SDK can not guarantee to render to requested size, we allow a small |
| 749 |
// difference. Only the overlapping region will be converted. |
| 750 |
const float maxDiffRatio = 1.03f; |
| 751 |
const dng_point& imageSize = image->Size(); |
| 752 |
if (imageSize.h / (float) width > maxDiffRatio || imageSize.h < width || |
| 753 |
imageSize.v / (float) height > maxDiffRatio || imageSize.v < height) { |
| 754 |
return SkCodec::kInvalidScale; |
| 755 |
} |
| 756 |
|
| 757 |
void* dstRow = dst; |
| 758 |
AutoTMalloc<uint8_t> srcRow(width * 3); |
| 759 |
|
| 760 |
dng_pixel_buffer buffer; |
| 761 |
buffer.fData = &srcRow[0]; |
| 762 |
buffer.fPlane = 0; |
| 763 |
buffer.fPlanes = 3; |
| 764 |
buffer.fColStep = buffer.fPlanes; |
| 765 |
buffer.fPlaneStep = 1; |
| 766 |
buffer.fPixelType = ttByte; |
| 767 |
buffer.fPixelSize = sizeof(uint8_t); |
| 768 |
buffer.fRowStep = width * 3; |
| 769 |
|
| 770 |
constexpr auto srcFormat = skcms_PixelFormat_RGB_888; |
| 771 |
skcms_PixelFormat dstFormat; |
| 772 |
if (!SkCodecPriv::SelectXformFormat(dstInfo.colorType(), false, &dstFormat)) { |
| 773 |
return kInvalidConversion; |
| 774 |
} |
| 775 |
|
| 776 |
const skcms_ICCProfile* const srcProfile = this->getEncodedInfo().profile(); |
| 777 |
skcms_ICCProfile dstProfileStorage; |
| 778 |
const skcms_ICCProfile* dstProfile = nullptr; |
| 779 |
if (auto cs = dstInfo.colorSpace()) { |
| 780 |
cs->toProfile(&dstProfileStorage); |
| 781 |
dstProfile = &dstProfileStorage; |
| 782 |
} |
| 783 |
|
| 784 |
for (int i = 0; i < height; ++i) { |
| 785 |
buffer.fArea = dng_rect(i, 0, i + 1, width); |
| 786 |
|
| 787 |
try { |
| 788 |
image->Get(buffer, dng_image::edge_zero); |
| 789 |
} catch (...) { |
| 790 |
*rowsDecoded = i; |
| 791 |
return kIncompleteInput; |
| 792 |
} |
| 793 |
|
| 794 |
if (!skcms_Transform(&srcRow[0], srcFormat, skcms_AlphaFormat_Unpremul, srcProfile, |
| 795 |
dstRow, dstFormat, skcms_AlphaFormat_Unpremul, dstProfile, |
| 796 |
dstInfo.width())) { |
| 797 |
SkDebugf("failed to transform\n"); |
| 798 |
*rowsDecoded = i; |
| 799 |
return kInternalError; |
| 800 |
} |
| 801 |
|
| 802 |
dstRow = SkTAddOffset<void>(dstRow, dstRowBytes); |
| 803 |
} |
| 804 |
return kSuccess; |
| 805 |
} |
| 806 |
|
| 807 |
SkISize SkRawCodec::onGetScaledDimensions(float desiredScale) const { |
| 808 |
SkASSERT(desiredScale <= 1.f); |
| 809 |
|
| 810 |
const SkISize dim = this->dimensions(); |
| 811 |
SkASSERT(dim.fWidth != 0 && dim.fHeight != 0); |
| 812 |
|
| 813 |
if (!fDngImage->isScalable()) { |
| 814 |
return dim; |
| 815 |
} |
| 816 |
|
| 817 |
// Limits the minimum size to be 80 on the short edge. |
| 818 |
const float shortEdge = static_cast<float>(std::min(dim.fWidth, dim.fHeight)); |
| 819 |
if (desiredScale < 80.f / shortEdge) { |
| 820 |
desiredScale = 80.f / shortEdge; |
| 821 |
} |
| 822 |
|
| 823 |
// For Xtrans images, the integer-factor scaling does not support the half-size scaling case |
| 824 |
// (stronger downscalings are fine). In this case, returns the factor "3" scaling instead. |
| 825 |
if (fDngImage->isXtransImage() && desiredScale > 1.f / 3.f && desiredScale < 1.f) { |
| 826 |
desiredScale = 1.f / 3.f; |
| 827 |
} |
| 828 |
|
| 829 |
// Round to integer-factors. |
| 830 |
const float finalScale = std::floor(1.f/ desiredScale); |
| 831 |
return SkISize::Make(static_cast<int32_t>(std::floor(dim.fWidth / finalScale)), |
| 832 |
static_cast<int32_t>(std::floor(dim.fHeight / finalScale))); |
| 833 |
} |
| 834 |
|
| 835 |
bool SkRawCodec::onDimensionsSupported(const SkISize& dim) { |
| 836 |
const SkISize fullDim = this->dimensions(); |
| 837 |
const float fullShortEdge = static_cast<float>(std::min(fullDim.fWidth, fullDim.fHeight)); |
| 838 |
const float shortEdge = static_cast<float>(std::min(dim.fWidth, dim.fHeight)); |
| 839 |
|
| 840 |
SkISize sizeFloor = this->onGetScaledDimensions(1.f / std::floor(fullShortEdge / shortEdge)); |
| 841 |
SkISize sizeCeil = this->onGetScaledDimensions(1.f / std::ceil(fullShortEdge / shortEdge)); |
| 842 |
return sizeFloor == dim || sizeCeil == dim; |
| 843 |
} |
| 844 |
|
| 845 |
SkRawCodec::~SkRawCodec() {} |
| 846 |
|
| 847 |
SkRawCodec::SkRawCodec(SkDngImage* dngImage) |
| 848 |
: INHERITED(SkEncodedInfo::Make(dngImage->width(), dngImage->height(), |
| 849 |
SkEncodedInfo::kRGB_Color, |
| 850 |
SkEncodedInfo::kOpaque_Alpha, 8), |
| 851 |
skcms_PixelFormat_RGBA_8888, nullptr) |
| 852 |
, fDngImage(dngImage) {} |
| 853 |
|
| 854 |
namespace SkRawDecoder { |
| 855 |
|
| 856 |
std::unique_ptr<SkCodec> Decode(std::unique_ptr<SkStream> stream, |
| 857 |
SkCodec::Result* outResult, |
| 858 |
SkCodecs::DecodeContext) { |
| 859 |
SkCodec::Result resultStorage; |
| 860 |
if (!outResult) { |
| 861 |
outResult = &resultStorage; |
| 862 |
} |
| 863 |
return SkRawCodec::MakeFromStream(std::move(stream), outResult); |
| 864 |
} |
| 865 |
|
| 866 |
std::unique_ptr<SkCodec> Decode(sk_sp<const SkData> data, |
| 867 |
SkCodec::Result* outResult, |
| 868 |
SkCodecs::DecodeContext) { |
| 869 |
if (!data) { |
| 870 |
if (outResult) { |
| 871 |
*outResult = SkCodec::kInvalidInput; |
| 872 |
} |
| 873 |
return nullptr; |
| 874 |
} |
| 875 |
return Decode(SkMemoryStream::Make(std::move(data)), outResult, nullptr); |
| 876 |
} |
| 877 |
} // namespace SkRawDecoder |