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

Side by Side Diff: third_party/WebKit/Source/platform/image-decoders/gif/GIFImageDecoder.cpp

Issue 2565323003: Move gif image decoder to SkCodec (Closed)
Patch Set: Zero fill pixel data when allocating Created 3 years, 9 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
1 /* 1 /*
2 * Copyright (C) 2006 Apple Computer, Inc. All rights reserved. 2 * Copyright (C) 2006 Apple Computer, Inc. All rights reserved.
3 * 3 *
4 * Redistribution and use in source and binary forms, with or without 4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions 5 * modification, are permitted provided that the following conditions
6 * are met: 6 * are met:
7 * 1. Redistributions of source code must retain the above copyright 7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer. 8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright 9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the 10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution. 11 * documentation and/or other materials provided with the distribution.
12 * 12 *
13 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY 13 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
14 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 14 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR 16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
17 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 17 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 18 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 19 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 20 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 */ 24 */
25 25
26 #include "platform/image-decoders/gif/GIFImageDecoder.h" 26 #include "platform/image-decoders/gif/GIFImageDecoder.h"
27 27
28 #include "platform/image-decoders/gif/GIFImageReader.h" 28 #include <limits>
29 #include "third_party/skia/include/core/SkImageInfo.h"
29 #include "wtf/NotFound.h" 30 #include "wtf/NotFound.h"
30 #include "wtf/PtrUtil.h" 31 #include "wtf/PtrUtil.h"
31 #include <limits>
32 32
33 namespace blink { 33 namespace blink {
34 34
35 GIFImageDecoder::GIFImageDecoder(AlphaOption alphaOption, 35 GIFImageDecoder::GIFImageDecoder(AlphaOption alphaOption,
36 const ColorBehavior& colorBehavior, 36 const ColorBehavior& colorBehavior,
37 size_t maxDecodedBytes) 37 size_t maxDecodedBytes)
38 : ImageDecoder(alphaOption, colorBehavior, maxDecodedBytes), 38 : ImageDecoder(alphaOption, colorBehavior, maxDecodedBytes),
39 m_repetitionCount(cAnimationLoopOnce) {} 39 m_codec(),
40 40 m_segmentStream(nullptr),
41 GIFImageDecoder::~GIFImageDecoder() {} 41 m_frameInfos() {}
42
43 GIFImageDecoder::~GIFImageDecoder() {
44 if (!m_codec) {
45 // if we did not create m_codec and thus did not pass ownership to it
46 if (m_segmentStream)
47 delete m_segmentStream;
48 }
49 }
42 50
43 void GIFImageDecoder::onSetData(SegmentReader* data) { 51 void GIFImageDecoder::onSetData(SegmentReader* data) {
44 if (m_reader) 52 if (!data) {
45 m_reader->setData(data); 53 if (m_segmentStream)
54 m_segmentStream->setReader(nullptr, false);
55 return;
56 }
57
58 if (!m_segmentStream)
59 m_segmentStream = new SegmentStream();
60
61 m_segmentStream->setReader(data, isAllDataReceived());
62
63 // If we don't have a SkCodec yet, create one from the stream
64 if (!m_codec) {
65 SkCodec* codec = SkCodec::NewFromStream(m_segmentStream);
66 if (codec) {
67 m_codec.reset(codec);
68 } else {
69 // m_segmentStream's ownership is passed. It is deleted if SkCodec
70 // creation fails. In this case, release our reference so we can create a
71 // new SegmentStream later.
72 m_segmentStream = nullptr;
73 return;
74 }
75
76 // SkCodec::NewFromStream will read enough of the image to get the image
77 // size.
78 SkImageInfo imageInfo = m_codec->getInfo();
79 setSize(imageInfo.width(), imageInfo.height());
80 }
46 } 81 }
47 82
48 int GIFImageDecoder::repetitionCount() const { 83 int GIFImageDecoder::repetitionCount() const {
84 if (!m_codec)
85 return cAnimationLoopOnce;
86
49 // This value can arrive at any point in the image data stream. Most GIFs 87 // This value can arrive at any point in the image data stream. Most GIFs
50 // in the wild declare it near the beginning of the file, so it usually is 88 // in the wild declare it near the beginning of the file, so it usually is
51 // set by the time we've decoded the size, but (depending on the GIF and the 89 // set by the time we've decoded the size, but (depending on the GIF and the
52 // packets sent back by the webserver) not always. If the reader hasn't 90 // packets sent back by the webserver) not always.
53 // seen a loop count yet, it will return cLoopCountNotSeen, in which case we
54 // should default to looping once (the initial value for
55 // |m_repetitionCount|).
56 // 91 //
57 // There are some additional wrinkles here. First, ImageSource::clear() 92 // SkCodec will parse forward in the file if the repetition count has not been
58 // may destroy the reader, making the result from the reader _less_ 93 // seen yet.
59 // authoritative on future calls if the recreated reader hasn't seen the 94
60 // loop count. We don't need to special-case this because in this case the 95 if (isAllDataReceived() && m_frameInfos.size() == 1)
61 // new reader will once again return cLoopCountNotSeen, and we won't 96 return cAnimationNone;
62 // overwrite the cached correct value. 97 if (failed())
63 // 98 return cAnimationLoopOnce;
64 // Second, a GIF might never set a loop count at all, in which case we 99
65 // should continue to treat it as a "loop once" animation. We don't need 100 int repetitionCount = m_codec->getRepetitionCount();
66 // special code here either, because in this case we'll never change 101 switch (repetitionCount) {
67 // |m_repetitionCount| from its default value. 102 case 0:
68 // 103 return cAnimationLoopOnce;
69 // Third, we use the same GIFImageReader for counting frames and we might 104 case SkCodec::kRepetitionCountInfinite:
70 // see the loop count and then encounter a decoding error which happens 105 return cAnimationLoopInfinite;
71 // later in the stream. It is also possible that no frames are in the 106 default:
72 // stream. In these cases we should just loop once. 107 return repetitionCount;
73 if (isAllDataReceived() && parseCompleted() && m_reader->imagesCount() == 1) 108 }
74 m_repetitionCount = cAnimationNone;
75 else if (failed() || (m_reader && (!m_reader->imagesCount())))
76 m_repetitionCount = cAnimationLoopOnce;
77 else if (m_reader && m_reader->loopCount() != cLoopCountNotSeen)
78 m_repetitionCount = m_reader->loopCount();
79 return m_repetitionCount;
80 } 109 }
81 110
82 bool GIFImageDecoder::frameIsCompleteAtIndex(size_t index) const { 111 bool GIFImageDecoder::frameIsCompleteAtIndex(size_t index) const {
83 return m_reader && (index < m_reader->imagesCount()) && 112 if (!m_codec)
84 m_reader->frameContext(index)->isComplete(); 113 return false;
114
115 if (m_frameInfos.size() <= index)
116 return false;
117
118 return m_frameInfos[index].fFullyReceived;
85 } 119 }
86 120
87 float GIFImageDecoder::frameDurationAtIndex(size_t index) const { 121 float GIFImageDecoder::frameDurationAtIndex(size_t index) const {
88 return (m_reader && (index < m_reader->imagesCount()) && 122 if (index < m_frameBufferCache.size())
89 m_reader->frameContext(index)->isHeaderDefined()) 123 return m_frameBufferCache[index].duration();
90 ? m_reader->frameContext(index)->delayTime() 124 return 0;
91 : 0; 125 }
92 } 126
93 127 size_t GIFImageDecoder::decodeFrameCount() {
94 bool GIFImageDecoder::setFailed() { 128 if (!m_codec)
95 m_reader.reset(); 129 return 0;
96 return ImageDecoder::setFailed(); 130
97 } 131 if (!failed() && !(m_segmentStream && m_segmentStream->isCleared()))
98 132 m_frameInfos = m_codec->getFrameInfo();
99 bool GIFImageDecoder::haveDecodedRow(size_t frameIndex, 133
100 GIFRow::const_iterator rowBegin, 134 return m_frameInfos.size();
101 size_t width, 135 }
102 size_t rowNumber, 136
103 unsigned repeatCount, 137 void GIFImageDecoder::initializeNewFrame(size_t index) {
104 bool writeTransparentPixels) { 138 DCHECK(m_codec);
105 const GIFFrameContext* frameContext = m_reader->frameContext(frameIndex); 139
106 // The pixel data and coordinates supplied to us are relative to the frame's 140 ImageFrame& frame = m_frameBufferCache[index];
107 // origin within the entire image size, i.e. 141 // SkCodec does not inform us if only a portion of the image was updated
108 // (frameContext->xOffset, frameContext->yOffset). There is no guarantee 142 // in the current frame. Because of this, rather than correctly filling in
109 // that width == (size().width() - frameContext->xOffset), so 143 // the frame rect, we set the frame rect to be the image's full size.
110 // we must ensure we don't run off the end of either the source data or the 144 IntSize fullImageSize = size();
111 // row's X-coordinates. 145 frame.setOriginalFrameRect(IntRect(IntPoint(), fullImageSize));
112 const int xBegin = frameContext->xOffset(); 146 frame.setDuration(m_frameInfos[index].fDuration);
113 const int yBegin = frameContext->yOffset() + rowNumber; 147 size_t requiredPreviousFrameIndex = m_frameInfos[index].fRequiredFrame;
114 const int xEnd = std::min(static_cast<int>(frameContext->xOffset() + width), 148 if (requiredPreviousFrameIndex == SkCodec::kNone)
115 size().width()); 149 requiredPreviousFrameIndex = WTF::kNotFound;
116 const int yEnd = std::min( 150 frame.setRequiredPreviousFrameIndex(requiredPreviousFrameIndex);
117 static_cast<int>(frameContext->yOffset() + rowNumber + repeatCount), 151 // The disposal method is not required any more, but is left in place
118 size().height()); 152 // for the other image decoders that do not yet rely on SkCodec.
119 if (!width || (xBegin < 0) || (yBegin < 0) || (xEnd <= xBegin) || 153 // For now, fill it with DisposeKeep.
120 (yEnd <= yBegin)) 154 frame.setDisposalMethod(ImageFrame::DisposeKeep);
121 return true; 155 }
122 156
123 const GIFColorMap::Table& colorTable = 157 void GIFImageDecoder::decode(size_t index) {
124 frameContext->localColorMap().isDefined() 158 if (failed())
125 ? frameContext->localColorMap().getTable() 159 return;
126 : m_reader->globalColorMap().getTable(); 160
127 161 if (!m_codec)
128 if (colorTable.isEmpty()) 162 return;
129 return true; 163
130 164 if (m_frameBufferCache.size() <= index) {
131 GIFColorMap::Table::const_iterator colorTableIter = colorTable.begin(); 165 // It is a fatal error if all data is received and we have decoded all
132 166 // frames available but the file is truncated.
133 // Initialize the frame if necessary. 167 if (isAllDataReceived())
134 ImageFrame& buffer = m_frameBufferCache[frameIndex]; 168 setFailed();
135 if (!initFrameBuffer(frameIndex)) 169
136 return false; 170 return;
137 171 }
138 const size_t transparentPixel = frameContext->transparentPixel(); 172
139 GIFRow::const_iterator rowEnd = rowBegin + (xEnd - xBegin); 173 updateAggressivePurging(index);
140 ImageFrame::PixelData* currentAddress = buffer.getAddr(xBegin, yBegin); 174
141 175 SkImageInfo imageInfo = m_codec->getInfo().makeColorType(kN32_SkColorType);
142 // We may or may not need to write transparent pixels to the buffer. 176
143 // If we're compositing against a previous image, it's wrong, and if 177 SkCodec::Options options;
144 // we're writing atop a cleared, fully transparent buffer, it's 178 options.fFrameIndex = index;
145 // unnecessary; but if we're decoding an interlaced gif and 179 options.fHasPriorFrame = false;
146 // displaying it "Haeberli"-style, we must write these for passes 180 options.fZeroInitialized = true;
147 // beyond the first, or the initial passes will "show through" the 181
148 // later ones. 182 ImageFrame& frame = m_frameBufferCache[index];
149 // 183 if (frame.getStatus() == ImageFrame::FrameEmpty) {
150 // The loops below are almost identical. One writes a transparent pixel 184 size_t requiredPreviousFrameIndex = frame.requiredPreviousFrameIndex();
151 // and one doesn't based on the value of |writeTransparentPixels|. 185 if (requiredPreviousFrameIndex == WTF::kNotFound) {
152 // The condition check is taken out of the loop to enhance performance. 186 frame.allocatePixelData(size().width(), size().height(),
153 // This optimization reduces decoding time by about 15% for a 3MB image. 187 colorSpaceForSkImages());
154 if (writeTransparentPixels) { 188 frame.zeroFillPixelData();
cblume 2017/03/25 07:54:39 I added the zero initialization here. Previously
scroggo_chromium 2017/04/05 18:06:14 Right.
cblume 2017/04/08 01:19:20 This was a false alarm on my part. The errors were
155 for (; rowBegin != rowEnd; ++rowBegin, ++currentAddress) { 189 } else {
156 const size_t sourceValue = *rowBegin; 190 ImageFrame& requiredPreviousFrame =
157 if ((sourceValue != transparentPixel) && 191 m_frameBufferCache[requiredPreviousFrameIndex];
158 (sourceValue < colorTable.size())) { 192
159 *currentAddress = colorTableIter[sourceValue]; 193 if (requiredPreviousFrame.getStatus() != ImageFrame::FrameComplete)
160 } else { 194 decode(requiredPreviousFrameIndex);
161 *currentAddress = 0; 195
162 m_currentBufferSawAlpha = true; 196 // We try to reuse |requiredPreviousFrame| as starting state to avoid
197 // copying. If canReusePreviousFrameBuffer returns false, we must copy
198 // the data since |requiredPreviousFrame| is necessary to decode this
199 // or later frames. In that case copy the data instead.
200 if ((!canReusePreviousFrameBuffer(index) ||
201 !frame.takeBitmapDataIfWritable(&requiredPreviousFrame)) &&
202 !frame.copyBitmapData(requiredPreviousFrame)) {
203 setFailed();
204 return;
163 } 205 }
206
207 options.fHasPriorFrame = true;
164 } 208 }
165 } else { 209
166 for (; rowBegin != rowEnd; ++rowBegin, ++currentAddress) { 210 SkCodec::Result startIncrementalDecodeResult =
167 const size_t sourceValue = *rowBegin; 211 m_codec->startIncrementalDecode(imageInfo, frame.bitmap().getPixels(),
168 if ((sourceValue != transparentPixel) && 212 frame.bitmap().rowBytes(), &options,
169 (sourceValue < colorTable.size())) 213 nullptr, nullptr);
170 *currentAddress = colorTableIter[sourceValue]; 214 switch (startIncrementalDecodeResult) {
171 else 215 case SkCodec::kSuccess:
172 m_currentBufferSawAlpha = true; 216 break;
217 case SkCodec::kIncompleteInput:
218 return;
219 default:
220 setFailed();
221 return;
173 } 222 }
174 } 223 frame.setStatus(ImageFrame::FramePartial);
175 224 }
176 // Tell the frame to copy the row data if need be. 225
177 if (repeatCount > 1) 226 int rowsDecoded = 0;
178 buffer.copyRowNTimes(xBegin, xEnd, yBegin, yEnd); 227 SkCodec::Result incrementalDecodeResult =
179 228 m_codec->incrementalDecode(&rowsDecoded);
180 buffer.setPixelsChanged(true); 229 switch (incrementalDecodeResult) {
181 return true; 230 case SkCodec::kSuccess:
182 } 231 frame.setPixelsChanged(true);
183 232 frame.setStatus(ImageFrame::FrameComplete);
184 bool GIFImageDecoder::parseCompleted() const { 233 postDecodeProcessing(index);
185 return m_reader && m_reader->parseCompleted(); 234 break;
186 } 235 case SkCodec::kIncompleteInput:
187 236 if (frameIsCompleteAtIndex(index) || isAllDataReceived()) {
188 bool GIFImageDecoder::frameComplete(size_t frameIndex) { 237 setFailed();
189 // Initialize the frame if necessary. Some GIFs insert do-nothing frames, 238 return;
190 // in which case we never reach haveDecodedRow() before getting here. 239 }
191 if (!initFrameBuffer(frameIndex)) 240
192 return setFailed(); 241 {
193 242 IntRect remainingRect = frame.originalFrameRect();
194 if (!m_currentBufferSawAlpha) 243 remainingRect.setY(rowsDecoded);
195 correctAlphaWhenFrameBufferSawNoAlpha(frameIndex); 244 remainingRect.setHeight(remainingRect.height() - rowsDecoded);
196 245 frame.zeroFillFrameRect(remainingRect);
197 m_frameBufferCache[frameIndex].setStatus(ImageFrame::FrameComplete); 246 }
198 247
199 return true; 248 frame.setPixelsChanged(true);
200 } 249 break;
201 250 default:
202 void GIFImageDecoder::clearFrameBuffer(size_t frameIndex) {
203 if (m_reader &&
204 m_frameBufferCache[frameIndex].getStatus() == ImageFrame::FramePartial) {
205 // Reset the state of the partial frame in the reader so that the frame
206 // can be decoded again when requested.
207 m_reader->clearDecodeState(frameIndex);
208 }
209 ImageDecoder::clearFrameBuffer(frameIndex);
210 }
211
212 size_t GIFImageDecoder::decodeFrameCount() {
213 parse(GIFFrameCountQuery);
214 // If decoding fails, |m_reader| will have been destroyed. Instead of
215 // returning 0 in this case, return the existing number of frames. This way
216 // if we get halfway through the image before decoding fails, we won't
217 // suddenly start reporting that the image has zero frames.
218 return failed() ? m_frameBufferCache.size() : m_reader->imagesCount();
219 }
220
221 void GIFImageDecoder::initializeNewFrame(size_t index) {
222 ImageFrame* buffer = &m_frameBufferCache[index];
223 const GIFFrameContext* frameContext = m_reader->frameContext(index);
224 buffer->setOriginalFrameRect(
225 intersection(frameContext->frameRect(), IntRect(IntPoint(), size())));
226 buffer->setDuration(frameContext->delayTime());
227 buffer->setDisposalMethod(frameContext->getDisposalMethod());
228 buffer->setRequiredPreviousFrameIndex(
229 findRequiredPreviousFrame(index, false));
230 }
231
232 void GIFImageDecoder::decode(size_t index) {
233 parse(GIFFrameCountQuery);
234
235 if (failed())
236 return;
237
238 updateAggressivePurging(index);
239
240 Vector<size_t> framesToDecode = findFramesToDecode(index);
241 for (auto i = framesToDecode.rbegin(); i != framesToDecode.rend(); ++i) {
242 if (!m_reader->decode(*i)) {
243 setFailed(); 251 setFailed();
244 return; 252 return;
245 } 253 }
246 254 }
247 // If this returns false, we need more data to continue decoding. 255
248 if (!postDecodeProcessing(*i)) 256 bool GIFImageDecoder::canReusePreviousFrameBuffer(size_t index) const {
249 break; 257 DCHECK(index < m_frameBufferCache.size());
250 } 258
251 259 // If the current frame and the next frame depend on the same frame, we cannot
252 // It is also a fatal error if all data is received and we have decoded all 260 // reuse the old frame. We must preserve it for the next frame.
253 // frames available but the file is truncated. 261 //
254 if (index >= m_frameBufferCache.size() - 1 && isAllDataReceived() && 262 // However, if the current and next frame depend on different frames then we
255 m_reader && !m_reader->parseCompleted()) 263 // know the current frame is the last one to use the frame it depends on. That
256 setFailed(); 264 // means the current frame can reuse the previous frame buffer.
257 } 265 //
258 266 // If we do not have information about the next frame yet, we cannot assume it
259 void GIFImageDecoder::parse(GIFParseQuery query) { 267 // is safe to reuse the previous frame buffer.
260 if (failed()) 268
261 return; 269 if (index + 1 >= m_frameBufferCache.size())
262 270 return false;
263 if (!m_reader) { 271
264 m_reader = WTF::makeUnique<GIFImageReader>(this); 272 const ImageFrame& frame = m_frameBufferCache[index];
265 m_reader->setData(m_data); 273 size_t requiredFrameIndex = frame.requiredPreviousFrameIndex();
266 } 274
267 275 const ImageFrame& nextFrame = m_frameBufferCache[index + 1];
268 if (!m_reader->parse(query)) 276 size_t nextRequiredFrameIndex = nextFrame.requiredPreviousFrameIndex();
269 setFailed(); 277
270 } 278 return requiredFrameIndex != nextRequiredFrameIndex;
271
272 void GIFImageDecoder::onInitFrameBuffer(size_t frameIndex) {
273 m_currentBufferSawAlpha = false;
274 }
275
276 bool GIFImageDecoder::canReusePreviousFrameBuffer(size_t frameIndex) const {
277 DCHECK(frameIndex < m_frameBufferCache.size());
278 return m_frameBufferCache[frameIndex].getDisposalMethod() !=
279 ImageFrame::DisposeOverwritePrevious;
280 } 279 }
281 280
282 } // namespace blink 281 } // namespace blink
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698