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

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

Issue 1520403003: Prototype of RAW decoding in Skia. (Closed) Base URL: https://skia.googlesource.com/skia.git@master
Patch Set: Fix bug in transferBuffer. 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
OLDNEW
(Empty)
1 /*
2 * Copyright 2015 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 virtual ~SkDngMemoryAllocator() {}
scroggo 2016/01/20 18:13:36 nit: I think we generally drop the virtual and use
yujieqin 2016/01/20 21:42:19 Done.
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 &&
scroggo 2016/01/20 18:13:36 It looks like we forgot to consider the case where
yujieqin 2016/01/20 21:42:20 Yes, it seems like the SkDynamicMemoryWStream.read
scroggo 2016/01/21 16:36:09 I filed skbug.com/4836 to investigate.
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 SkCodecPrintf("Warning: SkDngImage::render() is called multiple time s.");
scroggo 2016/01/20 18:13:36 I don't think this print statement is still necess
yujieqin 2016/01/20 21:42:19 Removed.
223 if (!this->readDng()) {
224 return nullptr;
225 }
226 } else {
227 host.reset(fHost.release());
228 info.reset(fInfo.release());
229 negative.reset(fNegative.release());
230 }
231
232 // DNG SDK preserves the aspect ratio, so it only needs to know the long er dimension.
233 const int preferredSize = SkTMax(width, height);
234 try {
235 host->SetPreferredSize(preferredSize);
236 host->ValidateSizes();
237
238 negative->ReadStage1Image(*host, *fStream, *info);
239
240 if (info->fMaskIndex != -1) {
241 negative->ReadTransparencyMask(*host, *fStream, *info);
242 }
243
244 negative->ValidateRawImageDigest(*host);
245 if (negative->IsDamaged()) {
246 return nullptr;
247 }
248
249 const int32 kMosaicPlane = -1;
250 negative->BuildStage2Image(*host);
251 negative->BuildStage3Image(*host, kMosaicPlane);
252
253 dng_render render(*host, *negative);
254 render.SetFinalSpace(dng_space_sRGB::Get());
255 render.SetFinalPixelType(ttByte);
256
257 dng_point stage3_size = negative->Stage3Image()->Size();
258 render.SetMaximumSize(SkTMax(stage3_size.h, stage3_size.v));
259
260 return render.Render();
261 } catch (...) {
262 return nullptr;
263 }
264 }
265
266 const SkImageInfo& getImageInfo() const {
267 return fImageInfo;
268 }
269
270 bool isXtransImage() const {
271 return fIsXtransImage;
272 }
273
274 private:
275 bool readDng() {
276 // Due to the limit of DNG SDK, we need to reset host and info.
277 fHost.reset(new dng_host(&fAllocator));
278 fInfo.reset(new dng_info);
279 try {
280 fHost->ValidateSizes();
281 fInfo->Parse(*fHost, *fStream);
282 fInfo->PostParse(*fHost);
283 if (!fInfo->IsValidDNG()) {
284 return false;
285 }
286
287 fNegative.reset(fHost->Make_dng_negative());
288 fNegative->Parse(*fHost, *fStream, *fInfo);
289 fNegative->PostParse(*fHost, *fStream, *fInfo);
290 fNegative->SynchronizeMetadata();
291
292 fImageInfo = SkImageInfo::Make(fNegative->DefaultCropSizeH().As_real 64(),
293 fNegative->DefaultCropSizeV().As_real 64(),
294 kN32_SkColorType, kOpaque_SkAlphaType );
295 fIsXtransImage = fNegative->GetMosaicInfo() != nullptr
296 ? (fNegative->GetMosaicInfo()->fCFAPatternSize.v == 6
297 && fNegative->GetMosaicInfo()->fCFAPatternSize.h == 6)
298 : false;
299 return true;
300 } catch (...) {
301 fNegative.reset(nullptr);
302 return false;
303 }
304 }
305
306 SkDngImage(SkRawStream* stream)
307 : fStream(stream) {}
308
309 SkDngMemoryAllocator fAllocator;
310 SkAutoTDelete<SkRawStream> fStream;
311 SkAutoTDelete<dng_host> fHost;
312 SkAutoTDelete<dng_info> fInfo;
313 SkAutoTDelete<dng_negative> fNegative;
314
315 SkImageInfo fImageInfo;
316 bool fIsXtransImage;
317 };
318
319 /*
320 * Tries to handle the image with PIEX. If PIEX returns kOk and finds the previe w image, create a
321 * SkJpegCodec. If PIEX returns kFail, then the file is invalid, return nullptr. In other cases,
322 * fallback to create SkRawCodec for DNG images.
323 */
324 SkCodec* SkRawCodec::NewFromStream(SkStream* stream) {
325 SkAutoTDelete<SkRawStream> rawStream(new SkRawStream(stream));
326 ::piex::PreviewImageData imageData;
327 if (::piex::IsRaw(rawStream.get())) {
328 ::piex::Error error = ::piex::GetPreviewImageData(rawStream.get(), &imag eData);
msarett 2016/01/20 20:23:17 This has the potential to "reallocate" the SkRawSt
yujieqin 2016/01/20 21:42:20 I am also aware of this issue. There is surely sti
329
330 if (error == ::piex::Error::kOk && imageData.preview_length > 0) {
msarett 2016/01/20 20:23:17 Bad Case Stream Memory Use for Raw Image with Piex
yujieqin 2016/01/20 21:42:20 The position of embedded preview is unpredictable
msarett 2016/01/21 15:46:16 Acknowledged.
scroggo 2016/01/21 16:36:09 We've already done something to help this problem
msarett 2016/01/21 16:48:49 Good point. Unfortunately, in my testing, it look
331 #if !defined(GOOGLE3)
332 // transferBuffer() is destructive to the rawStream. Abandon the raw Stream after this
333 // function call.
334 SkMemoryStream* memoryStream =
335 rawStream->transferBuffer(imageData.preview_offset, imageDat a.preview_length);
msarett 2016/01/20 20:23:17 This operation involves allocating a new 1-4 MB bu
scroggo 2016/01/20 20:36:24 (1) Not sure if this is where you were going with
msarett 2016/01/20 20:43:52 (1) Agreed. (2) Seems like a bad idea to hold onto
yujieqin 2016/01/20 21:42:20 Added FIXME. But, as said, the location of the emb
msarett 2016/01/21 15:46:16 Acknowledged.
336 return memoryStream ? SkJpegCodec::NewFromStream(memoryStream) : nul lptr;
337 #else
338 return nullptr;
339 #endif
340 } else if (error == ::piex::Error::kFail) {
341 return nullptr;
342 }
343 }
344
345 SkAutoTDelete<SkDngImage> dngImage(SkDngImage::NewFromStream(rawStream.relea se()));
msarett 2016/01/20 20:23:17 It looks to me like ::piex::IsRaw() returns true f
yujieqin 2016/01/20 21:42:20 Similar to the type checks in SkCodec.cpp, the ::p
msarett 2016/01/21 15:46:16 Understood. Would it be possible to make it a lon
scroggo 2016/01/21 16:36:10 FWIW, SkCodec.cpp's type checks may offer false po
yujieqin 2016/01/21 17:44:26 Unfortunately, yes. Due to the variations of RAW f
346 if (!dngImage) {
347 return nullptr;
348 }
349
350 return new SkRawCodec(dngImage.release());
msarett 2016/01/20 20:23:17 Bad Case Memory Use for Dng Image without Preview:
yujieqin 2016/01/20 21:42:20 Unfortunately, the length is required by DNG SDK,
msarett 2016/01/21 15:46:16 Can we make it a longer term goal to "fix" the DNG
351 }
352
353 SkCodec::Result SkRawCodec::onGetPixels(const SkImageInfo& requestedInfo, void* dst,
354 size_t dstRowBytes, const Options& optio ns,
355 SkPMColor ctable[], int* ctableCount,
356 int* rowsDecoded) {
357 if (!conversion_possible(requestedInfo, this->getInfo())) {
358 SkCodecPrintf("Error: cannot convert input type to output type.\n");
359 return kInvalidConversion;
360 }
361
362 SkAutoTDelete<SkSwizzler> swizzler(SkSwizzler::CreateSwizzler(
363 SkSwizzler::kRGB, nullptr, requestedInfo, options));
364 if (!swizzler) {
msarett 2016/01/20 20:23:17 I think that, because conversion_possible succeede
yujieqin 2016/01/20 21:42:19 I think the 565 does not work in current test, the
msarett 2016/01/21 15:46:16 No, SkSwizzler had a bug where we forgot to add th
yujieqin 2016/01/21 16:40:01 Yeah, after rebase, I don't need this check anymor
365 SkCodecPrintf("Error: cannot create swizzler.\n");
366 return kInvalidConversion;
367 }
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 in onGetPixels( ).
scroggo 2016/01/20 18:13:36 nit: "in onGetPixels()" seems unnecessary here - t
yujieqin 2016/01/20 21:42:20 Done.
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;
scroggo 2016/01/20 18:13:36 Is this code ever reached? This gets called by SkC
yujieqin 2016/01/20 21:42:20 adaubert@ wrote a test to verify this part could h
adaubert 2016/01/21 10:43:30 In practice we should be safe and this case should
scroggo 2016/01/21 16:36:10 I guess that's fine. My real concern would be if g
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 non-scaled ve rsion.
scroggo 2016/01/20 18:13:36 So this is saying that scaling by a half is not su
msarett 2016/01/20 20:23:17 I've changed that code multiple times for multiple
yujieqin 2016/01/20 21:42:20 Just for clarification, does it mean we can keep o
adaubert 2016/01/21 10:43:30 Downscaling to a smaller size, in this case 1/3, w
msarett 2016/01/21 15:46:16 Leon?
scroggo 2016/01/21 16:36:09 My preference would be 1/3 for now. The caller can
yujieqin 2016/01/21 17:44:26 Sure, 1/3 it is now. :)
426 if (fDngImage->isXtransImage() && desiredScale >= 0.5f) {
427 return dim;
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) {
scroggo 2016/01/20 18:13:36 All this scaling code seems complex. Should we add
yujieqin 2016/01/20 21:42:20 * The image in current CL is not xtrans. * I think
scroggo 2016/01/21 16:36:09 I think that's a fine start.
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

Powered by Google App Engine
This is Rietveld 408576698