blob: ef8ba700a46b22130bdfd262b610e2b66e1c72ee [file] [log] [blame]
yujieqin916de9f2016-01-25 08:26:16 -08001/*
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 "SkCodec.h"
9#include "SkCodecPriv.h"
10#include "SkColorPriv.h"
11#include "SkData.h"
yujieqin916de9f2016-01-25 08:26:16 -080012#include "SkJpegCodec.h"
yujieqinf236ee42016-02-29 07:14:42 -080013#include "SkMutex.h"
yujieqin916de9f2016-01-25 08:26:16 -080014#include "SkRawCodec.h"
15#include "SkRefCnt.h"
16#include "SkStream.h"
17#include "SkStreamPriv.h"
18#include "SkSwizzler.h"
yujieqinf236ee42016-02-29 07:14:42 -080019#include "SkTArray.h"
ebrauerb84b5b42016-01-27 08:21:03 -080020#include "SkTaskGroup.h"
yujieqin916de9f2016-01-25 08:26:16 -080021#include "SkTemplates.h"
22#include "SkTypes.h"
23
ebrauerb84b5b42016-01-27 08:21:03 -080024#include "dng_area_task.h"
yujieqin916de9f2016-01-25 08:26:16 -080025#include "dng_color_space.h"
yujieqinf236ee42016-02-29 07:14:42 -080026#include "dng_errors.h"
yujieqin916de9f2016-01-25 08:26:16 -080027#include "dng_exceptions.h"
28#include "dng_host.h"
29#include "dng_info.h"
30#include "dng_memory.h"
31#include "dng_render.h"
32#include "dng_stream.h"
33
34#include "src/piex.h"
35
36#include <cmath> // for std::round,floor,ceil
37#include <limits>
38
39namespace {
40
ebrauerb84b5b42016-01-27 08:21:03 -080041// Caluclates the number of tiles of tile_size that fit into the area in vertical and horizontal
42// directions.
43dng_point num_tiles_in_area(const dng_point &areaSize,
44 const dng_point_real64 &tileSize) {
45 // FIXME: Add a ceil_div() helper in SkCodecPriv.h
yujieqinfda27a92016-01-27 09:03:20 -080046 return dng_point(static_cast<int32>((areaSize.v + tileSize.v - 1) / tileSize.v),
47 static_cast<int32>((areaSize.h + tileSize.h - 1) / tileSize.h));
ebrauerb84b5b42016-01-27 08:21:03 -080048}
49
50int num_tasks_required(const dng_point& tilesInTask,
51 const dng_point& tilesInArea) {
52 return ((tilesInArea.v + tilesInTask.v - 1) / tilesInTask.v) *
53 ((tilesInArea.h + tilesInTask.h - 1) / tilesInTask.h);
54}
55
56// Calculate the number of tiles to process per task, taking into account the maximum number of
57// tasks. It prefers to increase horizontally for better locality of reference.
58dng_point num_tiles_per_task(const int maxTasks,
59 const dng_point &tilesInArea) {
60 dng_point tilesInTask = {1, 1};
61 while (num_tasks_required(tilesInTask, tilesInArea) > maxTasks) {
62 if (tilesInTask.h < tilesInArea.h) {
63 ++tilesInTask.h;
64 } else if (tilesInTask.v < tilesInArea.v) {
65 ++tilesInTask.v;
66 } else {
67 ThrowProgramError("num_tiles_per_task calculation is wrong.");
68 }
69 }
70 return tilesInTask;
71}
72
73std::vector<dng_rect> compute_task_areas(const int maxTasks, const dng_rect& area,
74 const dng_point& tileSize) {
75 std::vector<dng_rect> taskAreas;
76 const dng_point tilesInArea = num_tiles_in_area(area.Size(), tileSize);
77 const dng_point tilesPerTask = num_tiles_per_task(maxTasks, tilesInArea);
78 const dng_point taskAreaSize = {tilesPerTask.v * tileSize.v,
79 tilesPerTask.h * tileSize.h};
80 for (int v = 0; v < tilesInArea.v; v += tilesPerTask.v) {
81 for (int h = 0; h < tilesInArea.h; h += tilesPerTask.h) {
82 dng_rect taskArea;
83 taskArea.t = area.t + v * tileSize.v;
84 taskArea.l = area.l + h * tileSize.h;
85 taskArea.b = Min_int32(taskArea.t + taskAreaSize.v, area.b);
86 taskArea.r = Min_int32(taskArea.l + taskAreaSize.h, area.r);
87
88 taskAreas.push_back(taskArea);
89 }
90 }
91 return taskAreas;
92}
93
94class SkDngHost : public dng_host {
95public:
yujieqinfda27a92016-01-27 09:03:20 -080096 explicit SkDngHost(dng_memory_allocator* allocater) : dng_host(allocater) {}
ebrauerb84b5b42016-01-27 08:21:03 -080097
98 void PerformAreaTask(dng_area_task& task, const dng_rect& area) override {
99 // The area task gets split up into max_tasks sub-tasks. The max_tasks is defined by the
100 // dng-sdks default implementation of dng_area_task::MaxThreads() which returns 8 or 32
101 // sub-tasks depending on the architecture.
102 const int maxTasks = static_cast<int>(task.MaxThreads());
103
104 SkTaskGroup taskGroup;
105
106 // tileSize is typically 256x256
107 const dng_point tileSize(task.FindTileSize(area));
108 const std::vector<dng_rect> taskAreas = compute_task_areas(maxTasks, area, tileSize);
yujieqinfda27a92016-01-27 09:03:20 -0800109 const int numTasks = static_cast<int>(taskAreas.size());
ebrauerb84b5b42016-01-27 08:21:03 -0800110
yujieqinf236ee42016-02-29 07:14:42 -0800111 SkMutex mutex;
112 SkTArray<dng_exception> exceptions;
ebrauerb84b5b42016-01-27 08:21:03 -0800113 task.Start(numTasks, tileSize, &Allocator(), Sniffer());
114 for (int taskIndex = 0; taskIndex < numTasks; ++taskIndex) {
yujieqinf236ee42016-02-29 07:14:42 -0800115 taskGroup.add([&mutex, &exceptions, &task, this, taskIndex, taskAreas, tileSize] {
116 try {
117 task.ProcessOnThread(taskIndex, taskAreas[taskIndex], tileSize, this->Sniffer());
118 } catch (dng_exception& exception) {
119 SkAutoMutexAcquire lock(mutex);
120 exceptions.push_back(exception);
121 } catch (...) {
122 SkAutoMutexAcquire lock(mutex);
123 exceptions.push_back(dng_exception(dng_error_unknown));
124 }
ebrauerb84b5b42016-01-27 08:21:03 -0800125 });
126 }
127
128 taskGroup.wait();
129 task.Finish(numTasks);
yujieqinf236ee42016-02-29 07:14:42 -0800130
131 // Currently we only re-throw the first catched exception.
132 if (!exceptions.empty()) {
133 Throw_dng_error(exceptions.front().ErrorCode(), nullptr, nullptr);
134 }
ebrauerb84b5b42016-01-27 08:21:03 -0800135 }
136
137 uint32 PerformAreaTaskThreads() override {
138 // FIXME: Need to get the real amount of available threads used in the SkTaskGroup.
139 return kMaxMPThreads;
140 }
141
142private:
143 typedef dng_host INHERITED;
144};
145
yujieqin916de9f2016-01-25 08:26:16 -0800146// T must be unsigned type.
147template <class T>
148bool safe_add_to_size_t(T arg1, T arg2, size_t* result) {
149 SkASSERT(arg1 >= 0);
150 SkASSERT(arg2 >= 0);
151 if (arg1 >= 0 && arg2 <= std::numeric_limits<T>::max() - arg1) {
152 T sum = arg1 + arg2;
153 if (sum <= std::numeric_limits<size_t>::max()) {
154 *result = static_cast<size_t>(sum);
155 return true;
156 }
157 }
158 return false;
159}
160
161class SkDngMemoryAllocator : public dng_memory_allocator {
162public:
163 ~SkDngMemoryAllocator() override {}
164
165 dng_memory_block* Allocate(uint32 size) override {
166 // To avoid arbitary allocation requests which might lead to out-of-memory, limit the
167 // amount of memory that can be allocated at once. The memory limit is based on experiments
168 // and supposed to be sufficient for all valid DNG images.
169 if (size > 300 * 1024 * 1024) { // 300 MB
170 ThrowMemoryFull();
171 }
172 return dng_memory_allocator::Allocate(size);
173 }
174};
175
yujieqin9c7a8a42016-02-05 08:21:19 -0800176bool is_asset_stream(const SkStream& stream) {
177 return stream.hasLength() && stream.hasPosition();
178}
179
yujieqin916de9f2016-01-25 08:26:16 -0800180} // namespace
181
yujieqin9c7a8a42016-02-05 08:21:19 -0800182class SkRawStream {
yujieqin916de9f2016-01-25 08:26:16 -0800183public:
yujieqin9c7a8a42016-02-05 08:21:19 -0800184 virtual ~SkRawStream() {}
yujieqin916de9f2016-01-25 08:26:16 -0800185
yujieqin9c7a8a42016-02-05 08:21:19 -0800186 /*
187 * Gets the length of the stream. Depending on the type of stream, this may require reading to
188 * the end of the stream.
189 */
190 virtual uint64 getLength() = 0;
191
192 virtual bool read(void* data, size_t offset, size_t length) = 0;
yujieqin916de9f2016-01-25 08:26:16 -0800193
194 /*
195 * Creates an SkMemoryStream from the offset with size.
196 * Note: for performance reason, this function is destructive to the SkRawStream. One should
197 * abandon current object after the function call.
198 */
yujieqin9c7a8a42016-02-05 08:21:19 -0800199 virtual SkMemoryStream* transferBuffer(size_t offset, size_t size) = 0;
200};
201
yujieqinc04df212016-03-09 13:49:36 -0800202class SkRawLimitedDynamicMemoryWStream : public SkDynamicMemoryWStream {
203public:
204 virtual ~SkRawLimitedDynamicMemoryWStream() {}
205
206 bool write(const void* buffer, size_t size) override {
207 size_t newSize;
208 if (!safe_add_to_size_t(this->bytesWritten(), size, &newSize) ||
209 newSize > kMaxStreamSize)
210 {
211 SkCodecPrintf("Error: Stream size exceeds the limit.\n");
212 return false;
213 }
214 return this->INHERITED::write(buffer, size);
215 }
216
217private:
yujieqind6215cf2016-03-10 05:15:49 -0800218 // Most of valid RAW images will not be larger than 100MB. This limit is helpful to avoid
219 // streaming too large data chunk. We can always adjust the limit here if we need.
yujieqinc04df212016-03-09 13:49:36 -0800220 const size_t kMaxStreamSize = 100 * 1024 * 1024; // 100MB
221
222 typedef SkDynamicMemoryWStream INHERITED;
223};
224
225// Note: the maximum buffer size is 100MB (limited by SkRawLimitedDynamicMemoryWStream).
yujieqin9c7a8a42016-02-05 08:21:19 -0800226class SkRawBufferedStream : public SkRawStream {
227public:
228 // Will take the ownership of the stream.
229 explicit SkRawBufferedStream(SkStream* stream)
230 : fStream(stream)
231 , fWholeStreamRead(false)
232 {
233 // Only use SkRawBufferedStream when the stream is not an asset stream.
234 SkASSERT(!is_asset_stream(*stream));
235 }
236
237 ~SkRawBufferedStream() override {}
238
239 uint64 getLength() override {
240 if (!this->bufferMoreData(kReadToEnd)) { // read whole stream
241 ThrowReadFile();
242 }
243 return fStreamBuffer.bytesWritten();
244 }
245
246 bool read(void* data, size_t offset, size_t length) override {
247 if (length == 0) {
248 return true;
249 }
250
251 size_t sum;
252 if (!safe_add_to_size_t(offset, length, &sum)) {
253 return false;
254 }
255
256 return this->bufferMoreData(sum) && fStreamBuffer.read(data, offset, length);
257 }
258
259 SkMemoryStream* transferBuffer(size_t offset, size_t size) override {
yujieqin916de9f2016-01-25 08:26:16 -0800260 SkAutoTUnref<SkData> data(SkData::NewUninitialized(size));
261 if (offset > fStreamBuffer.bytesWritten()) {
262 // If the offset is not buffered, read from fStream directly and skip the buffering.
263 const size_t skipLength = offset - fStreamBuffer.bytesWritten();
264 if (fStream->skip(skipLength) != skipLength) {
265 return nullptr;
266 }
267 const size_t bytesRead = fStream->read(data->writable_data(), size);
268 if (bytesRead < size) {
269 data.reset(SkData::NewSubset(data.get(), 0, bytesRead));
270 }
271 } else {
272 const size_t alreadyBuffered = SkTMin(fStreamBuffer.bytesWritten() - offset, size);
273 if (alreadyBuffered > 0 &&
274 !fStreamBuffer.read(data->writable_data(), offset, alreadyBuffered)) {
275 return nullptr;
276 }
277
278 const size_t remaining = size - alreadyBuffered;
279 if (remaining) {
280 auto* dst = static_cast<uint8_t*>(data->writable_data()) + alreadyBuffered;
281 const size_t bytesRead = fStream->read(dst, remaining);
282 size_t newSize;
283 if (bytesRead < remaining) {
284 if (!safe_add_to_size_t(alreadyBuffered, bytesRead, &newSize)) {
285 return nullptr;
286 }
287 data.reset(SkData::NewSubset(data.get(), 0, newSize));
288 }
289 }
290 }
291 return new SkMemoryStream(data);
292 }
293
yujieqin916de9f2016-01-25 08:26:16 -0800294private:
295 // Note: if the newSize == kReadToEnd (0), this function will read to the end of stream.
296 bool bufferMoreData(size_t newSize) {
297 if (newSize == kReadToEnd) {
298 if (fWholeStreamRead) { // already read-to-end.
299 return true;
300 }
301
302 // TODO: optimize for the special case when the input is SkMemoryStream.
303 return SkStreamCopy(&fStreamBuffer, fStream.get());
304 }
305
306 if (newSize <= fStreamBuffer.bytesWritten()) { // already buffered to newSize
307 return true;
308 }
309 if (fWholeStreamRead) { // newSize is larger than the whole stream.
310 return false;
311 }
312
yujieqin22000d12016-02-02 08:09:07 -0800313 // Try to read at least 8192 bytes to avoid to many small reads.
314 const size_t kMinSizeToRead = 8192;
315 const size_t sizeRequested = newSize - fStreamBuffer.bytesWritten();
316 const size_t sizeToRead = SkTMax(kMinSizeToRead, sizeRequested);
317 SkAutoSTMalloc<kMinSizeToRead, uint8> tempBuffer(sizeToRead);
yujieqin916de9f2016-01-25 08:26:16 -0800318 const size_t bytesRead = fStream->read(tempBuffer.get(), sizeToRead);
yujieqin22000d12016-02-02 08:09:07 -0800319 if (bytesRead < sizeRequested) {
yujieqin916de9f2016-01-25 08:26:16 -0800320 return false;
321 }
322 return fStreamBuffer.write(tempBuffer.get(), bytesRead);
323 }
324
325 SkAutoTDelete<SkStream> fStream;
326 bool fWholeStreamRead;
327
yujieqinc04df212016-03-09 13:49:36 -0800328 // Use a size-limited stream to avoid holding too huge buffer.
329 SkRawLimitedDynamicMemoryWStream fStreamBuffer;
yujieqin916de9f2016-01-25 08:26:16 -0800330
331 const size_t kReadToEnd = 0;
332};
333
yujieqin9c7a8a42016-02-05 08:21:19 -0800334class SkRawAssetStream : public SkRawStream {
yujieqin916de9f2016-01-25 08:26:16 -0800335public:
yujieqin9c7a8a42016-02-05 08:21:19 -0800336 // Will take the ownership of the stream.
337 explicit SkRawAssetStream(SkStream* stream)
338 : fStream(stream)
339 {
340 // Only use SkRawAssetStream when the stream is an asset stream.
341 SkASSERT(is_asset_stream(*stream));
342 }
yujieqin916de9f2016-01-25 08:26:16 -0800343
yujieqin9c7a8a42016-02-05 08:21:19 -0800344 ~SkRawAssetStream() override {}
yujieqin916de9f2016-01-25 08:26:16 -0800345
yujieqin9c7a8a42016-02-05 08:21:19 -0800346 uint64 getLength() override {
347 return fStream->getLength();
348 }
349
350
351 bool read(void* data, size_t offset, size_t length) override {
352 if (length == 0) {
353 return true;
354 }
355
356 size_t sum;
357 if (!safe_add_to_size_t(offset, length, &sum)) {
358 return false;
359 }
360
361 return fStream->seek(offset) && (fStream->read(data, length) == length);
362 }
363
364 SkMemoryStream* transferBuffer(size_t offset, size_t size) override {
365 if (fStream->getLength() < offset) {
366 return nullptr;
367 }
368
369 size_t sum;
370 if (!safe_add_to_size_t(offset, size, &sum)) {
371 return nullptr;
372 }
373
374 // This will allow read less than the requested "size", because the JPEG codec wants to
375 // handle also a partial JPEG file.
376 const size_t bytesToRead = SkTMin(sum, fStream->getLength()) - offset;
377 if (bytesToRead == 0) {
378 return nullptr;
379 }
380
381 if (fStream->getMemoryBase()) { // directly copy if getMemoryBase() is available.
382 SkAutoTUnref<SkData> data(SkData::NewWithCopy(
383 static_cast<const uint8_t*>(fStream->getMemoryBase()) + offset, bytesToRead));
mtklein852f15d2016-03-17 10:51:27 -0700384 fStream.reset();
yujieqin9c7a8a42016-02-05 08:21:19 -0800385 return new SkMemoryStream(data);
386 } else {
387 SkAutoTUnref<SkData> data(SkData::NewUninitialized(bytesToRead));
388 if (!fStream->seek(offset)) {
389 return nullptr;
390 }
391 const size_t bytesRead = fStream->read(data->writable_data(), bytesToRead);
392 if (bytesRead < bytesToRead) {
393 data.reset(SkData::NewSubset(data.get(), 0, bytesRead));
394 }
395 return new SkMemoryStream(data);
396 }
397 }
398private:
399 SkAutoTDelete<SkStream> fStream;
400};
401
402class SkPiexStream : public ::piex::StreamInterface {
403public:
404 // Will NOT take the ownership of the stream.
405 explicit SkPiexStream(SkRawStream* stream) : fStream(stream) {}
406
407 ~SkPiexStream() override {}
408
409 ::piex::Error GetData(const size_t offset, const size_t length,
410 uint8* data) override {
411 return fStream->read(static_cast<void*>(data), offset, length) ?
412 ::piex::Error::kOk : ::piex::Error::kFail;
yujieqin916de9f2016-01-25 08:26:16 -0800413 }
414
415private:
yujieqin9c7a8a42016-02-05 08:21:19 -0800416 SkRawStream* fStream;
417};
418
419class SkDngStream : public dng_stream {
420public:
421 // Will NOT take the ownership of the stream.
422 SkDngStream(SkRawStream* stream) : fStream(stream) {}
423
424 ~SkDngStream() override {}
425
426 uint64 DoGetLength() override { return fStream->getLength(); }
427
428 void DoRead(void* data, uint32 count, uint64 offset) override {
429 size_t sum;
430 if (!safe_add_to_size_t(static_cast<uint64>(count), offset, &sum) ||
431 !fStream->read(data, static_cast<size_t>(offset), static_cast<size_t>(count))) {
432 ThrowReadFile();
433 }
434 }
435
436private:
437 SkRawStream* fStream;
yujieqin916de9f2016-01-25 08:26:16 -0800438};
439
440class SkDngImage {
441public:
ebrauer46d2aa82016-02-17 08:04:00 -0800442 /*
443 * Initializes the object with the information from Piex in a first attempt. This way it can
444 * save time and storage to obtain the DNG dimensions and color filter array (CFA) pattern
445 * which is essential for the demosaicing of the sensor image.
446 * Note: this will take the ownership of the stream.
447 */
yujieqin916de9f2016-01-25 08:26:16 -0800448 static SkDngImage* NewFromStream(SkRawStream* stream) {
449 SkAutoTDelete<SkDngImage> dngImage(new SkDngImage(stream));
yujieqind6215cf2016-03-10 05:15:49 -0800450 if (!dngImage->isTiffHeaderValid()) {
451 return nullptr;
452 }
453
ebrauer46d2aa82016-02-17 08:04:00 -0800454 if (!dngImage->initFromPiex()) {
455 if (!dngImage->readDng()) {
456 return nullptr;
457 }
yujieqin916de9f2016-01-25 08:26:16 -0800458 }
459
yujieqin916de9f2016-01-25 08:26:16 -0800460 return dngImage.release();
461 }
462
463 /*
464 * Renders the DNG image to the size. The DNG SDK only allows scaling close to integer factors
465 * down to 80 pixels on the short edge. The rendered image will be close to the specified size,
466 * but there is no guarantee that any of the edges will match the requested size. E.g.
467 * 100% size: 4000 x 3000
468 * requested size: 1600 x 1200
469 * returned size could be: 2000 x 1500
470 */
471 dng_image* render(int width, int height) {
472 if (!fHost || !fInfo || !fNegative || !fDngStream) {
473 if (!this->readDng()) {
474 return nullptr;
475 }
476 }
477
yujieqin916de9f2016-01-25 08:26:16 -0800478 // DNG SDK preserves the aspect ratio, so it only needs to know the longer dimension.
479 const int preferredSize = SkTMax(width, height);
480 try {
yujieqinf236ee42016-02-29 07:14:42 -0800481 // render() takes ownership of fHost, fInfo, fNegative and fDngStream when available.
482 SkAutoTDelete<dng_host> host(fHost.release());
483 SkAutoTDelete<dng_info> info(fInfo.release());
484 SkAutoTDelete<dng_negative> negative(fNegative.release());
485 SkAutoTDelete<dng_stream> dngStream(fDngStream.release());
486
yujieqin916de9f2016-01-25 08:26:16 -0800487 host->SetPreferredSize(preferredSize);
488 host->ValidateSizes();
489
490 negative->ReadStage1Image(*host, *dngStream, *info);
491
492 if (info->fMaskIndex != -1) {
493 negative->ReadTransparencyMask(*host, *dngStream, *info);
494 }
495
496 negative->ValidateRawImageDigest(*host);
497 if (negative->IsDamaged()) {
498 return nullptr;
499 }
500
501 const int32 kMosaicPlane = -1;
502 negative->BuildStage2Image(*host);
503 negative->BuildStage3Image(*host, kMosaicPlane);
504
505 dng_render render(*host, *negative);
506 render.SetFinalSpace(dng_space_sRGB::Get());
507 render.SetFinalPixelType(ttByte);
508
509 dng_point stage3_size = negative->Stage3Image()->Size();
510 render.SetMaximumSize(SkTMax(stage3_size.h, stage3_size.v));
511
512 return render.Render();
513 } catch (...) {
514 return nullptr;
515 }
516 }
517
518 const SkImageInfo& getImageInfo() const {
519 return fImageInfo;
520 }
521
522 bool isScalable() const {
523 return fIsScalable;
524 }
525
526 bool isXtransImage() const {
527 return fIsXtransImage;
528 }
529
530private:
yujieqind6215cf2016-03-10 05:15:49 -0800531 // Quick check if the image contains a valid TIFF header as requested by DNG format.
532 bool isTiffHeaderValid() const {
533 const size_t kHeaderSize = 4;
534 SkAutoSTMalloc<kHeaderSize, unsigned char> header(kHeaderSize);
535 if (!fStream->read(header.get(), 0 /* offset */, kHeaderSize)) {
536 return false;
537 }
538
539 // Check if the header is valid (endian info and magic number "42").
msarett0e6274f2016-03-21 08:04:40 -0700540 bool littleEndian;
541 if (!is_valid_endian_marker(header, &littleEndian)) {
542 return false;
543 }
544
545 return 0x2A == get_endian_short(header + 2, littleEndian);
yujieqind6215cf2016-03-10 05:15:49 -0800546 }
547
ebrauer46d2aa82016-02-17 08:04:00 -0800548 void init(const int width, const int height, const dng_point& cfaPatternSize) {
549 fImageInfo = SkImageInfo::Make(width, height, kN32_SkColorType, kOpaque_SkAlphaType);
550
551 // The DNG SDK scales only during demosaicing, so scaling is only possible when
552 // a mosaic info is available.
553 fIsScalable = cfaPatternSize.v != 0 && cfaPatternSize.h != 0;
554 fIsXtransImage = fIsScalable ? (cfaPatternSize.v == 6 && cfaPatternSize.h == 6) : false;
555 }
556
557 bool initFromPiex() {
558 // Does not take the ownership of rawStream.
559 SkPiexStream piexStream(fStream.get());
560 ::piex::PreviewImageData imageData;
561 if (::piex::IsRaw(&piexStream)
562 && ::piex::GetPreviewImageData(&piexStream, &imageData) == ::piex::Error::kOk)
563 {
yujieqind0e08852016-03-03 07:38:27 -0800564 // Verify the size information, as it is only optional information for PIEX.
565 if (imageData.full_width == 0 || imageData.full_height == 0) {
566 return false;
567 }
568
ebrauer46d2aa82016-02-17 08:04:00 -0800569 dng_point cfaPatternSize(imageData.cfa_pattern_dim[1], imageData.cfa_pattern_dim[0]);
570 this->init(static_cast<int>(imageData.full_width),
571 static_cast<int>(imageData.full_height), cfaPatternSize);
572 return true;
573 }
574 return false;
575 }
576
yujieqin916de9f2016-01-25 08:26:16 -0800577 bool readDng() {
yujieqin916de9f2016-01-25 08:26:16 -0800578 try {
yujieqinf236ee42016-02-29 07:14:42 -0800579 // Due to the limit of DNG SDK, we need to reset host and info.
580 fHost.reset(new SkDngHost(&fAllocator));
581 fInfo.reset(new dng_info);
582 fDngStream.reset(new SkDngStream(fStream));
583
yujieqin916de9f2016-01-25 08:26:16 -0800584 fHost->ValidateSizes();
585 fInfo->Parse(*fHost, *fDngStream);
586 fInfo->PostParse(*fHost);
587 if (!fInfo->IsValidDNG()) {
588 return false;
589 }
590
591 fNegative.reset(fHost->Make_dng_negative());
592 fNegative->Parse(*fHost, *fDngStream, *fInfo);
593 fNegative->PostParse(*fHost, *fDngStream, *fInfo);
594 fNegative->SynchronizeMetadata();
595
ebrauer46d2aa82016-02-17 08:04:00 -0800596 dng_point cfaPatternSize(0, 0);
597 if (fNegative->GetMosaicInfo() != nullptr) {
598 cfaPatternSize = fNegative->GetMosaicInfo()->fCFAPatternSize;
599 }
600 this->init(static_cast<int>(fNegative->DefaultCropSizeH().As_real64()),
601 static_cast<int>(fNegative->DefaultCropSizeV().As_real64()),
602 cfaPatternSize);
yujieqin916de9f2016-01-25 08:26:16 -0800603 return true;
604 } catch (...) {
yujieqin916de9f2016-01-25 08:26:16 -0800605 return false;
606 }
607 }
608
609 SkDngImage(SkRawStream* stream)
610 : fStream(stream) {}
611
612 SkDngMemoryAllocator fAllocator;
613 SkAutoTDelete<SkRawStream> fStream;
614 SkAutoTDelete<dng_host> fHost;
615 SkAutoTDelete<dng_info> fInfo;
616 SkAutoTDelete<dng_negative> fNegative;
617 SkAutoTDelete<dng_stream> fDngStream;
618
619 SkImageInfo fImageInfo;
620 bool fIsScalable;
621 bool fIsXtransImage;
622};
623
624/*
625 * Tries to handle the image with PIEX. If PIEX returns kOk and finds the preview image, create a
626 * SkJpegCodec. If PIEX returns kFail, then the file is invalid, return nullptr. In other cases,
627 * fallback to create SkRawCodec for DNG images.
628 */
629SkCodec* SkRawCodec::NewFromStream(SkStream* stream) {
yujieqin9c7a8a42016-02-05 08:21:19 -0800630 SkAutoTDelete<SkRawStream> rawStream;
631 if (is_asset_stream(*stream)) {
632 rawStream.reset(new SkRawAssetStream(stream));
633 } else {
634 rawStream.reset(new SkRawBufferedStream(stream));
635 }
636
637 // Does not take the ownership of rawStream.
638 SkPiexStream piexStream(rawStream.get());
yujieqin916de9f2016-01-25 08:26:16 -0800639 ::piex::PreviewImageData imageData;
yujieqin9c7a8a42016-02-05 08:21:19 -0800640 if (::piex::IsRaw(&piexStream)) {
641 ::piex::Error error = ::piex::GetPreviewImageData(&piexStream, &imageData);
yujieqin916de9f2016-01-25 08:26:16 -0800642
yujieqine34635d2016-04-14 07:04:00 -0700643 // Theoretically PIEX can return JPEG compressed image or uncompressed RGB image. We only
644 // handle the JPEG compressed preview image here.
645 if (error == ::piex::Error::kOk && imageData.preview.length > 0 &&
646 imageData.preview.format == ::piex::Image::kJpegCompressed)
647 {
yujieqin916de9f2016-01-25 08:26:16 -0800648 // transferBuffer() is destructive to the rawStream. Abandon the rawStream after this
649 // function call.
650 // FIXME: one may avoid the copy of memoryStream and use the buffered rawStream.
651 SkMemoryStream* memoryStream =
yujieqin2d172eb2016-02-23 06:49:38 -0800652 rawStream->transferBuffer(imageData.preview.offset, imageData.preview.length);
yujieqin916de9f2016-01-25 08:26:16 -0800653 return memoryStream ? SkJpegCodec::NewFromStream(memoryStream) : nullptr;
yujieqin916de9f2016-01-25 08:26:16 -0800654 } else if (error == ::piex::Error::kFail) {
655 return nullptr;
656 }
657 }
658
yujieqin9c7a8a42016-02-05 08:21:19 -0800659 // Takes the ownership of the rawStream.
yujieqin916de9f2016-01-25 08:26:16 -0800660 SkAutoTDelete<SkDngImage> dngImage(SkDngImage::NewFromStream(rawStream.release()));
661 if (!dngImage) {
662 return nullptr;
663 }
664
665 return new SkRawCodec(dngImage.release());
666}
667
668SkCodec::Result SkRawCodec::onGetPixels(const SkImageInfo& requestedInfo, void* dst,
669 size_t dstRowBytes, const Options& options,
670 SkPMColor ctable[], int* ctableCount,
671 int* rowsDecoded) {
672 if (!conversion_possible(requestedInfo, this->getInfo())) {
673 SkCodecPrintf("Error: cannot convert input type to output type.\n");
674 return kInvalidConversion;
675 }
676
677 SkAutoTDelete<SkSwizzler> swizzler(SkSwizzler::CreateSwizzler(
678 SkSwizzler::kRGB, nullptr, requestedInfo, options));
679 SkASSERT(swizzler);
680
681 const int width = requestedInfo.width();
682 const int height = requestedInfo.height();
683 SkAutoTDelete<dng_image> image(fDngImage->render(width, height));
684 if (!image) {
685 return kInvalidInput;
686 }
687
688 // Because the DNG SDK can not guarantee to render to requested size, we allow a small
689 // difference. Only the overlapping region will be converted.
690 const float maxDiffRatio = 1.03f;
691 const dng_point& imageSize = image->Size();
692 if (imageSize.h / width > maxDiffRatio || imageSize.h < width ||
693 imageSize.v / height > maxDiffRatio || imageSize.v < height) {
694 return SkCodec::kInvalidScale;
695 }
696
697 void* dstRow = dst;
yujieqin24716be2016-01-27 07:59:00 -0800698 SkAutoTMalloc<uint8_t> srcRow(width * 3);
yujieqin916de9f2016-01-25 08:26:16 -0800699
700 dng_pixel_buffer buffer;
701 buffer.fData = &srcRow[0];
702 buffer.fPlane = 0;
703 buffer.fPlanes = 3;
704 buffer.fColStep = buffer.fPlanes;
705 buffer.fPlaneStep = 1;
706 buffer.fPixelType = ttByte;
707 buffer.fPixelSize = sizeof(uint8_t);
scroggoe6459652016-01-30 10:06:11 -0800708 buffer.fRowStep = width * 3;
yujieqin916de9f2016-01-25 08:26:16 -0800709
710 for (int i = 0; i < height; ++i) {
711 buffer.fArea = dng_rect(i, 0, i + 1, width);
712
713 try {
714 image->Get(buffer, dng_image::edge_zero);
715 } catch (...) {
716 *rowsDecoded = i;
717 return kIncompleteInput;
718 }
719
720 swizzler->swizzle(dstRow, &srcRow[0]);
721 dstRow = SkTAddOffset<void>(dstRow, dstRowBytes);
722 }
723 return kSuccess;
724}
725
726SkISize SkRawCodec::onGetScaledDimensions(float desiredScale) const {
727 SkASSERT(desiredScale <= 1.f);
yujieqind0e08852016-03-03 07:38:27 -0800728
yujieqin916de9f2016-01-25 08:26:16 -0800729 const SkISize dim = this->getInfo().dimensions();
yujieqind0e08852016-03-03 07:38:27 -0800730 SkASSERT(dim.fWidth != 0 && dim.fHeight != 0);
731
yujieqin916de9f2016-01-25 08:26:16 -0800732 if (!fDngImage->isScalable()) {
733 return dim;
734 }
735
736 // Limits the minimum size to be 80 on the short edge.
yujieqin076d83d2016-01-27 08:25:53 -0800737 const float shortEdge = static_cast<float>(SkTMin(dim.fWidth, dim.fHeight));
yujieqin916de9f2016-01-25 08:26:16 -0800738 if (desiredScale < 80.f / shortEdge) {
739 desiredScale = 80.f / shortEdge;
740 }
741
742 // For Xtrans images, the integer-factor scaling does not support the half-size scaling case
743 // (stronger downscalings are fine). In this case, returns the factor "3" scaling instead.
744 if (fDngImage->isXtransImage() && desiredScale > 1.f / 3.f && desiredScale < 1.f) {
745 desiredScale = 1.f / 3.f;
746 }
747
748 // Round to integer-factors.
749 const float finalScale = std::floor(1.f/ desiredScale);
yujieqin076d83d2016-01-27 08:25:53 -0800750 return SkISize::Make(static_cast<int32_t>(std::floor(dim.fWidth / finalScale)),
751 static_cast<int32_t>(std::floor(dim.fHeight / finalScale)));
yujieqin916de9f2016-01-25 08:26:16 -0800752}
753
754bool SkRawCodec::onDimensionsSupported(const SkISize& dim) {
755 const SkISize fullDim = this->getInfo().dimensions();
yujieqin076d83d2016-01-27 08:25:53 -0800756 const float fullShortEdge = static_cast<float>(SkTMin(fullDim.fWidth, fullDim.fHeight));
757 const float shortEdge = static_cast<float>(SkTMin(dim.fWidth, dim.fHeight));
yujieqin916de9f2016-01-25 08:26:16 -0800758
759 SkISize sizeFloor = this->onGetScaledDimensions(1.f / std::floor(fullShortEdge / shortEdge));
760 SkISize sizeCeil = this->onGetScaledDimensions(1.f / std::ceil(fullShortEdge / shortEdge));
761 return sizeFloor == dim || sizeCeil == dim;
762}
763
764SkRawCodec::~SkRawCodec() {}
765
766SkRawCodec::SkRawCodec(SkDngImage* dngImage)
767 : INHERITED(dngImage->getImageInfo(), nullptr)
768 , fDngImage(dngImage) {}