1/*
2 * Copyright (C) 2006, 2016 Apple Inc. All rights reserved.
3 * Copyright (C) 2008-2009 Torch Mobile, Inc.
4 * Copyright (C) Research In Motion Limited 2009-2010. All rights reserved.
5 * Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies)
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
20 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
21 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
22 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
23 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
24 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 */
28
29#pragma once
30
31#include "ImageDecoder.h"
32#include "IntRect.h"
33#include "ScalableImageDecoderFrame.h"
34#include "SharedBuffer.h"
35#include <wtf/Assertions.h>
36#include <wtf/Lock.h>
37#include <wtf/RefPtr.h>
38#include <wtf/Vector.h>
39#include <wtf/text/WTFString.h>
40
41namespace WebCore {
42
43// ScalableImageDecoder is a base for all format-specific decoders
44// (e.g. JPEGImageDecoder). This base manages the ScalableImageDecoderFrame cache.
45
46class ScalableImageDecoder : public ImageDecoder {
47 WTF_MAKE_NONCOPYABLE(ScalableImageDecoder); WTF_MAKE_FAST_ALLOCATED;
48public:
49 ScalableImageDecoder(AlphaOption alphaOption, GammaAndColorProfileOption gammaAndColorProfileOption)
50 : m_premultiplyAlpha(alphaOption == AlphaOption::Premultiplied)
51 , m_ignoreGammaAndColorProfile(gammaAndColorProfileOption == GammaAndColorProfileOption::Ignored)
52 {
53 }
54
55 virtual ~ScalableImageDecoder()
56 {
57 }
58
59 static bool supportsMediaType(MediaType type) { return type == MediaType::Image; }
60
61 // Returns nullptr if we can't sniff a supported type from the provided data (possibly
62 // because there isn't enough data yet).
63 static RefPtr<ScalableImageDecoder> create(SharedBuffer& data, AlphaOption, GammaAndColorProfileOption);
64
65 bool premultiplyAlpha() const { return m_premultiplyAlpha; }
66
67 bool isAllDataReceived() const override
68 {
69 ASSERT(!m_decodingSizeFromSetData);
70 return m_encodedDataStatus == EncodedDataStatus::Complete;
71 }
72
73 void setData(SharedBuffer& data, bool allDataReceived) override
74 {
75 LockHolder lockHolder(m_mutex);
76 if (m_encodedDataStatus == EncodedDataStatus::Error)
77 return;
78
79 m_data = &data;
80 if (m_encodedDataStatus == EncodedDataStatus::TypeAvailable) {
81 m_decodingSizeFromSetData = true;
82 tryDecodeSize(allDataReceived);
83 m_decodingSizeFromSetData = false;
84 }
85
86 if (m_encodedDataStatus == EncodedDataStatus::Error)
87 return;
88
89 if (allDataReceived) {
90 ASSERT(m_encodedDataStatus == EncodedDataStatus::SizeAvailable);
91 m_encodedDataStatus = EncodedDataStatus::Complete;
92 }
93 }
94
95 EncodedDataStatus encodedDataStatus() const override { return m_encodedDataStatus; }
96
97 bool isSizeAvailable() const override { return m_encodedDataStatus >= EncodedDataStatus::SizeAvailable; }
98
99 IntSize size() const override { return isSizeAvailable() ? m_size : IntSize(); }
100
101 IntSize scaledSize()
102 {
103 return m_scaled ? IntSize(m_scaledColumns.size(), m_scaledRows.size()) : size();
104 }
105
106 // This will only differ from size() for ICO (where each frame is a
107 // different icon) or other formats where different frames are different
108 // sizes. This does NOT differ from size() for GIF, since decoding GIFs
109 // composites any smaller frames against previous frames to create full-
110 // size frames.
111 IntSize frameSizeAtIndex(size_t, SubsamplingLevel) const override
112 {
113 return size();
114 }
115
116 // Returns whether the size is legal (i.e. not going to result in
117 // overflow elsewhere). If not, marks decoding as failed.
118 virtual bool setSize(const IntSize& size)
119 {
120 if (ImageBackingStore::isOverSize(size))
121 return setFailed();
122 m_size = size;
123 m_encodedDataStatus = EncodedDataStatus::SizeAvailable;
124 return true;
125 }
126
127 // Lazily-decodes enough of the image to get the frame count (if
128 // possible), without decoding the individual frames.
129 // FIXME: Right now that has to be done by each subclass; factor the
130 // decode call out and use it here.
131 size_t frameCount() const override { return 1; }
132
133 RepetitionCount repetitionCount() const override { return RepetitionCountNone; }
134
135 // Decodes as much of the requested frame as possible, and returns an
136 // ScalableImageDecoder-owned pointer.
137 virtual ScalableImageDecoderFrame* frameBufferAtIndex(size_t) = 0;
138
139 bool frameIsCompleteAtIndex(size_t) const override;
140
141 // Make the best effort guess to check if the requested frame has alpha channel.
142 bool frameHasAlphaAtIndex(size_t) const override;
143
144 // Number of bytes in the decoded frame requested. Return 0 if not yet decoded.
145 unsigned frameBytesAtIndex(size_t, SubsamplingLevel = SubsamplingLevel::Default) const override;
146
147 Seconds frameDurationAtIndex(size_t) const final;
148
149 NativeImagePtr createFrameImageAtIndex(size_t, SubsamplingLevel = SubsamplingLevel::Default, const DecodingOptions& = DecodingOptions(DecodingMode::Synchronous)) override;
150
151 void setIgnoreGammaAndColorProfile(bool flag) { m_ignoreGammaAndColorProfile = flag; }
152 bool ignoresGammaAndColorProfile() const { return m_ignoreGammaAndColorProfile; }
153
154 ImageOrientation frameOrientationAtIndex(size_t) const override { return m_orientation; }
155
156 bool frameAllowSubsamplingAtIndex(size_t) const override { return false; }
157
158 enum { ICCColorProfileHeaderLength = 128 };
159
160 static bool rgbColorProfile(const char* profileData, unsigned profileLength)
161 {
162 ASSERT_UNUSED(profileLength, profileLength >= ICCColorProfileHeaderLength);
163
164 return !memcmp(&profileData[16], "RGB ", 4);
165 }
166
167 size_t bytesDecodedToDetermineProperties() const final { return 0; }
168
169 static SubsamplingLevel subsamplingLevelForScale(float, SubsamplingLevel) { return SubsamplingLevel::Default; }
170
171 static bool inputDeviceColorProfile(const char* profileData, unsigned profileLength)
172 {
173 ASSERT_UNUSED(profileLength, profileLength >= ICCColorProfileHeaderLength);
174
175 return !memcmp(&profileData[12], "mntr", 4) || !memcmp(&profileData[12], "scnr", 4);
176 }
177
178 // Sets the "decode failure" flag. For caller convenience (since so
179 // many callers want to return false after calling this), returns false
180 // to enable easy tailcalling. Subclasses may override this to also
181 // clean up any local data.
182 virtual bool setFailed()
183 {
184 m_encodedDataStatus = EncodedDataStatus::Error;
185 return false;
186 }
187
188 bool failed() const { return m_encodedDataStatus == EncodedDataStatus::Error; }
189
190 // Clears decoded pixel data from before the provided frame unless that
191 // data may be needed to decode future frames (e.g. due to GIF frame
192 // compositing).
193 void clearFrameBufferCache(size_t) override { }
194
195 // If the image has a cursor hot-spot, stores it in the argument
196 // and returns true. Otherwise returns false.
197 Optional<IntPoint> hotSpot() const override { return WTF::nullopt; }
198
199protected:
200 void prepareScaleDataIfNecessary();
201 int upperBoundScaledX(int origX, int searchStart = 0);
202 int lowerBoundScaledX(int origX, int searchStart = 0);
203 int upperBoundScaledY(int origY, int searchStart = 0);
204 int lowerBoundScaledY(int origY, int searchStart = 0);
205 int scaledY(int origY, int searchStart = 0);
206
207 RefPtr<SharedBuffer> m_data; // The encoded data.
208 Vector<ScalableImageDecoderFrame, 1> m_frameBufferCache;
209 mutable Lock m_mutex;
210 bool m_scaled { false };
211 Vector<int> m_scaledColumns;
212 Vector<int> m_scaledRows;
213 bool m_premultiplyAlpha;
214 bool m_ignoreGammaAndColorProfile;
215 ImageOrientation m_orientation;
216
217private:
218 virtual void tryDecodeSize(bool) = 0;
219
220 IntSize m_size;
221 EncodedDataStatus m_encodedDataStatus { EncodedDataStatus::TypeAvailable };
222 bool m_decodingSizeFromSetData { false };
223
224 // FIXME: Evaluate the need for decoded data scaling. m_scaled,
225 // m_scaledColumns and m_scaledRows are member variables that are
226 // affected by this value, and are not used at all since the value
227 // is negavite (see prepareScaleDataIfNecessary()).
228 static const int m_maxNumPixels { -1 };
229};
230
231} // namespace WebCore
232