Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(1)

Side by Side Diff: src/codec/SkRawCodec.cpp

Issue 1624513003: Add RAW decoding support to Skia (Closed) Base URL: https://skia.googlesource.com/skia.git@master
Patch Set: Fix sample_dng in resources, Treat less warnings as errors Created 4 years, 11 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « src/codec/SkRawCodec.h ('k') | tests/CodexTest.cpp » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
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 "SkCodec.h"
9 #include "SkCodecPriv.h"
10 #include "SkColorPriv.h"
11 #include "SkData.h"
12 #if !defined(GOOGLE3)
13 #include "SkJpegCodec.h"
14 #endif
15 #include "SkRawCodec.h"
16 #include "SkRefCnt.h"
17 #include "SkStream.h"
18 #include "SkStreamPriv.h"
19 #include "SkSwizzler.h"
20 #include "SkTemplates.h"
21 #include "SkTypes.h"
22
23 #include "dng_color_space.h"
24 #include "dng_exceptions.h"
25 #include "dng_host.h"
26 #include "dng_info.h"
27 #include "dng_memory.h"
28 #include "dng_render.h"
29 #include "dng_stream.h"
30
31 #include "src/piex.h"
32
33 #include <cmath> // for std::round,floor,ceil
34 #include <limits>
35
36 namespace {
37
38 // T must be unsigned type.
39 template <class T>
40 bool safe_add_to_size_t(T arg1, T arg2, size_t* result) {
41 SkASSERT(arg1 >= 0);
42 SkASSERT(arg2 >= 0);
43 if (arg1 >= 0 && arg2 <= std::numeric_limits<T>::max() - arg1) {
44 T sum = arg1 + arg2;
45 if (sum <= std::numeric_limits<size_t>::max()) {
46 *result = static_cast<size_t>(sum);
47 return true;
48 }
49 }
50 return false;
51 }
52
53 class SkDngMemoryAllocator : public dng_memory_allocator {
54 public:
55 ~SkDngMemoryAllocator() override {}
56
57 dng_memory_block* Allocate(uint32 size) override {
58 // To avoid arbitary allocation requests which might lead to out-of-memo ry, limit the
59 // amount of memory that can be allocated at once. The memory limit is b ased on experiments
60 // and supposed to be sufficient for all valid DNG images.
61 if (size > 300 * 1024 * 1024) { // 300 MB
62 ThrowMemoryFull();
63 }
64 return dng_memory_allocator::Allocate(size);
65 }
66 };
67
68 } // namespace
69
70 // Note: this class could throw exception if it is used as dng_stream.
71 class SkRawStream : public dng_stream, public ::piex::StreamInterface {
72 public:
73 // Note that this call will take the ownership of stream.
74 explicit SkRawStream(SkStream* stream)
75 : fStream(stream), fWholeStreamRead(false) {}
76
77 ~SkRawStream() override {}
78
79 /*
80 * Creates an SkMemoryStream from the offset with size.
81 * Note: for performance reason, this function is destructive to the SkRawSt ream. One should
82 * abandon current object after the function call.
83 */
84 SkMemoryStream* transferBuffer(size_t offset, size_t size) {
85 SkAutoTUnref<SkData> data(SkData::NewUninitialized(size));
86 if (offset > fStreamBuffer.bytesWritten()) {
87 // If the offset is not buffered, read from fStream directly and ski p the buffering.
88 const size_t skipLength = offset - fStreamBuffer.bytesWritten();
89 if (fStream->skip(skipLength) != skipLength) {
90 return nullptr;
91 }
92 const size_t bytesRead = fStream->read(data->writable_data(), size);
93 if (bytesRead < size) {
94 data.reset(SkData::NewSubset(data.get(), 0, bytesRead));
95 }
96 } else {
97 const size_t alreadyBuffered = SkTMin(fStreamBuffer.bytesWritten() - offset, size);
98 if (alreadyBuffered > 0 &&
99 !fStreamBuffer.read(data->writable_data(), offset, alreadyBuffer ed)) {
100 return nullptr;
101 }
102
103 const size_t remaining = size - alreadyBuffered;
104 if (remaining) {
105 auto* dst = static_cast<uint8_t*>(data->writable_data()) + alrea dyBuffered;
106 const size_t bytesRead = fStream->read(dst, remaining);
107 size_t newSize;
108 if (bytesRead < remaining) {
109 if (!safe_add_to_size_t(alreadyBuffered, bytesRead, &newSize )) {
110 return nullptr;
111 }
112 data.reset(SkData::NewSubset(data.get(), 0, newSize));
113 }
114 }
115 }
116 return new SkMemoryStream(data);
117 }
118
119 // For PIEX
120 ::piex::Error GetData(const size_t offset, const size_t length,
121 uint8* data) override {
122 if (offset == 0 && length == 0) {
123 return ::piex::Error::kOk;
124 }
125 size_t sum;
126 if (!safe_add_to_size_t(offset, length, &sum) || !this->bufferMoreData(s um)) {
127 return ::piex::Error::kFail;
128 }
129 if (!fStreamBuffer.read(data, offset, length)) {
130 return ::piex::Error::kFail;
131 }
132 return ::piex::Error::kOk;
133 }
134
135 protected:
136 // For dng_stream
137 uint64 DoGetLength() override {
138 if (!this->bufferMoreData(kReadToEnd)) { // read whole stream
139 ThrowReadFile();
140 }
141 return fStreamBuffer.bytesWritten();
142 }
143
144 // For dng_stream
145 void DoRead(void* data, uint32 count, uint64 offset) override {
146 if (count == 0 && offset == 0) {
147 return;
148 }
149 size_t sum;
150 if (!safe_add_to_size_t(static_cast<uint64>(count), offset, &sum) ||
151 !this->bufferMoreData(sum)) {
152 ThrowReadFile();
153 }
154
155 if (!fStreamBuffer.read(data, offset, count)) {
156 ThrowReadFile();
157 }
158 }
159
160 private:
161 // Note: if the newSize == kReadToEnd (0), this function will read to the en d of stream.
162 bool bufferMoreData(size_t newSize) {
163 if (newSize == kReadToEnd) {
164 if (fWholeStreamRead) { // already read-to-end.
165 return true;
166 }
167
168 // TODO: optimize for the special case when the input is SkMemoryStr eam.
169 return SkStreamCopy(&fStreamBuffer, fStream.get());
170 }
171
172 if (newSize <= fStreamBuffer.bytesWritten()) { // already buffered to n ewSize
173 return true;
174 }
175 if (fWholeStreamRead) { // newSize is larger than the whole stream.
176 return false;
177 }
178
179 const size_t sizeToRead = newSize - fStreamBuffer.bytesWritten();
180 SkAutoTMalloc<uint8> tempBuffer(sizeToRead);
181 const size_t bytesRead = fStream->read(tempBuffer.get(), sizeToRead);
182 if (bytesRead != sizeToRead) {
183 return false;
184 }
185 return fStreamBuffer.write(tempBuffer.get(), bytesRead);
186 }
187
188 SkAutoTDelete<SkStream> fStream;
189 bool fWholeStreamRead;
190
191 SkDynamicMemoryWStream fStreamBuffer;
192
193 const size_t kReadToEnd = 0;
194 };
195
196 class SkDngImage {
197 public:
198 static SkDngImage* NewFromStream(SkRawStream* stream) {
199 SkAutoTDelete<SkDngImage> dngImage(new SkDngImage(stream));
200 if (!dngImage->readDng()) {
201 return nullptr;
202 }
203
204 SkASSERT(dngImage->fNegative);
205 return dngImage.release();
206 }
207
208 /*
209 * Renders the DNG image to the size. The DNG SDK only allows scaling close to integer factors
210 * down to 80 pixels on the short edge. The rendered image will be close to the specified size,
211 * but there is no guarantee that any of the edges will match the requested size. E.g.
212 * 100% size: 4000 x 3000
213 * requested size: 1600 x 1200
214 * returned size could be: 2000 x 1500
215 */
216 dng_image* render(int width, int height) {
217 // render() takes ownership of fHost, fInfo and fNegative when available .
218 SkAutoTDelete<dng_host> host;
219 SkAutoTDelete<dng_info> info;
220 SkAutoTDelete<dng_negative> negative;
221 if (!fHost || !fInfo || !fNegative) {
222 if (!this->readDng()) {
223 return nullptr;
224 }
225 } else {
226 host.reset(fHost.release());
227 info.reset(fInfo.release());
228 negative.reset(fNegative.release());
229 }
230
231 // DNG SDK preserves the aspect ratio, so it only needs to know the long er dimension.
232 const int preferredSize = SkTMax(width, height);
233 try {
234 host->SetPreferredSize(preferredSize);
235 host->ValidateSizes();
236
237 negative->ReadStage1Image(*host, *fStream, *info);
238
239 if (info->fMaskIndex != -1) {
240 negative->ReadTransparencyMask(*host, *fStream, *info);
241 }
242
243 negative->ValidateRawImageDigest(*host);
244 if (negative->IsDamaged()) {
245 return nullptr;
246 }
247
248 const int32 kMosaicPlane = -1;
249 negative->BuildStage2Image(*host);
250 negative->BuildStage3Image(*host, kMosaicPlane);
251
252 dng_render render(*host, *negative);
253 render.SetFinalSpace(dng_space_sRGB::Get());
254 render.SetFinalPixelType(ttByte);
255
256 dng_point stage3_size = negative->Stage3Image()->Size();
257 render.SetMaximumSize(SkTMax(stage3_size.h, stage3_size.v));
258
259 return render.Render();
260 } catch (...) {
261 return nullptr;
262 }
263 }
264
265 const SkImageInfo& getImageInfo() const {
266 return fImageInfo;
267 }
268
269 bool isXtransImage() const {
270 return fIsXtransImage;
271 }
272
273 private:
274 bool readDng() {
275 // Due to the limit of DNG SDK, we need to reset host and info.
276 fHost.reset(new dng_host(&fAllocator));
277 fInfo.reset(new dng_info);
278 try {
279 fHost->ValidateSizes();
280 fInfo->Parse(*fHost, *fStream);
281 fInfo->PostParse(*fHost);
282 if (!fInfo->IsValidDNG()) {
283 return false;
284 }
285
286 fNegative.reset(fHost->Make_dng_negative());
287 fNegative->Parse(*fHost, *fStream, *fInfo);
288 fNegative->PostParse(*fHost, *fStream, *fInfo);
289 fNegative->SynchronizeMetadata();
290
291 fImageInfo = SkImageInfo::Make(fNegative->DefaultCropSizeH().As_real 64(),
292 fNegative->DefaultCropSizeV().As_real 64(),
293 kN32_SkColorType, kOpaque_SkAlphaType );
294 fIsXtransImage = fNegative->GetMosaicInfo() != nullptr
295 ? (fNegative->GetMosaicInfo()->fCFAPatternSize.v == 6
296 && fNegative->GetMosaicInfo()->fCFAPatternSize.h == 6)
297 : false;
298 return true;
299 } catch (...) {
300 fNegative.reset(nullptr);
301 return false;
302 }
303 }
304
305 SkDngImage(SkRawStream* stream)
306 : fStream(stream) {}
307
308 SkDngMemoryAllocator fAllocator;
309 SkAutoTDelete<SkRawStream> fStream;
310 SkAutoTDelete<dng_host> fHost;
311 SkAutoTDelete<dng_info> fInfo;
312 SkAutoTDelete<dng_negative> fNegative;
313
314 SkImageInfo fImageInfo;
315 bool fIsXtransImage;
316 };
317
318 /*
319 * Tries to handle the image with PIEX. If PIEX returns kOk and finds the previe w image, create a
320 * SkJpegCodec. If PIEX returns kFail, then the file is invalid, return nullptr. In other cases,
321 * fallback to create SkRawCodec for DNG images.
322 */
323 SkCodec* SkRawCodec::NewFromStream(SkStream* stream) {
324 SkAutoTDelete<SkRawStream> rawStream(new SkRawStream(stream));
325 ::piex::PreviewImageData imageData;
326 // FIXME: ::piex::GetPreviewImageData() calls GetData() frequently with smal l amounts,
327 // resulting in many calls to bufferMoreData(). Could we make this more effi cient by grouping
328 // smaller requests together?
329 if (::piex::IsRaw(rawStream.get())) {
330 ::piex::Error error = ::piex::GetPreviewImageData(rawStream.get(), &imag eData);
331
332 if (error == ::piex::Error::kOk && imageData.preview_length > 0) {
333 #if !defined(GOOGLE3)
334 // transferBuffer() is destructive to the rawStream. Abandon the raw Stream after this
335 // function call.
336 // FIXME: one may avoid the copy of memoryStream and use the buffere d rawStream.
337 SkMemoryStream* memoryStream =
338 rawStream->transferBuffer(imageData.preview_offset, imageDat a.preview_length);
339 return memoryStream ? SkJpegCodec::NewFromStream(memoryStream) : nul lptr;
340 #else
341 return nullptr;
342 #endif
343 } else if (error == ::piex::Error::kFail) {
344 return nullptr;
345 }
346 }
347
348 SkAutoTDelete<SkDngImage> dngImage(SkDngImage::NewFromStream(rawStream.relea se()));
349 if (!dngImage) {
350 return nullptr;
351 }
352
353 return new SkRawCodec(dngImage.release());
354 }
355
356 SkCodec::Result SkRawCodec::onGetPixels(const SkImageInfo& requestedInfo, void* dst,
357 size_t dstRowBytes, const Options& optio ns,
358 SkPMColor ctable[], int* ctableCount,
359 int* rowsDecoded) {
360 if (!conversion_possible(requestedInfo, this->getInfo())) {
361 SkCodecPrintf("Error: cannot convert input type to output type.\n");
362 return kInvalidConversion;
363 }
364
365 SkAutoTDelete<SkSwizzler> swizzler(SkSwizzler::CreateSwizzler(
366 SkSwizzler::kRGB, nullptr, requestedInfo, options));
367 SkASSERT(swizzler);
368
369 const int width = requestedInfo.width();
370 const int height = requestedInfo.height();
371 SkAutoTDelete<dng_image> image(fDngImage->render(width, height));
372 if (!image) {
373 return kInvalidInput;
374 }
375
376 // Because the DNG SDK can not guarantee to render to requested size, we all ow a small
377 // difference. Only the overlapping region will be converted.
378 const float maxDiffRatio = 1.03f;
379 const dng_point& imageSize = image->Size();
380 if (imageSize.h / width > maxDiffRatio || imageSize.h < width ||
381 imageSize.v / height > maxDiffRatio || imageSize.v < height) {
382 return SkCodec::kInvalidScale;
383 }
384
385 void* dstRow = dst;
386 uint8_t srcRow[width * 3];
387
388 dng_pixel_buffer buffer;
389 buffer.fData = &srcRow[0];
390 buffer.fPlane = 0;
391 buffer.fPlanes = 3;
392 buffer.fColStep = buffer.fPlanes;
393 buffer.fPlaneStep = 1;
394 buffer.fPixelType = ttByte;
395 buffer.fPixelSize = sizeof(uint8_t);
396 buffer.fRowStep = sizeof(srcRow);
397
398 for (int i = 0; i < height; ++i) {
399 buffer.fArea = dng_rect(i, 0, i + 1, width);
400
401 try {
402 image->Get(buffer, dng_image::edge_zero);
403 } catch (...) {
404 *rowsDecoded = i;
405 return kIncompleteInput;
406 }
407
408 swizzler->swizzle(dstRow, &srcRow[0]);
409 dstRow = SkTAddOffset<void>(dstRow, dstRowBytes);
410 }
411 return kSuccess;
412 }
413
414 SkISize SkRawCodec::onGetScaledDimensions(float desiredScale) const {
415 SkASSERT(desiredScale <= 1.f);
416 const SkISize dim = this->getInfo().dimensions();
417
418 // Limits the minimum size to be 80 on the short edge.
419 const float shortEdge = SkTMin(dim.fWidth, dim.fHeight);
420 if (desiredScale < 80.f / shortEdge) {
421 desiredScale = 80.f / shortEdge;
422 }
423
424 // For Xtrans images, the integer-factor scaling does not support the half-s ize scaling case
425 // (stronger downscalings are fine). In this case, returns the factor "3" sc aling instead.
426 if (fDngImage->isXtransImage() && desiredScale > 1.f / 3.f && desiredScale < 1.f) {
427 desiredScale = 1.f / 3.f;
428 }
429
430 // Round to integer-factors.
431 const float finalScale = std::floor(1.f/ desiredScale);
432 return SkISize::Make(std::floor(dim.fWidth / finalScale),
433 std::floor(dim.fHeight / finalScale));
434 }
435
436 bool SkRawCodec::onDimensionsSupported(const SkISize& dim) {
437 const SkISize fullDim = this->getInfo().dimensions();
438 const float fullShortEdge = SkTMin(fullDim.fWidth, fullDim.fHeight);
439 const float shortEdge = SkTMin(dim.fWidth, dim.fHeight);
440
441 SkISize sizeFloor = this->onGetScaledDimensions(1.f / std::floor(fullShortEd ge / shortEdge));
442 SkISize sizeCeil = this->onGetScaledDimensions(1.f / std::ceil(fullShortEdge / shortEdge));
443 return sizeFloor == dim || sizeCeil == dim;
444 }
445
446 SkRawCodec::~SkRawCodec() {}
447
448 SkRawCodec::SkRawCodec(SkDngImage* dngImage)
449 : INHERITED(dngImage->getImageInfo(), nullptr)
450 , fDngImage(dngImage) {}
OLDNEW
« no previous file with comments | « src/codec/SkRawCodec.h ('k') | tests/CodexTest.cpp » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698