blob: 9d0fb1cb251b288bf83ce279ff3d1440ed945551 [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
202class SkRawBufferedStream : public SkRawStream {
203public:
204 // Will take the ownership of the stream.
205 explicit SkRawBufferedStream(SkStream* stream)
206 : fStream(stream)
207 , fWholeStreamRead(false)
208 {
209 // Only use SkRawBufferedStream when the stream is not an asset stream.
210 SkASSERT(!is_asset_stream(*stream));
211 }
212
213 ~SkRawBufferedStream() override {}
214
215 uint64 getLength() override {
216 if (!this->bufferMoreData(kReadToEnd)) { // read whole stream
217 ThrowReadFile();
218 }
219 return fStreamBuffer.bytesWritten();
220 }
221
222 bool read(void* data, size_t offset, size_t length) override {
223 if (length == 0) {
224 return true;
225 }
226
227 size_t sum;
228 if (!safe_add_to_size_t(offset, length, &sum)) {
229 return false;
230 }
231
232 return this->bufferMoreData(sum) && fStreamBuffer.read(data, offset, length);
233 }
234
235 SkMemoryStream* transferBuffer(size_t offset, size_t size) override {
yujieqin916de9f2016-01-25 08:26:16 -0800236 SkAutoTUnref<SkData> data(SkData::NewUninitialized(size));
237 if (offset > fStreamBuffer.bytesWritten()) {
238 // If the offset is not buffered, read from fStream directly and skip the buffering.
239 const size_t skipLength = offset - fStreamBuffer.bytesWritten();
240 if (fStream->skip(skipLength) != skipLength) {
241 return nullptr;
242 }
243 const size_t bytesRead = fStream->read(data->writable_data(), size);
244 if (bytesRead < size) {
245 data.reset(SkData::NewSubset(data.get(), 0, bytesRead));
246 }
247 } else {
248 const size_t alreadyBuffered = SkTMin(fStreamBuffer.bytesWritten() - offset, size);
249 if (alreadyBuffered > 0 &&
250 !fStreamBuffer.read(data->writable_data(), offset, alreadyBuffered)) {
251 return nullptr;
252 }
253
254 const size_t remaining = size - alreadyBuffered;
255 if (remaining) {
256 auto* dst = static_cast<uint8_t*>(data->writable_data()) + alreadyBuffered;
257 const size_t bytesRead = fStream->read(dst, remaining);
258 size_t newSize;
259 if (bytesRead < remaining) {
260 if (!safe_add_to_size_t(alreadyBuffered, bytesRead, &newSize)) {
261 return nullptr;
262 }
263 data.reset(SkData::NewSubset(data.get(), 0, newSize));
264 }
265 }
266 }
267 return new SkMemoryStream(data);
268 }
269
yujieqin916de9f2016-01-25 08:26:16 -0800270private:
271 // Note: if the newSize == kReadToEnd (0), this function will read to the end of stream.
272 bool bufferMoreData(size_t newSize) {
273 if (newSize == kReadToEnd) {
274 if (fWholeStreamRead) { // already read-to-end.
275 return true;
276 }
277
278 // TODO: optimize for the special case when the input is SkMemoryStream.
279 return SkStreamCopy(&fStreamBuffer, fStream.get());
280 }
281
282 if (newSize <= fStreamBuffer.bytesWritten()) { // already buffered to newSize
283 return true;
284 }
285 if (fWholeStreamRead) { // newSize is larger than the whole stream.
286 return false;
287 }
288
yujieqin22000d12016-02-02 08:09:07 -0800289 // Try to read at least 8192 bytes to avoid to many small reads.
290 const size_t kMinSizeToRead = 8192;
291 const size_t sizeRequested = newSize - fStreamBuffer.bytesWritten();
292 const size_t sizeToRead = SkTMax(kMinSizeToRead, sizeRequested);
293 SkAutoSTMalloc<kMinSizeToRead, uint8> tempBuffer(sizeToRead);
yujieqin916de9f2016-01-25 08:26:16 -0800294 const size_t bytesRead = fStream->read(tempBuffer.get(), sizeToRead);
yujieqin22000d12016-02-02 08:09:07 -0800295 if (bytesRead < sizeRequested) {
yujieqin916de9f2016-01-25 08:26:16 -0800296 return false;
297 }
298 return fStreamBuffer.write(tempBuffer.get(), bytesRead);
299 }
300
301 SkAutoTDelete<SkStream> fStream;
302 bool fWholeStreamRead;
303
304 SkDynamicMemoryWStream fStreamBuffer;
305
306 const size_t kReadToEnd = 0;
307};
308
yujieqin9c7a8a42016-02-05 08:21:19 -0800309class SkRawAssetStream : public SkRawStream {
yujieqin916de9f2016-01-25 08:26:16 -0800310public:
yujieqin9c7a8a42016-02-05 08:21:19 -0800311 // Will take the ownership of the stream.
312 explicit SkRawAssetStream(SkStream* stream)
313 : fStream(stream)
314 {
315 // Only use SkRawAssetStream when the stream is an asset stream.
316 SkASSERT(is_asset_stream(*stream));
317 }
yujieqin916de9f2016-01-25 08:26:16 -0800318
yujieqin9c7a8a42016-02-05 08:21:19 -0800319 ~SkRawAssetStream() override {}
yujieqin916de9f2016-01-25 08:26:16 -0800320
yujieqin9c7a8a42016-02-05 08:21:19 -0800321 uint64 getLength() override {
322 return fStream->getLength();
323 }
324
325
326 bool read(void* data, size_t offset, size_t length) override {
327 if (length == 0) {
328 return true;
329 }
330
331 size_t sum;
332 if (!safe_add_to_size_t(offset, length, &sum)) {
333 return false;
334 }
335
336 return fStream->seek(offset) && (fStream->read(data, length) == length);
337 }
338
339 SkMemoryStream* transferBuffer(size_t offset, size_t size) override {
340 if (fStream->getLength() < offset) {
341 return nullptr;
342 }
343
344 size_t sum;
345 if (!safe_add_to_size_t(offset, size, &sum)) {
346 return nullptr;
347 }
348
349 // This will allow read less than the requested "size", because the JPEG codec wants to
350 // handle also a partial JPEG file.
351 const size_t bytesToRead = SkTMin(sum, fStream->getLength()) - offset;
352 if (bytesToRead == 0) {
353 return nullptr;
354 }
355
356 if (fStream->getMemoryBase()) { // directly copy if getMemoryBase() is available.
357 SkAutoTUnref<SkData> data(SkData::NewWithCopy(
358 static_cast<const uint8_t*>(fStream->getMemoryBase()) + offset, bytesToRead));
359 fStream.free();
360 return new SkMemoryStream(data);
361 } else {
362 SkAutoTUnref<SkData> data(SkData::NewUninitialized(bytesToRead));
363 if (!fStream->seek(offset)) {
364 return nullptr;
365 }
366 const size_t bytesRead = fStream->read(data->writable_data(), bytesToRead);
367 if (bytesRead < bytesToRead) {
368 data.reset(SkData::NewSubset(data.get(), 0, bytesRead));
369 }
370 return new SkMemoryStream(data);
371 }
372 }
373private:
374 SkAutoTDelete<SkStream> fStream;
375};
376
377class SkPiexStream : public ::piex::StreamInterface {
378public:
379 // Will NOT take the ownership of the stream.
380 explicit SkPiexStream(SkRawStream* stream) : fStream(stream) {}
381
382 ~SkPiexStream() override {}
383
384 ::piex::Error GetData(const size_t offset, const size_t length,
385 uint8* data) override {
386 return fStream->read(static_cast<void*>(data), offset, length) ?
387 ::piex::Error::kOk : ::piex::Error::kFail;
yujieqin916de9f2016-01-25 08:26:16 -0800388 }
389
390private:
yujieqin9c7a8a42016-02-05 08:21:19 -0800391 SkRawStream* fStream;
392};
393
394class SkDngStream : public dng_stream {
395public:
396 // Will NOT take the ownership of the stream.
397 SkDngStream(SkRawStream* stream) : fStream(stream) {}
398
399 ~SkDngStream() override {}
400
401 uint64 DoGetLength() override { return fStream->getLength(); }
402
403 void DoRead(void* data, uint32 count, uint64 offset) override {
404 size_t sum;
405 if (!safe_add_to_size_t(static_cast<uint64>(count), offset, &sum) ||
406 !fStream->read(data, static_cast<size_t>(offset), static_cast<size_t>(count))) {
407 ThrowReadFile();
408 }
409 }
410
411private:
412 SkRawStream* fStream;
yujieqin916de9f2016-01-25 08:26:16 -0800413};
414
415class SkDngImage {
416public:
ebrauer46d2aa82016-02-17 08:04:00 -0800417 /*
418 * Initializes the object with the information from Piex in a first attempt. This way it can
419 * save time and storage to obtain the DNG dimensions and color filter array (CFA) pattern
420 * which is essential for the demosaicing of the sensor image.
421 * Note: this will take the ownership of the stream.
422 */
yujieqin916de9f2016-01-25 08:26:16 -0800423 static SkDngImage* NewFromStream(SkRawStream* stream) {
424 SkAutoTDelete<SkDngImage> dngImage(new SkDngImage(stream));
ebrauer46d2aa82016-02-17 08:04:00 -0800425 if (!dngImage->initFromPiex()) {
426 if (!dngImage->readDng()) {
427 return nullptr;
428 }
yujieqin916de9f2016-01-25 08:26:16 -0800429 }
430
yujieqin916de9f2016-01-25 08:26:16 -0800431 return dngImage.release();
432 }
433
434 /*
435 * Renders the DNG image to the size. The DNG SDK only allows scaling close to integer factors
436 * down to 80 pixels on the short edge. The rendered image will be close to the specified size,
437 * but there is no guarantee that any of the edges will match the requested size. E.g.
438 * 100% size: 4000 x 3000
439 * requested size: 1600 x 1200
440 * returned size could be: 2000 x 1500
441 */
442 dng_image* render(int width, int height) {
443 if (!fHost || !fInfo || !fNegative || !fDngStream) {
444 if (!this->readDng()) {
445 return nullptr;
446 }
447 }
448
yujieqin916de9f2016-01-25 08:26:16 -0800449 // DNG SDK preserves the aspect ratio, so it only needs to know the longer dimension.
450 const int preferredSize = SkTMax(width, height);
451 try {
yujieqinf236ee42016-02-29 07:14:42 -0800452 // render() takes ownership of fHost, fInfo, fNegative and fDngStream when available.
453 SkAutoTDelete<dng_host> host(fHost.release());
454 SkAutoTDelete<dng_info> info(fInfo.release());
455 SkAutoTDelete<dng_negative> negative(fNegative.release());
456 SkAutoTDelete<dng_stream> dngStream(fDngStream.release());
457
yujieqin916de9f2016-01-25 08:26:16 -0800458 host->SetPreferredSize(preferredSize);
459 host->ValidateSizes();
460
461 negative->ReadStage1Image(*host, *dngStream, *info);
462
463 if (info->fMaskIndex != -1) {
464 negative->ReadTransparencyMask(*host, *dngStream, *info);
465 }
466
467 negative->ValidateRawImageDigest(*host);
468 if (negative->IsDamaged()) {
469 return nullptr;
470 }
471
472 const int32 kMosaicPlane = -1;
473 negative->BuildStage2Image(*host);
474 negative->BuildStage3Image(*host, kMosaicPlane);
475
476 dng_render render(*host, *negative);
477 render.SetFinalSpace(dng_space_sRGB::Get());
478 render.SetFinalPixelType(ttByte);
479
480 dng_point stage3_size = negative->Stage3Image()->Size();
481 render.SetMaximumSize(SkTMax(stage3_size.h, stage3_size.v));
482
483 return render.Render();
484 } catch (...) {
485 return nullptr;
486 }
487 }
488
489 const SkImageInfo& getImageInfo() const {
490 return fImageInfo;
491 }
492
493 bool isScalable() const {
494 return fIsScalable;
495 }
496
497 bool isXtransImage() const {
498 return fIsXtransImage;
499 }
500
501private:
ebrauer46d2aa82016-02-17 08:04:00 -0800502 void init(const int width, const int height, const dng_point& cfaPatternSize) {
503 fImageInfo = SkImageInfo::Make(width, height, kN32_SkColorType, kOpaque_SkAlphaType);
504
505 // The DNG SDK scales only during demosaicing, so scaling is only possible when
506 // a mosaic info is available.
507 fIsScalable = cfaPatternSize.v != 0 && cfaPatternSize.h != 0;
508 fIsXtransImage = fIsScalable ? (cfaPatternSize.v == 6 && cfaPatternSize.h == 6) : false;
509 }
510
511 bool initFromPiex() {
512 // Does not take the ownership of rawStream.
513 SkPiexStream piexStream(fStream.get());
514 ::piex::PreviewImageData imageData;
515 if (::piex::IsRaw(&piexStream)
516 && ::piex::GetPreviewImageData(&piexStream, &imageData) == ::piex::Error::kOk)
517 {
518 dng_point cfaPatternSize(imageData.cfa_pattern_dim[1], imageData.cfa_pattern_dim[0]);
519 this->init(static_cast<int>(imageData.full_width),
520 static_cast<int>(imageData.full_height), cfaPatternSize);
521 return true;
522 }
523 return false;
524 }
525
yujieqin916de9f2016-01-25 08:26:16 -0800526 bool readDng() {
yujieqin916de9f2016-01-25 08:26:16 -0800527 try {
yujieqinf236ee42016-02-29 07:14:42 -0800528 // Due to the limit of DNG SDK, we need to reset host and info.
529 fHost.reset(new SkDngHost(&fAllocator));
530 fInfo.reset(new dng_info);
531 fDngStream.reset(new SkDngStream(fStream));
532
yujieqin916de9f2016-01-25 08:26:16 -0800533 fHost->ValidateSizes();
534 fInfo->Parse(*fHost, *fDngStream);
535 fInfo->PostParse(*fHost);
536 if (!fInfo->IsValidDNG()) {
537 return false;
538 }
539
540 fNegative.reset(fHost->Make_dng_negative());
541 fNegative->Parse(*fHost, *fDngStream, *fInfo);
542 fNegative->PostParse(*fHost, *fDngStream, *fInfo);
543 fNegative->SynchronizeMetadata();
544
ebrauer46d2aa82016-02-17 08:04:00 -0800545 dng_point cfaPatternSize(0, 0);
546 if (fNegative->GetMosaicInfo() != nullptr) {
547 cfaPatternSize = fNegative->GetMosaicInfo()->fCFAPatternSize;
548 }
549 this->init(static_cast<int>(fNegative->DefaultCropSizeH().As_real64()),
550 static_cast<int>(fNegative->DefaultCropSizeV().As_real64()),
551 cfaPatternSize);
yujieqin916de9f2016-01-25 08:26:16 -0800552 return true;
553 } catch (...) {
yujieqin916de9f2016-01-25 08:26:16 -0800554 return false;
555 }
556 }
557
558 SkDngImage(SkRawStream* stream)
559 : fStream(stream) {}
560
561 SkDngMemoryAllocator fAllocator;
562 SkAutoTDelete<SkRawStream> fStream;
563 SkAutoTDelete<dng_host> fHost;
564 SkAutoTDelete<dng_info> fInfo;
565 SkAutoTDelete<dng_negative> fNegative;
566 SkAutoTDelete<dng_stream> fDngStream;
567
568 SkImageInfo fImageInfo;
569 bool fIsScalable;
570 bool fIsXtransImage;
571};
572
573/*
574 * Tries to handle the image with PIEX. If PIEX returns kOk and finds the preview image, create a
575 * SkJpegCodec. If PIEX returns kFail, then the file is invalid, return nullptr. In other cases,
576 * fallback to create SkRawCodec for DNG images.
577 */
578SkCodec* SkRawCodec::NewFromStream(SkStream* stream) {
yujieqin9c7a8a42016-02-05 08:21:19 -0800579 SkAutoTDelete<SkRawStream> rawStream;
580 if (is_asset_stream(*stream)) {
581 rawStream.reset(new SkRawAssetStream(stream));
582 } else {
583 rawStream.reset(new SkRawBufferedStream(stream));
584 }
585
586 // Does not take the ownership of rawStream.
587 SkPiexStream piexStream(rawStream.get());
yujieqin916de9f2016-01-25 08:26:16 -0800588 ::piex::PreviewImageData imageData;
yujieqin9c7a8a42016-02-05 08:21:19 -0800589 if (::piex::IsRaw(&piexStream)) {
590 ::piex::Error error = ::piex::GetPreviewImageData(&piexStream, &imageData);
yujieqin916de9f2016-01-25 08:26:16 -0800591
yujieqin2d172eb2016-02-23 06:49:38 -0800592 if (error == ::piex::Error::kOk && imageData.preview.length > 0) {
yujieqin916de9f2016-01-25 08:26:16 -0800593 // transferBuffer() is destructive to the rawStream. Abandon the rawStream after this
594 // function call.
595 // FIXME: one may avoid the copy of memoryStream and use the buffered rawStream.
596 SkMemoryStream* memoryStream =
yujieqin2d172eb2016-02-23 06:49:38 -0800597 rawStream->transferBuffer(imageData.preview.offset, imageData.preview.length);
yujieqin916de9f2016-01-25 08:26:16 -0800598 return memoryStream ? SkJpegCodec::NewFromStream(memoryStream) : nullptr;
yujieqin916de9f2016-01-25 08:26:16 -0800599 } else if (error == ::piex::Error::kFail) {
600 return nullptr;
601 }
602 }
603
yujieqin9c7a8a42016-02-05 08:21:19 -0800604 // Takes the ownership of the rawStream.
yujieqin916de9f2016-01-25 08:26:16 -0800605 SkAutoTDelete<SkDngImage> dngImage(SkDngImage::NewFromStream(rawStream.release()));
606 if (!dngImage) {
607 return nullptr;
608 }
609
610 return new SkRawCodec(dngImage.release());
611}
612
613SkCodec::Result SkRawCodec::onGetPixels(const SkImageInfo& requestedInfo, void* dst,
614 size_t dstRowBytes, const Options& options,
615 SkPMColor ctable[], int* ctableCount,
616 int* rowsDecoded) {
617 if (!conversion_possible(requestedInfo, this->getInfo())) {
618 SkCodecPrintf("Error: cannot convert input type to output type.\n");
619 return kInvalidConversion;
620 }
621
622 SkAutoTDelete<SkSwizzler> swizzler(SkSwizzler::CreateSwizzler(
623 SkSwizzler::kRGB, nullptr, requestedInfo, options));
624 SkASSERT(swizzler);
625
626 const int width = requestedInfo.width();
627 const int height = requestedInfo.height();
628 SkAutoTDelete<dng_image> image(fDngImage->render(width, height));
629 if (!image) {
630 return kInvalidInput;
631 }
632
633 // Because the DNG SDK can not guarantee to render to requested size, we allow a small
634 // difference. Only the overlapping region will be converted.
635 const float maxDiffRatio = 1.03f;
636 const dng_point& imageSize = image->Size();
637 if (imageSize.h / width > maxDiffRatio || imageSize.h < width ||
638 imageSize.v / height > maxDiffRatio || imageSize.v < height) {
639 return SkCodec::kInvalidScale;
640 }
641
642 void* dstRow = dst;
yujieqin24716be2016-01-27 07:59:00 -0800643 SkAutoTMalloc<uint8_t> srcRow(width * 3);
yujieqin916de9f2016-01-25 08:26:16 -0800644
645 dng_pixel_buffer buffer;
646 buffer.fData = &srcRow[0];
647 buffer.fPlane = 0;
648 buffer.fPlanes = 3;
649 buffer.fColStep = buffer.fPlanes;
650 buffer.fPlaneStep = 1;
651 buffer.fPixelType = ttByte;
652 buffer.fPixelSize = sizeof(uint8_t);
scroggoe6459652016-01-30 10:06:11 -0800653 buffer.fRowStep = width * 3;
yujieqin916de9f2016-01-25 08:26:16 -0800654
655 for (int i = 0; i < height; ++i) {
656 buffer.fArea = dng_rect(i, 0, i + 1, width);
657
658 try {
659 image->Get(buffer, dng_image::edge_zero);
660 } catch (...) {
661 *rowsDecoded = i;
662 return kIncompleteInput;
663 }
664
665 swizzler->swizzle(dstRow, &srcRow[0]);
666 dstRow = SkTAddOffset<void>(dstRow, dstRowBytes);
667 }
668 return kSuccess;
669}
670
671SkISize SkRawCodec::onGetScaledDimensions(float desiredScale) const {
672 SkASSERT(desiredScale <= 1.f);
673 const SkISize dim = this->getInfo().dimensions();
674 if (!fDngImage->isScalable()) {
675 return dim;
676 }
677
678 // Limits the minimum size to be 80 on the short edge.
yujieqin076d83d2016-01-27 08:25:53 -0800679 const float shortEdge = static_cast<float>(SkTMin(dim.fWidth, dim.fHeight));
yujieqin916de9f2016-01-25 08:26:16 -0800680 if (desiredScale < 80.f / shortEdge) {
681 desiredScale = 80.f / shortEdge;
682 }
683
684 // For Xtrans images, the integer-factor scaling does not support the half-size scaling case
685 // (stronger downscalings are fine). In this case, returns the factor "3" scaling instead.
686 if (fDngImage->isXtransImage() && desiredScale > 1.f / 3.f && desiredScale < 1.f) {
687 desiredScale = 1.f / 3.f;
688 }
689
690 // Round to integer-factors.
691 const float finalScale = std::floor(1.f/ desiredScale);
yujieqin076d83d2016-01-27 08:25:53 -0800692 return SkISize::Make(static_cast<int32_t>(std::floor(dim.fWidth / finalScale)),
693 static_cast<int32_t>(std::floor(dim.fHeight / finalScale)));
yujieqin916de9f2016-01-25 08:26:16 -0800694}
695
696bool SkRawCodec::onDimensionsSupported(const SkISize& dim) {
697 const SkISize fullDim = this->getInfo().dimensions();
yujieqin076d83d2016-01-27 08:25:53 -0800698 const float fullShortEdge = static_cast<float>(SkTMin(fullDim.fWidth, fullDim.fHeight));
699 const float shortEdge = static_cast<float>(SkTMin(dim.fWidth, dim.fHeight));
yujieqin916de9f2016-01-25 08:26:16 -0800700
701 SkISize sizeFloor = this->onGetScaledDimensions(1.f / std::floor(fullShortEdge / shortEdge));
702 SkISize sizeCeil = this->onGetScaledDimensions(1.f / std::ceil(fullShortEdge / shortEdge));
703 return sizeFloor == dim || sizeCeil == dim;
704}
705
706SkRawCodec::~SkRawCodec() {}
707
708SkRawCodec::SkRawCodec(SkDngImage* dngImage)
709 : INHERITED(dngImage->getImageInfo(), nullptr)
710 , fDngImage(dngImage) {}