1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #include "ImageLogging.h" // Must appear first
8 #include "gfxPlatform.h"
9 #include "mozilla/TelemetryHistogramEnums.h"
10 #include "nsWebPDecoder.h"
12 #include "RasterImage.h"
13 #include "SurfacePipeFactory.h"
15 using namespace mozilla::gfx
;
20 static LazyLogModule
sWebPLog("WebPDecoder");
22 nsWebPDecoder::nsWebPDecoder(RasterImage
* aImage
)
25 mBlend(BlendMethod::OVER
),
26 mDisposal(DisposalMethod::KEEP
),
27 mTimeout(FrameTimeout::Forever()),
28 mFormat(SurfaceFormat::OS_RGBX
),
33 mIteratorComplete(false),
35 mGotColorProfile(false) {
36 MOZ_LOG(sWebPLog
, LogLevel::Debug
,
37 ("[this=%p] nsWebPDecoder::nsWebPDecoder", this));
40 nsWebPDecoder::~nsWebPDecoder() {
41 MOZ_LOG(sWebPLog
, LogLevel::Debug
,
42 ("[this=%p] nsWebPDecoder::~nsWebPDecoder", this));
44 WebPIDelete(mDecoder
);
45 WebPFreeDecBuffer(&mBuffer
);
49 LexerResult
nsWebPDecoder::ReadData() {
51 MOZ_ASSERT(mLength
> 0);
53 WebPDemuxer
* demuxer
= nullptr;
54 bool complete
= mIteratorComplete
;
59 fragment
.bytes
= mData
;
60 fragment
.size
= mLength
;
62 demuxer
= WebPDemuxPartial(&fragment
, &state
);
63 if (state
== WEBP_DEMUX_PARSE_ERROR
) {
65 sWebPLog
, LogLevel::Error
,
66 ("[this=%p] nsWebPDecoder::ReadData -- demux parse error\n", this));
67 WebPDemuxDelete(demuxer
);
68 return LexerResult(TerminalState::FAILURE
);
71 if (state
== WEBP_DEMUX_PARSING_HEADER
) {
72 WebPDemuxDelete(demuxer
);
73 return LexerResult(Yield::NEED_MORE_DATA
);
77 MOZ_LOG(sWebPLog
, LogLevel::Error
,
78 ("[this=%p] nsWebPDecoder::ReadData -- no demuxer\n", this));
79 return LexerResult(TerminalState::FAILURE
);
82 complete
= complete
|| state
== WEBP_DEMUX_DONE
;
85 LexerResult
rv(TerminalState::FAILURE
);
87 rv
= ReadHeader(demuxer
, complete
);
89 rv
= ReadPayload(demuxer
, complete
);
92 WebPDemuxDelete(demuxer
);
96 LexerResult
nsWebPDecoder::DoDecode(SourceBufferIterator
& aIterator
,
97 IResumable
* aOnResume
) {
99 SourceBufferIterator::State state
= SourceBufferIterator::COMPLETE
;
100 if (!mIteratorComplete
) {
101 state
= aIterator
.AdvanceOrScheduleResume(SIZE_MAX
, aOnResume
);
103 // We need to remember since we can't advance a complete iterator.
104 mIteratorComplete
= state
== SourceBufferIterator::COMPLETE
;
107 if (state
== SourceBufferIterator::WAITING
) {
108 return LexerResult(Yield::NEED_MORE_DATA
);
111 LexerResult rv
= UpdateBuffer(aIterator
, state
);
112 if (rv
.is
<Yield
>() && rv
.as
<Yield
>() == Yield::NEED_MORE_DATA
) {
113 // We need to check the iterator to see if more is available before
114 // giving up unless we are already complete.
115 if (mIteratorComplete
) {
116 MOZ_LOG(sWebPLog
, LogLevel::Error
,
117 ("[this=%p] nsWebPDecoder::DoDecode -- read all data, "
120 return LexerResult(TerminalState::FAILURE
);
129 LexerResult
nsWebPDecoder::UpdateBuffer(SourceBufferIterator
& aIterator
,
130 SourceBufferIterator::State aState
) {
131 MOZ_ASSERT(!HasError(), "Shouldn't call DoDecode after error!");
134 case SourceBufferIterator::READY
:
135 if (!aIterator
.IsContiguous()) {
136 // We need to buffer. This should be rare, but expensive.
140 // For as long as we hold onto an iterator, we know the data pointers
141 // to the chunks cannot change underneath us, so save the pointer to
143 MOZ_ASSERT(mLength
== 0);
144 mData
= reinterpret_cast<const uint8_t*>(aIterator
.Data());
146 mLength
+= aIterator
.Length();
148 case SourceBufferIterator::COMPLETE
:
150 // We must have hit an error, such as an OOM, when buffering the
151 // first set of encoded data.
153 sWebPLog
, LogLevel::Error
,
154 ("[this=%p] nsWebPDecoder::DoDecode -- complete no data\n", this));
155 return LexerResult(TerminalState::FAILURE
);
159 MOZ_LOG(sWebPLog
, LogLevel::Error
,
160 ("[this=%p] nsWebPDecoder::DoDecode -- bad state\n", this));
161 return LexerResult(TerminalState::FAILURE
);
164 // We need to buffer. If we have no data buffered, we need to get everything
165 // from the first chunk of the source buffer before appending the new data.
166 if (mBufferedData
.empty()) {
168 MOZ_ASSERT(mLength
> 0);
170 if (!mBufferedData
.append(mData
, mLength
)) {
171 MOZ_LOG(sWebPLog
, LogLevel::Error
,
172 ("[this=%p] nsWebPDecoder::DoDecode -- oom, initialize %zu\n",
174 return LexerResult(TerminalState::FAILURE
);
177 MOZ_LOG(sWebPLog
, LogLevel::Debug
,
178 ("[this=%p] nsWebPDecoder::DoDecode -- buffered %zu bytes\n", this,
182 // Append the incremental data from the iterator.
183 if (!mBufferedData
.append(aIterator
.Data(), aIterator
.Length())) {
184 MOZ_LOG(sWebPLog
, LogLevel::Error
,
185 ("[this=%p] nsWebPDecoder::DoDecode -- oom, append %zu on %zu\n",
186 this, aIterator
.Length(), mBufferedData
.length()));
187 return LexerResult(TerminalState::FAILURE
);
190 MOZ_LOG(sWebPLog
, LogLevel::Debug
,
191 ("[this=%p] nsWebPDecoder::DoDecode -- buffered %zu -> %zu bytes\n",
192 this, aIterator
.Length(), mBufferedData
.length()));
193 mData
= mBufferedData
.begin();
194 mLength
= mBufferedData
.length();
198 nsresult
nsWebPDecoder::CreateFrame(const OrientedIntRect
& aFrameRect
) {
199 MOZ_ASSERT(HasSize());
200 MOZ_ASSERT(!mDecoder
);
203 sWebPLog
, LogLevel::Debug
,
204 ("[this=%p] nsWebPDecoder::CreateFrame -- frame %u, (%d, %d) %d x %d\n",
205 this, mCurrentFrame
, aFrameRect
.x
, aFrameRect
.y
, aFrameRect
.width
,
208 if (aFrameRect
.width
<= 0 || aFrameRect
.height
<= 0) {
209 MOZ_LOG(sWebPLog
, LogLevel::Error
,
210 ("[this=%p] nsWebPDecoder::CreateFrame -- bad frame rect\n", this));
211 return NS_ERROR_FAILURE
;
214 // If this is our first frame in an animation and it doesn't cover the
215 // full frame, then we are transparent even if there is no alpha
216 if (mCurrentFrame
== 0 && !aFrameRect
.IsEqualEdges(FullFrame())) {
217 MOZ_ASSERT(HasAnimation());
218 mFormat
= SurfaceFormat::OS_RGBA
;
219 PostHasTransparency();
222 WebPInitDecBuffer(&mBuffer
);
224 switch (SurfaceFormat::OS_RGBA
) {
225 case SurfaceFormat::B8G8R8A8
:
226 mBuffer
.colorspace
= MODE_BGRA
;
228 case SurfaceFormat::A8R8G8B8
:
229 mBuffer
.colorspace
= MODE_ARGB
;
231 case SurfaceFormat::R8G8B8A8
:
232 mBuffer
.colorspace
= MODE_RGBA
;
235 MOZ_ASSERT_UNREACHABLE("Unknown OS_RGBA");
236 return NS_ERROR_FAILURE
;
239 mDecoder
= WebPINewDecoder(&mBuffer
);
241 MOZ_LOG(sWebPLog
, LogLevel::Error
,
242 ("[this=%p] nsWebPDecoder::CreateFrame -- create decoder error\n",
244 return NS_ERROR_FAILURE
;
247 // WebP doesn't guarantee that the alpha generated matches the hint in the
248 // header, so we always need to claim the input is BGRA. If the output is
249 // BGRX, swizzling will mask off the alpha channel.
250 SurfaceFormat inFormat
= SurfaceFormat::OS_RGBA
;
252 SurfacePipeFlags pipeFlags
= SurfacePipeFlags();
253 if (mFormat
== SurfaceFormat::OS_RGBA
&&
254 !(GetSurfaceFlags() & SurfaceFlags::NO_PREMULTIPLY_ALPHA
)) {
255 pipeFlags
|= SurfacePipeFlags::PREMULTIPLY_ALPHA
;
258 Maybe
<AnimationParams
> animParams
;
259 if (!IsFirstFrameDecode()) {
260 animParams
.emplace(aFrameRect
.ToUnknownRect(), mTimeout
, mCurrentFrame
,
264 Maybe
<SurfacePipe
> pipe
= SurfacePipeFactory::CreateSurfacePipe(
265 this, Size(), OutputSize(), aFrameRect
, inFormat
, mFormat
, animParams
,
266 mTransform
, pipeFlags
);
268 MOZ_LOG(sWebPLog
, LogLevel::Error
,
269 ("[this=%p] nsWebPDecoder::CreateFrame -- no pipe\n", this));
270 return NS_ERROR_FAILURE
;
273 mFrameRect
= aFrameRect
;
274 mPipe
= std::move(*pipe
);
278 void nsWebPDecoder::EndFrame() {
279 MOZ_ASSERT(HasSize());
280 MOZ_ASSERT(mDecoder
);
282 auto opacity
= mFormat
== SurfaceFormat::OS_RGBA
? Opacity::SOME_TRANSPARENCY
283 : Opacity::FULLY_OPAQUE
;
285 MOZ_LOG(sWebPLog
, LogLevel::Debug
,
286 ("[this=%p] nsWebPDecoder::EndFrame -- frame %u, opacity %d, "
287 "disposal %d, timeout %d, blend %d\n",
288 this, mCurrentFrame
, (int)opacity
, (int)mDisposal
,
289 mTimeout
.AsEncodedValueDeprecated(), (int)mBlend
));
291 PostFrameStop(opacity
);
292 WebPIDelete(mDecoder
);
293 WebPFreeDecBuffer(&mBuffer
);
299 void nsWebPDecoder::ApplyColorProfile(const char* aProfile
, size_t aLength
) {
300 MOZ_ASSERT(!mGotColorProfile
);
301 mGotColorProfile
= true;
303 if (mCMSMode
== CMSMode::Off
|| !GetCMSOutputProfile() ||
304 (mCMSMode
== CMSMode::TaggedOnly
&& !aProfile
)) {
309 MOZ_LOG(sWebPLog
, LogLevel::Debug
,
310 ("[this=%p] nsWebPDecoder::ApplyColorProfile -- not tagged, use "
313 mTransform
= GetCMSsRGBTransform(SurfaceFormat::OS_RGBA
);
317 mInProfile
= qcms_profile_from_memory(aProfile
, aLength
);
320 sWebPLog
, LogLevel::Error
,
321 ("[this=%p] nsWebPDecoder::ApplyColorProfile -- bad color profile\n",
326 uint32_t profileSpace
= qcms_profile_get_color_space(mInProfile
);
327 if (profileSpace
!= icSigRgbData
) {
328 // WebP doesn't produce grayscale data, this must be corrupt.
329 MOZ_LOG(sWebPLog
, LogLevel::Error
,
330 ("[this=%p] nsWebPDecoder::ApplyColorProfile -- ignoring non-rgb "
336 // Calculate rendering intent.
337 int intent
= gfxPlatform::GetRenderingIntent();
339 intent
= qcms_profile_get_rendering_intent(mInProfile
);
342 // Create the color management transform.
343 qcms_data_type type
= gfxPlatform::GetCMSOSRGBAType();
344 mTransform
= qcms_transform_create(mInProfile
, type
, GetCMSOutputProfile(),
345 type
, (qcms_intent
)intent
);
346 MOZ_LOG(sWebPLog
, LogLevel::Debug
,
347 ("[this=%p] nsWebPDecoder::ApplyColorProfile -- use tagged "
352 LexerResult
nsWebPDecoder::ReadHeader(WebPDemuxer
* aDemuxer
, bool aIsComplete
) {
353 MOZ_ASSERT(aDemuxer
);
356 sWebPLog
, LogLevel::Debug
,
357 ("[this=%p] nsWebPDecoder::ReadHeader -- %zu bytes\n", this, mLength
));
359 uint32_t flags
= WebPDemuxGetI(aDemuxer
, WEBP_FF_FORMAT_FLAGS
);
361 if (!IsMetadataDecode() && !mGotColorProfile
) {
362 if (flags
& WebPFeatureFlags::ICCP_FLAG
) {
363 WebPChunkIterator iter
;
364 if (WebPDemuxGetChunk(aDemuxer
, "ICCP", 1, &iter
)) {
365 ApplyColorProfile(reinterpret_cast<const char*>(iter
.chunk
.bytes
),
367 WebPDemuxReleaseChunkIterator(&iter
);
371 return LexerResult(Yield::NEED_MORE_DATA
);
374 MOZ_LOG(sWebPLog
, LogLevel::Warning
,
375 ("[this=%p] nsWebPDecoder::ReadHeader header specified ICCP "
376 "but no ICCP chunk found, ignoring\n",
379 ApplyColorProfile(nullptr, 0);
382 ApplyColorProfile(nullptr, 0);
386 if (flags
& WebPFeatureFlags::ANIMATION_FLAG
) {
387 // A metadata decode expects to get the correct first frame timeout which
388 // sadly is not provided by the normal WebP header parsing.
390 if (!WebPDemuxGetFrame(aDemuxer
, 1, &iter
)) {
391 return aIsComplete
? LexerResult(TerminalState::FAILURE
)
392 : LexerResult(Yield::NEED_MORE_DATA
);
395 PostIsAnimated(FrameTimeout::FromRawMilliseconds(iter
.duration
));
396 WebPDemuxReleaseIterator(&iter
);
398 // Single frames don't need a demuxer to be created.
399 mNeedDemuxer
= false;
402 uint32_t width
= WebPDemuxGetI(aDemuxer
, WEBP_FF_CANVAS_WIDTH
);
403 uint32_t height
= WebPDemuxGetI(aDemuxer
, WEBP_FF_CANVAS_HEIGHT
);
404 if (width
> INT32_MAX
|| height
> INT32_MAX
) {
405 return LexerResult(TerminalState::FAILURE
);
408 PostSize(width
, height
);
410 bool alpha
= flags
& WebPFeatureFlags::ALPHA_FLAG
;
412 mFormat
= SurfaceFormat::OS_RGBA
;
413 PostHasTransparency();
416 MOZ_LOG(sWebPLog
, LogLevel::Debug
,
417 ("[this=%p] nsWebPDecoder::ReadHeader -- %u x %u, alpha %d, "
418 "animation %d, metadata decode %d, first frame decode %d\n",
419 this, width
, height
, alpha
, HasAnimation(), IsMetadataDecode(),
420 IsFirstFrameDecode()));
422 if (IsMetadataDecode()) {
423 return LexerResult(TerminalState::SUCCESS
);
426 return ReadPayload(aDemuxer
, aIsComplete
);
429 LexerResult
nsWebPDecoder::ReadPayload(WebPDemuxer
* aDemuxer
,
431 if (!HasAnimation()) {
432 auto rv
= ReadSingle(mData
, mLength
, FullFrame());
433 if (rv
.is
<TerminalState
>() &&
434 rv
.as
<TerminalState
>() == TerminalState::SUCCESS
) {
439 return ReadMultiple(aDemuxer
, aIsComplete
);
442 LexerResult
nsWebPDecoder::ReadSingle(const uint8_t* aData
, size_t aLength
,
443 const OrientedIntRect
& aFrameRect
) {
444 MOZ_ASSERT(!IsMetadataDecode());
446 MOZ_ASSERT(aLength
> 0);
449 sWebPLog
, LogLevel::Debug
,
450 ("[this=%p] nsWebPDecoder::ReadSingle -- %zu bytes\n", this, aLength
));
452 if (!mDecoder
&& NS_FAILED(CreateFrame(aFrameRect
))) {
453 return LexerResult(TerminalState::FAILURE
);
458 VP8StatusCode status
= WebPIUpdate(mDecoder
, aData
, aLength
);
463 case VP8_STATUS_SUSPENDED
:
467 MOZ_LOG(sWebPLog
, LogLevel::Error
,
468 ("[this=%p] nsWebPDecoder::ReadSingle -- append error %d\n",
470 return LexerResult(TerminalState::FAILURE
);
478 WebPIDecGetRGB(mDecoder
, &lastRow
, &width
, &height
, &stride
);
481 sWebPLog
, LogLevel::Debug
,
482 ("[this=%p] nsWebPDecoder::ReadSingle -- complete %d, read %d rows, "
483 "has %d rows available\n",
484 this, complete
, mLastRow
, lastRow
));
486 if (!rowStart
|| lastRow
== -1 || lastRow
== mLastRow
) {
487 return LexerResult(Yield::NEED_MORE_DATA
);
490 if (width
!= mFrameRect
.width
|| height
!= mFrameRect
.height
||
491 stride
< mFrameRect
.width
* 4 || lastRow
> mFrameRect
.height
) {
492 MOZ_LOG(sWebPLog
, LogLevel::Error
,
493 ("[this=%p] nsWebPDecoder::ReadSingle -- bad (w,h,s) = (%d, %d, "
495 this, width
, height
, stride
));
496 return LexerResult(TerminalState::FAILURE
);
499 for (int row
= mLastRow
; row
< lastRow
; row
++) {
500 uint32_t* src
= reinterpret_cast<uint32_t*>(rowStart
+ row
* stride
);
501 WriteState result
= mPipe
.WriteBuffer(src
);
503 Maybe
<SurfaceInvalidRect
> invalidRect
= mPipe
.TakeInvalidRect();
505 PostInvalidation(invalidRect
->mInputSpaceRect
,
506 Some(invalidRect
->mOutputSpaceRect
));
509 if (result
== WriteState::FAILURE
) {
510 MOZ_LOG(sWebPLog
, LogLevel::Error
,
511 ("[this=%p] nsWebPDecoder::ReadSingle -- write pixels error\n",
513 return LexerResult(TerminalState::FAILURE
);
516 if (result
== WriteState::FINISHED
) {
517 MOZ_ASSERT(row
== lastRow
- 1, "There was more data to read?");
527 return LexerResult(Yield::NEED_MORE_DATA
);
531 return LexerResult(TerminalState::SUCCESS
);
534 LexerResult
nsWebPDecoder::ReadMultiple(WebPDemuxer
* aDemuxer
,
536 MOZ_ASSERT(!IsMetadataDecode());
537 MOZ_ASSERT(aDemuxer
);
539 MOZ_LOG(sWebPLog
, LogLevel::Debug
,
540 ("[this=%p] nsWebPDecoder::ReadMultiple\n", this));
542 bool complete
= aIsComplete
;
544 auto rv
= LexerResult(Yield::NEED_MORE_DATA
);
545 if (WebPDemuxGetFrame(aDemuxer
, mCurrentFrame
+ 1, &iter
)) {
546 switch (iter
.blend_method
) {
548 mBlend
= BlendMethod::OVER
;
550 case WEBP_MUX_NO_BLEND
:
551 mBlend
= BlendMethod::SOURCE
;
554 MOZ_ASSERT_UNREACHABLE("Unhandled blend method");
558 switch (iter
.dispose_method
) {
559 case WEBP_MUX_DISPOSE_NONE
:
560 mDisposal
= DisposalMethod::KEEP
;
562 case WEBP_MUX_DISPOSE_BACKGROUND
:
563 mDisposal
= DisposalMethod::CLEAR
;
566 MOZ_ASSERT_UNREACHABLE("Unhandled dispose method");
570 mFormat
= iter
.has_alpha
|| mCurrentFrame
> 0 ? SurfaceFormat::OS_RGBA
571 : SurfaceFormat::OS_RGBX
;
572 mTimeout
= FrameTimeout::FromRawMilliseconds(iter
.duration
);
573 OrientedIntRect
frameRect(iter
.x_offset
, iter
.y_offset
, iter
.width
,
576 rv
= ReadSingle(iter
.fragment
.bytes
, iter
.fragment
.size
, frameRect
);
577 complete
= complete
&& !WebPDemuxNextFrame(&iter
);
578 WebPDemuxReleaseIterator(&iter
);
581 if (rv
.is
<TerminalState
>() &&
582 rv
.as
<TerminalState
>() == TerminalState::SUCCESS
) {
583 // If we extracted one frame, and it is not the last, we need to yield to
584 // the lexer to allow the upper layers to acknowledge the frame.
585 if (!complete
&& !IsFirstFrameDecode()) {
586 rv
= LexerResult(Yield::OUTPUT_AVAILABLE
);
588 uint32_t loopCount
= WebPDemuxGetI(aDemuxer
, WEBP_FF_LOOP_COUNT
);
590 MOZ_LOG(sWebPLog
, LogLevel::Debug
,
591 ("[this=%p] nsWebPDecoder::ReadMultiple -- loop count %u\n", this,
593 PostDecodeDone(loopCount
- 1);
600 Maybe
<Telemetry::HistogramID
> nsWebPDecoder::SpeedHistogram() const {
601 return Some(Telemetry::IMAGE_DECODE_SPEED_WEBP
);
605 } // namespace mozilla