Backed out changeset b858a0740582 (bug 1848694) for causing build bustages on dom...
[gecko.git] / image / decoders / nsWebPDecoder.cpp
blobe7467f0066017736105c13ae4fea041ce42731ee
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;
17 namespace mozilla {
18 namespace image {
20 static LazyLogModule sWebPLog("WebPDecoder");
22 nsWebPDecoder::nsWebPDecoder(RasterImage* aImage)
23 : Decoder(aImage),
24 mDecoder(nullptr),
25 mBlend(BlendMethod::OVER),
26 mDisposal(DisposalMethod::KEEP),
27 mTimeout(FrameTimeout::Forever()),
28 mFormat(SurfaceFormat::OS_RGBX),
29 mLastRow(0),
30 mCurrentFrame(0),
31 mData(nullptr),
32 mLength(0),
33 mIteratorComplete(false),
34 mNeedDemuxer(true),
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));
43 if (mDecoder) {
44 WebPIDelete(mDecoder);
45 WebPFreeDecBuffer(&mBuffer);
49 LexerResult nsWebPDecoder::ReadData() {
50 MOZ_ASSERT(mData);
51 MOZ_ASSERT(mLength > 0);
53 WebPDemuxer* demuxer = nullptr;
54 bool complete = mIteratorComplete;
56 if (mNeedDemuxer) {
57 WebPDemuxState state;
58 WebPData fragment;
59 fragment.bytes = mData;
60 fragment.size = mLength;
62 demuxer = WebPDemuxPartial(&fragment, &state);
63 if (state == WEBP_DEMUX_PARSE_ERROR) {
64 MOZ_LOG(
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);
76 if (!demuxer) {
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);
86 if (!HasSize()) {
87 rv = ReadHeader(demuxer, complete);
88 } else {
89 rv = ReadPayload(demuxer, complete);
92 WebPDemuxDelete(demuxer);
93 return rv;
96 LexerResult nsWebPDecoder::DoDecode(SourceBufferIterator& aIterator,
97 IResumable* aOnResume) {
98 while (true) {
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, "
118 "but needs more\n",
119 this));
120 return LexerResult(TerminalState::FAILURE);
122 continue;
125 return rv;
129 LexerResult nsWebPDecoder::UpdateBuffer(SourceBufferIterator& aIterator,
130 SourceBufferIterator::State aState) {
131 MOZ_ASSERT(!HasError(), "Shouldn't call DoDecode after error!");
133 switch (aState) {
134 case SourceBufferIterator::READY:
135 if (!aIterator.IsContiguous()) {
136 // We need to buffer. This should be rare, but expensive.
137 break;
139 if (!mData) {
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
142 // the first block.
143 MOZ_ASSERT(mLength == 0);
144 mData = reinterpret_cast<const uint8_t*>(aIterator.Data());
146 mLength += aIterator.Length();
147 return ReadData();
148 case SourceBufferIterator::COMPLETE:
149 if (!mData) {
150 // We must have hit an error, such as an OOM, when buffering the
151 // first set of encoded data.
152 MOZ_LOG(
153 sWebPLog, LogLevel::Error,
154 ("[this=%p] nsWebPDecoder::DoDecode -- complete no data\n", this));
155 return LexerResult(TerminalState::FAILURE);
157 return ReadData();
158 default:
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()) {
167 MOZ_ASSERT(mData);
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",
173 this, mLength));
174 return LexerResult(TerminalState::FAILURE);
177 MOZ_LOG(sWebPLog, LogLevel::Debug,
178 ("[this=%p] nsWebPDecoder::DoDecode -- buffered %zu bytes\n", this,
179 mLength));
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();
195 return ReadData();
198 nsresult nsWebPDecoder::CreateFrame(const OrientedIntRect& aFrameRect) {
199 MOZ_ASSERT(HasSize());
200 MOZ_ASSERT(!mDecoder);
202 MOZ_LOG(
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,
206 aFrameRect.height));
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;
227 break;
228 case SurfaceFormat::A8R8G8B8:
229 mBuffer.colorspace = MODE_ARGB;
230 break;
231 case SurfaceFormat::R8G8B8A8:
232 mBuffer.colorspace = MODE_RGBA;
233 break;
234 default:
235 MOZ_ASSERT_UNREACHABLE("Unknown OS_RGBA");
236 return NS_ERROR_FAILURE;
239 mDecoder = WebPINewDecoder(&mBuffer);
240 if (!mDecoder) {
241 MOZ_LOG(sWebPLog, LogLevel::Error,
242 ("[this=%p] nsWebPDecoder::CreateFrame -- create decoder error\n",
243 this));
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,
261 mBlend, mDisposal);
264 Maybe<SurfacePipe> pipe = SurfacePipeFactory::CreateSurfacePipe(
265 this, Size(), OutputSize(), aFrameRect, inFormat, mFormat, animParams,
266 mTransform, pipeFlags);
267 if (!pipe) {
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);
275 return NS_OK;
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);
294 mDecoder = nullptr;
295 mLastRow = 0;
296 ++mCurrentFrame;
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)) {
305 return;
308 if (!aProfile) {
309 MOZ_LOG(sWebPLog, LogLevel::Debug,
310 ("[this=%p] nsWebPDecoder::ApplyColorProfile -- not tagged, use "
311 "sRGB transform\n",
312 this));
313 mTransform = GetCMSsRGBTransform(SurfaceFormat::OS_RGBA);
314 return;
317 mInProfile = qcms_profile_from_memory(aProfile, aLength);
318 if (!mInProfile) {
319 MOZ_LOG(
320 sWebPLog, LogLevel::Error,
321 ("[this=%p] nsWebPDecoder::ApplyColorProfile -- bad color profile\n",
322 this));
323 return;
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 "
331 "color profile\n",
332 this));
333 return;
336 // Calculate rendering intent.
337 int intent = gfxPlatform::GetRenderingIntent();
338 if (intent == -1) {
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 "
348 "transform\n",
349 this));
352 LexerResult nsWebPDecoder::ReadHeader(WebPDemuxer* aDemuxer, bool aIsComplete) {
353 MOZ_ASSERT(aDemuxer);
355 MOZ_LOG(
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),
366 iter.chunk.size);
367 WebPDemuxReleaseChunkIterator(&iter);
369 } else {
370 if (!aIsComplete) {
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",
377 this));
379 ApplyColorProfile(nullptr, 0);
381 } else {
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.
389 WebPIterator iter;
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);
397 } else {
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;
411 if (alpha) {
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,
430 bool aIsComplete) {
431 if (!HasAnimation()) {
432 auto rv = ReadSingle(mData, mLength, FullFrame());
433 if (rv.is<TerminalState>() &&
434 rv.as<TerminalState>() == TerminalState::SUCCESS) {
435 PostDecodeDone();
437 return rv;
439 return ReadMultiple(aDemuxer, aIsComplete);
442 LexerResult nsWebPDecoder::ReadSingle(const uint8_t* aData, size_t aLength,
443 const OrientedIntRect& aFrameRect) {
444 MOZ_ASSERT(!IsMetadataDecode());
445 MOZ_ASSERT(aData);
446 MOZ_ASSERT(aLength > 0);
448 MOZ_LOG(
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);
456 bool complete;
457 do {
458 VP8StatusCode status = WebPIUpdate(mDecoder, aData, aLength);
459 switch (status) {
460 case VP8_STATUS_OK:
461 complete = true;
462 break;
463 case VP8_STATUS_SUSPENDED:
464 complete = false;
465 break;
466 default:
467 MOZ_LOG(sWebPLog, LogLevel::Error,
468 ("[this=%p] nsWebPDecoder::ReadSingle -- append error %d\n",
469 this, status));
470 return LexerResult(TerminalState::FAILURE);
473 int lastRow = -1;
474 int width = 0;
475 int height = 0;
476 int stride = 0;
477 uint8_t* rowStart =
478 WebPIDecGetRGB(mDecoder, &lastRow, &width, &height, &stride);
480 MOZ_LOG(
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, "
494 "%d)\n",
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();
504 if (invalidRect) {
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",
512 this));
513 return LexerResult(TerminalState::FAILURE);
516 if (result == WriteState::FINISHED) {
517 MOZ_ASSERT(row == lastRow - 1, "There was more data to read?");
518 complete = true;
519 break;
523 mLastRow = lastRow;
524 } while (!complete);
526 if (!complete) {
527 return LexerResult(Yield::NEED_MORE_DATA);
530 EndFrame();
531 return LexerResult(TerminalState::SUCCESS);
534 LexerResult nsWebPDecoder::ReadMultiple(WebPDemuxer* aDemuxer,
535 bool aIsComplete) {
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;
543 WebPIterator iter;
544 auto rv = LexerResult(Yield::NEED_MORE_DATA);
545 if (WebPDemuxGetFrame(aDemuxer, mCurrentFrame + 1, &iter)) {
546 switch (iter.blend_method) {
547 case WEBP_MUX_BLEND:
548 mBlend = BlendMethod::OVER;
549 break;
550 case WEBP_MUX_NO_BLEND:
551 mBlend = BlendMethod::SOURCE;
552 break;
553 default:
554 MOZ_ASSERT_UNREACHABLE("Unhandled blend method");
555 break;
558 switch (iter.dispose_method) {
559 case WEBP_MUX_DISPOSE_NONE:
560 mDisposal = DisposalMethod::KEEP;
561 break;
562 case WEBP_MUX_DISPOSE_BACKGROUND:
563 mDisposal = DisposalMethod::CLEAR;
564 break;
565 default:
566 MOZ_ASSERT_UNREACHABLE("Unhandled dispose method");
567 break;
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,
574 iter.height);
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);
587 } else {
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,
592 loopCount));
593 PostDecodeDone(loopCount - 1);
597 return rv;
600 Maybe<Telemetry::HistogramID> nsWebPDecoder::SpeedHistogram() const {
601 return Some(Telemetry::IMAGE_DECODE_SPEED_WEBP);
604 } // namespace image
605 } // namespace mozilla