blob: 609b0aef02b42761044c29d4085555cbb6975e35 [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:
218 const size_t kMaxStreamSize = 100 * 1024 * 1024; // 100MB
219
220 typedef SkDynamicMemoryWStream INHERITED;
221};
222
223// Note: the maximum buffer size is 100MB (limited by SkRawLimitedDynamicMemoryWStream).
yujieqin9c7a8a42016-02-05 08:21:19 -0800224class SkRawBufferedStream : public SkRawStream {
225public:
226 // Will take the ownership of the stream.
227 explicit SkRawBufferedStream(SkStream* stream)
228 : fStream(stream)
229 , fWholeStreamRead(false)
230 {
231 // Only use SkRawBufferedStream when the stream is not an asset stream.
232 SkASSERT(!is_asset_stream(*stream));
233 }
234
235 ~SkRawBufferedStream() override {}
236
237 uint64 getLength() override {
238 if (!this->bufferMoreData(kReadToEnd)) { // read whole stream
239 ThrowReadFile();
240 }
241 return fStreamBuffer.bytesWritten();
242 }
243
244 bool read(void* data, size_t offset, size_t length) override {
245 if (length == 0) {
246 return true;
247 }
248
249 size_t sum;
250 if (!safe_add_to_size_t(offset, length, &sum)) {
251 return false;
252 }
253
254 return this->bufferMoreData(sum) && fStreamBuffer.read(data, offset, length);
255 }
256
257 SkMemoryStream* transferBuffer(size_t offset, size_t size) override {
yujieqin916de9f2016-01-25 08:26:16 -0800258 SkAutoTUnref<SkData> data(SkData::NewUninitialized(size));
259 if (offset > fStreamBuffer.bytesWritten()) {
260 // If the offset is not buffered, read from fStream directly and skip the buffering.
261 const size_t skipLength = offset - fStreamBuffer.bytesWritten();
262 if (fStream->skip(skipLength) != skipLength) {
263 return nullptr;
264 }
265 const size_t bytesRead = fStream->read(data->writable_data(), size);
266 if (bytesRead < size) {
267 data.reset(SkData::NewSubset(data.get(), 0, bytesRead));
268 }
269 } else {
270 const size_t alreadyBuffered = SkTMin(fStreamBuffer.bytesWritten() - offset, size);
271 if (alreadyBuffered > 0 &&
272 !fStreamBuffer.read(data->writable_data(), offset, alreadyBuffered)) {
273 return nullptr;
274 }
275
276 const size_t remaining = size - alreadyBuffered;
277 if (remaining) {
278 auto* dst = static_cast<uint8_t*>(data->writable_data()) + alreadyBuffered;
279 const size_t bytesRead = fStream->read(dst, remaining);
280 size_t newSize;
281 if (bytesRead < remaining) {
282 if (!safe_add_to_size_t(alreadyBuffered, bytesRead, &newSize)) {
283 return nullptr;
284 }
285 data.reset(SkData::NewSubset(data.get(), 0, newSize));
286 }
287 }
288 }
289 return new SkMemoryStream(data);
290 }
291
yujieqin916de9f2016-01-25 08:26:16 -0800292private:
293 // Note: if the newSize == kReadToEnd (0), this function will read to the end of stream.
294 bool bufferMoreData(size_t newSize) {
295 if (newSize == kReadToEnd) {
296 if (fWholeStreamRead) { // already read-to-end.
297 return true;
298 }
299
300 // TODO: optimize for the special case when the input is SkMemoryStream.
301 return SkStreamCopy(&fStreamBuffer, fStream.get());
302 }
303
304 if (newSize <= fStreamBuffer.bytesWritten()) { // already buffered to newSize
305 return true;
306 }
307 if (fWholeStreamRead) { // newSize is larger than the whole stream.
308 return false;
309 }
310
yujieqin22000d12016-02-02 08:09:07 -0800311 // Try to read at least 8192 bytes to avoid to many small reads.
312 const size_t kMinSizeToRead = 8192;
313 const size_t sizeRequested = newSize - fStreamBuffer.bytesWritten();
314 const size_t sizeToRead = SkTMax(kMinSizeToRead, sizeRequested);
315 SkAutoSTMalloc<kMinSizeToRead, uint8> tempBuffer(sizeToRead);
yujieqin916de9f2016-01-25 08:26:16 -0800316 const size_t bytesRead = fStream->read(tempBuffer.get(), sizeToRead);
yujieqin22000d12016-02-02 08:09:07 -0800317 if (bytesRead < sizeRequested) {
yujieqin916de9f2016-01-25 08:26:16 -0800318 return false;
319 }
320 return fStreamBuffer.write(tempBuffer.get(), bytesRead);
321 }
322
323 SkAutoTDelete<SkStream> fStream;
324 bool fWholeStreamRead;
325
yujieqinc04df212016-03-09 13:49:36 -0800326 // Use a size-limited stream to avoid holding too huge buffer.
327 SkRawLimitedDynamicMemoryWStream fStreamBuffer;
yujieqin916de9f2016-01-25 08:26:16 -0800328
329 const size_t kReadToEnd = 0;
330};
331
yujieqin9c7a8a42016-02-05 08:21:19 -0800332class SkRawAssetStream : public SkRawStream {
yujieqin916de9f2016-01-25 08:26:16 -0800333public:
yujieqin9c7a8a42016-02-05 08:21:19 -0800334 // Will take the ownership of the stream.
335 explicit SkRawAssetStream(SkStream* stream)
336 : fStream(stream)
337 {
338 // Only use SkRawAssetStream when the stream is an asset stream.
339 SkASSERT(is_asset_stream(*stream));
340 }
yujieqin916de9f2016-01-25 08:26:16 -0800341
yujieqin9c7a8a42016-02-05 08:21:19 -0800342 ~SkRawAssetStream() override {}
yujieqin916de9f2016-01-25 08:26:16 -0800343
yujieqin9c7a8a42016-02-05 08:21:19 -0800344 uint64 getLength() override {
345 return fStream->getLength();
346 }
347
348
349 bool read(void* data, size_t offset, size_t length) override {
350 if (length == 0) {
351 return true;
352 }
353
354 size_t sum;
355 if (!safe_add_to_size_t(offset, length, &sum)) {
356 return false;
357 }
358
359 return fStream->seek(offset) && (fStream->read(data, length) == length);
360 }
361
362 SkMemoryStream* transferBuffer(size_t offset, size_t size) override {
363 if (fStream->getLength() < offset) {
364 return nullptr;
365 }
366
367 size_t sum;
368 if (!safe_add_to_size_t(offset, size, &sum)) {
369 return nullptr;
370 }
371
372 // This will allow read less than the requested "size", because the JPEG codec wants to
373 // handle also a partial JPEG file.
374 const size_t bytesToRead = SkTMin(sum, fStream->getLength()) - offset;
375 if (bytesToRead == 0) {
376 return nullptr;
377 }
378
379 if (fStream->getMemoryBase()) { // directly copy if getMemoryBase() is available.
380 SkAutoTUnref<SkData> data(SkData::NewWithCopy(
381 static_cast<const uint8_t*>(fStream->getMemoryBase()) + offset, bytesToRead));
382 fStream.free();
383 return new SkMemoryStream(data);
384 } else {
385 SkAutoTUnref<SkData> data(SkData::NewUninitialized(bytesToRead));
386 if (!fStream->seek(offset)) {
387 return nullptr;
388 }
389 const size_t bytesRead = fStream->read(data->writable_data(), bytesToRead);
390 if (bytesRead < bytesToRead) {
391 data.reset(SkData::NewSubset(data.get(), 0, bytesRead));
392 }
393 return new SkMemoryStream(data);
394 }
395 }
396private:
397 SkAutoTDelete<SkStream> fStream;
398};
399
400class SkPiexStream : public ::piex::StreamInterface {
401public:
402 // Will NOT take the ownership of the stream.
403 explicit SkPiexStream(SkRawStream* stream) : fStream(stream) {}
404
405 ~SkPiexStream() override {}
406
407 ::piex::Error GetData(const size_t offset, const size_t length,
408 uint8* data) override {
409 return fStream->read(static_cast<void*>(data), offset, length) ?
410 ::piex::Error::kOk : ::piex::Error::kFail;
yujieqin916de9f2016-01-25 08:26:16 -0800411 }
412
413private:
yujieqin9c7a8a42016-02-05 08:21:19 -0800414 SkRawStream* fStream;
415};
416
417class SkDngStream : public dng_stream {
418public:
419 // Will NOT take the ownership of the stream.
420 SkDngStream(SkRawStream* stream) : fStream(stream) {}
421
422 ~SkDngStream() override {}
423
424 uint64 DoGetLength() override { return fStream->getLength(); }
425
426 void DoRead(void* data, uint32 count, uint64 offset) override {
427 size_t sum;
428 if (!safe_add_to_size_t(static_cast<uint64>(count), offset, &sum) ||
429 !fStream->read(data, static_cast<size_t>(offset), static_cast<size_t>(count))) {
430 ThrowReadFile();
431 }
432 }
433
434private:
435 SkRawStream* fStream;
yujieqin916de9f2016-01-25 08:26:16 -0800436};
437
438class SkDngImage {
439public:
ebrauer46d2aa82016-02-17 08:04:00 -0800440 /*
441 * Initializes the object with the information from Piex in a first attempt. This way it can
442 * save time and storage to obtain the DNG dimensions and color filter array (CFA) pattern
443 * which is essential for the demosaicing of the sensor image.
444 * Note: this will take the ownership of the stream.
445 */
yujieqin916de9f2016-01-25 08:26:16 -0800446 static SkDngImage* NewFromStream(SkRawStream* stream) {
447 SkAutoTDelete<SkDngImage> dngImage(new SkDngImage(stream));
ebrauer46d2aa82016-02-17 08:04:00 -0800448 if (!dngImage->initFromPiex()) {
449 if (!dngImage->readDng()) {
450 return nullptr;
451 }
yujieqin916de9f2016-01-25 08:26:16 -0800452 }
453
yujieqin916de9f2016-01-25 08:26:16 -0800454 return dngImage.release();
455 }
456
457 /*
458 * Renders the DNG image to the size. The DNG SDK only allows scaling close to integer factors
459 * down to 80 pixels on the short edge. The rendered image will be close to the specified size,
460 * but there is no guarantee that any of the edges will match the requested size. E.g.
461 * 100% size: 4000 x 3000
462 * requested size: 1600 x 1200
463 * returned size could be: 2000 x 1500
464 */
465 dng_image* render(int width, int height) {
466 if (!fHost || !fInfo || !fNegative || !fDngStream) {
467 if (!this->readDng()) {
468 return nullptr;
469 }
470 }
471
yujieqin916de9f2016-01-25 08:26:16 -0800472 // DNG SDK preserves the aspect ratio, so it only needs to know the longer dimension.
473 const int preferredSize = SkTMax(width, height);
474 try {
yujieqinf236ee42016-02-29 07:14:42 -0800475 // render() takes ownership of fHost, fInfo, fNegative and fDngStream when available.
476 SkAutoTDelete<dng_host> host(fHost.release());
477 SkAutoTDelete<dng_info> info(fInfo.release());
478 SkAutoTDelete<dng_negative> negative(fNegative.release());
479 SkAutoTDelete<dng_stream> dngStream(fDngStream.release());
480
yujieqin916de9f2016-01-25 08:26:16 -0800481 host->SetPreferredSize(preferredSize);
482 host->ValidateSizes();
483
484 negative->ReadStage1Image(*host, *dngStream, *info);
485
486 if (info->fMaskIndex != -1) {
487 negative->ReadTransparencyMask(*host, *dngStream, *info);
488 }
489
490 negative->ValidateRawImageDigest(*host);
491 if (negative->IsDamaged()) {
492 return nullptr;
493 }
494
495 const int32 kMosaicPlane = -1;
496 negative->BuildStage2Image(*host);
497 negative->BuildStage3Image(*host, kMosaicPlane);
498
499 dng_render render(*host, *negative);
500 render.SetFinalSpace(dng_space_sRGB::Get());
501 render.SetFinalPixelType(ttByte);
502
503 dng_point stage3_size = negative->Stage3Image()->Size();
504 render.SetMaximumSize(SkTMax(stage3_size.h, stage3_size.v));
505
506 return render.Render();
507 } catch (...) {
508 return nullptr;
509 }
510 }
511
512 const SkImageInfo& getImageInfo() const {
513 return fImageInfo;
514 }
515
516 bool isScalable() const {
517 return fIsScalable;
518 }
519
520 bool isXtransImage() const {
521 return fIsXtransImage;
522 }
523
524private:
ebrauer46d2aa82016-02-17 08:04:00 -0800525 void init(const int width, const int height, const dng_point& cfaPatternSize) {
526 fImageInfo = SkImageInfo::Make(width, height, kN32_SkColorType, kOpaque_SkAlphaType);
527
528 // The DNG SDK scales only during demosaicing, so scaling is only possible when
529 // a mosaic info is available.
530 fIsScalable = cfaPatternSize.v != 0 && cfaPatternSize.h != 0;
531 fIsXtransImage = fIsScalable ? (cfaPatternSize.v == 6 && cfaPatternSize.h == 6) : false;
532 }
533
534 bool initFromPiex() {
535 // Does not take the ownership of rawStream.
536 SkPiexStream piexStream(fStream.get());
537 ::piex::PreviewImageData imageData;
538 if (::piex::IsRaw(&piexStream)
539 && ::piex::GetPreviewImageData(&piexStream, &imageData) == ::piex::Error::kOk)
540 {
yujieqind0e08852016-03-03 07:38:27 -0800541 // Verify the size information, as it is only optional information for PIEX.
542 if (imageData.full_width == 0 || imageData.full_height == 0) {
543 return false;
544 }
545
ebrauer46d2aa82016-02-17 08:04:00 -0800546 dng_point cfaPatternSize(imageData.cfa_pattern_dim[1], imageData.cfa_pattern_dim[0]);
547 this->init(static_cast<int>(imageData.full_width),
548 static_cast<int>(imageData.full_height), cfaPatternSize);
549 return true;
550 }
551 return false;
552 }
553
yujieqin916de9f2016-01-25 08:26:16 -0800554 bool readDng() {
yujieqin916de9f2016-01-25 08:26:16 -0800555 try {
yujieqinf236ee42016-02-29 07:14:42 -0800556 // Due to the limit of DNG SDK, we need to reset host and info.
557 fHost.reset(new SkDngHost(&fAllocator));
558 fInfo.reset(new dng_info);
559 fDngStream.reset(new SkDngStream(fStream));
560
yujieqin916de9f2016-01-25 08:26:16 -0800561 fHost->ValidateSizes();
562 fInfo->Parse(*fHost, *fDngStream);
563 fInfo->PostParse(*fHost);
564 if (!fInfo->IsValidDNG()) {
565 return false;
566 }
567
568 fNegative.reset(fHost->Make_dng_negative());
569 fNegative->Parse(*fHost, *fDngStream, *fInfo);
570 fNegative->PostParse(*fHost, *fDngStream, *fInfo);
571 fNegative->SynchronizeMetadata();
572
ebrauer46d2aa82016-02-17 08:04:00 -0800573 dng_point cfaPatternSize(0, 0);
574 if (fNegative->GetMosaicInfo() != nullptr) {
575 cfaPatternSize = fNegative->GetMosaicInfo()->fCFAPatternSize;
576 }
577 this->init(static_cast<int>(fNegative->DefaultCropSizeH().As_real64()),
578 static_cast<int>(fNegative->DefaultCropSizeV().As_real64()),
579 cfaPatternSize);
yujieqin916de9f2016-01-25 08:26:16 -0800580 return true;
581 } catch (...) {
yujieqin916de9f2016-01-25 08:26:16 -0800582 return false;
583 }
584 }
585
586 SkDngImage(SkRawStream* stream)
587 : fStream(stream) {}
588
589 SkDngMemoryAllocator fAllocator;
590 SkAutoTDelete<SkRawStream> fStream;
591 SkAutoTDelete<dng_host> fHost;
592 SkAutoTDelete<dng_info> fInfo;
593 SkAutoTDelete<dng_negative> fNegative;
594 SkAutoTDelete<dng_stream> fDngStream;
595
596 SkImageInfo fImageInfo;
597 bool fIsScalable;
598 bool fIsXtransImage;
599};
600
601/*
602 * Tries to handle the image with PIEX. If PIEX returns kOk and finds the preview image, create a
603 * SkJpegCodec. If PIEX returns kFail, then the file is invalid, return nullptr. In other cases,
604 * fallback to create SkRawCodec for DNG images.
605 */
606SkCodec* SkRawCodec::NewFromStream(SkStream* stream) {
yujieqin9c7a8a42016-02-05 08:21:19 -0800607 SkAutoTDelete<SkRawStream> rawStream;
608 if (is_asset_stream(*stream)) {
609 rawStream.reset(new SkRawAssetStream(stream));
610 } else {
611 rawStream.reset(new SkRawBufferedStream(stream));
612 }
613
614 // Does not take the ownership of rawStream.
615 SkPiexStream piexStream(rawStream.get());
yujieqin916de9f2016-01-25 08:26:16 -0800616 ::piex::PreviewImageData imageData;
yujieqin9c7a8a42016-02-05 08:21:19 -0800617 if (::piex::IsRaw(&piexStream)) {
618 ::piex::Error error = ::piex::GetPreviewImageData(&piexStream, &imageData);
yujieqin916de9f2016-01-25 08:26:16 -0800619
yujieqin2d172eb2016-02-23 06:49:38 -0800620 if (error == ::piex::Error::kOk && imageData.preview.length > 0) {
yujieqin916de9f2016-01-25 08:26:16 -0800621 // transferBuffer() is destructive to the rawStream. Abandon the rawStream after this
622 // function call.
623 // FIXME: one may avoid the copy of memoryStream and use the buffered rawStream.
624 SkMemoryStream* memoryStream =
yujieqin2d172eb2016-02-23 06:49:38 -0800625 rawStream->transferBuffer(imageData.preview.offset, imageData.preview.length);
yujieqin916de9f2016-01-25 08:26:16 -0800626 return memoryStream ? SkJpegCodec::NewFromStream(memoryStream) : nullptr;
yujieqin916de9f2016-01-25 08:26:16 -0800627 } else if (error == ::piex::Error::kFail) {
628 return nullptr;
629 }
630 }
631
yujieqin9c7a8a42016-02-05 08:21:19 -0800632 // Takes the ownership of the rawStream.
yujieqin916de9f2016-01-25 08:26:16 -0800633 SkAutoTDelete<SkDngImage> dngImage(SkDngImage::NewFromStream(rawStream.release()));
634 if (!dngImage) {
635 return nullptr;
636 }
637
638 return new SkRawCodec(dngImage.release());
639}
640
641SkCodec::Result SkRawCodec::onGetPixels(const SkImageInfo& requestedInfo, void* dst,
642 size_t dstRowBytes, const Options& options,
643 SkPMColor ctable[], int* ctableCount,
644 int* rowsDecoded) {
645 if (!conversion_possible(requestedInfo, this->getInfo())) {
646 SkCodecPrintf("Error: cannot convert input type to output type.\n");
647 return kInvalidConversion;
648 }
649
650 SkAutoTDelete<SkSwizzler> swizzler(SkSwizzler::CreateSwizzler(
651 SkSwizzler::kRGB, nullptr, requestedInfo, options));
652 SkASSERT(swizzler);
653
654 const int width = requestedInfo.width();
655 const int height = requestedInfo.height();
656 SkAutoTDelete<dng_image> image(fDngImage->render(width, height));
657 if (!image) {
658 return kInvalidInput;
659 }
660
661 // Because the DNG SDK can not guarantee to render to requested size, we allow a small
662 // difference. Only the overlapping region will be converted.
663 const float maxDiffRatio = 1.03f;
664 const dng_point& imageSize = image->Size();
665 if (imageSize.h / width > maxDiffRatio || imageSize.h < width ||
666 imageSize.v / height > maxDiffRatio || imageSize.v < height) {
667 return SkCodec::kInvalidScale;
668 }
669
670 void* dstRow = dst;
yujieqin24716be2016-01-27 07:59:00 -0800671 SkAutoTMalloc<uint8_t> srcRow(width * 3);
yujieqin916de9f2016-01-25 08:26:16 -0800672
673 dng_pixel_buffer buffer;
674 buffer.fData = &srcRow[0];
675 buffer.fPlane = 0;
676 buffer.fPlanes = 3;
677 buffer.fColStep = buffer.fPlanes;
678 buffer.fPlaneStep = 1;
679 buffer.fPixelType = ttByte;
680 buffer.fPixelSize = sizeof(uint8_t);
scroggoe6459652016-01-30 10:06:11 -0800681 buffer.fRowStep = width * 3;
yujieqin916de9f2016-01-25 08:26:16 -0800682
683 for (int i = 0; i < height; ++i) {
684 buffer.fArea = dng_rect(i, 0, i + 1, width);
685
686 try {
687 image->Get(buffer, dng_image::edge_zero);
688 } catch (...) {
689 *rowsDecoded = i;
690 return kIncompleteInput;
691 }
692
693 swizzler->swizzle(dstRow, &srcRow[0]);
694 dstRow = SkTAddOffset<void>(dstRow, dstRowBytes);
695 }
696 return kSuccess;
697}
698
699SkISize SkRawCodec::onGetScaledDimensions(float desiredScale) const {
700 SkASSERT(desiredScale <= 1.f);
yujieqind0e08852016-03-03 07:38:27 -0800701
yujieqin916de9f2016-01-25 08:26:16 -0800702 const SkISize dim = this->getInfo().dimensions();
yujieqind0e08852016-03-03 07:38:27 -0800703 SkASSERT(dim.fWidth != 0 && dim.fHeight != 0);
704
yujieqin916de9f2016-01-25 08:26:16 -0800705 if (!fDngImage->isScalable()) {
706 return dim;
707 }
708
709 // Limits the minimum size to be 80 on the short edge.
yujieqin076d83d2016-01-27 08:25:53 -0800710 const float shortEdge = static_cast<float>(SkTMin(dim.fWidth, dim.fHeight));
yujieqin916de9f2016-01-25 08:26:16 -0800711 if (desiredScale < 80.f / shortEdge) {
712 desiredScale = 80.f / shortEdge;
713 }
714
715 // For Xtrans images, the integer-factor scaling does not support the half-size scaling case
716 // (stronger downscalings are fine). In this case, returns the factor "3" scaling instead.
717 if (fDngImage->isXtransImage() && desiredScale > 1.f / 3.f && desiredScale < 1.f) {
718 desiredScale = 1.f / 3.f;
719 }
720
721 // Round to integer-factors.
722 const float finalScale = std::floor(1.f/ desiredScale);
yujieqin076d83d2016-01-27 08:25:53 -0800723 return SkISize::Make(static_cast<int32_t>(std::floor(dim.fWidth / finalScale)),
724 static_cast<int32_t>(std::floor(dim.fHeight / finalScale)));
yujieqin916de9f2016-01-25 08:26:16 -0800725}
726
727bool SkRawCodec::onDimensionsSupported(const SkISize& dim) {
728 const SkISize fullDim = this->getInfo().dimensions();
yujieqin076d83d2016-01-27 08:25:53 -0800729 const float fullShortEdge = static_cast<float>(SkTMin(fullDim.fWidth, fullDim.fHeight));
730 const float shortEdge = static_cast<float>(SkTMin(dim.fWidth, dim.fHeight));
yujieqin916de9f2016-01-25 08:26:16 -0800731
732 SkISize sizeFloor = this->onGetScaledDimensions(1.f / std::floor(fullShortEdge / shortEdge));
733 SkISize sizeCeil = this->onGetScaledDimensions(1.f / std::ceil(fullShortEdge / shortEdge));
734 return sizeFloor == dim || sizeCeil == dim;
735}
736
737SkRawCodec::~SkRawCodec() {}
738
739SkRawCodec::SkRawCodec(SkDngImage* dngImage)
740 : INHERITED(dngImage->getImageInfo(), nullptr)
741 , fDngImage(dngImage) {}