forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 1
/
RasterImage.cpp
1777 lines (1474 loc) · 50.2 KB
/
RasterImage.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// Must #include ImageLogging.h before any IPDL-generated files or other files
// that #include prlog.h
#include "ImageLogging.h"
#include "RasterImage.h"
#include "gfxPlatform.h"
#include "nsComponentManagerUtils.h"
#include "nsError.h"
#include "Decoder.h"
#include "prenv.h"
#include "prsystem.h"
#include "IDecodingTask.h"
#include "ImageContainer.h"
#include "ImageRegion.h"
#include "Layers.h"
#include "LookupResult.h"
#include "nsIConsoleService.h"
#include "nsIInputStream.h"
#include "nsIScriptError.h"
#include "nsISupportsPrimitives.h"
#include "nsPresContext.h"
#include "SourceBuffer.h"
#include "SurfaceCache.h"
#include "FrameAnimator.h"
#include "gfxContext.h"
#include "mozilla/gfx/2D.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/Likely.h"
#include "mozilla/RefPtr.h"
#include "mozilla/Move.h"
#include "mozilla/MemoryReporting.h"
#include "mozilla/Services.h"
#include <stdint.h>
#include "mozilla/Telemetry.h"
#include "mozilla/TimeStamp.h"
#include "mozilla/Tuple.h"
#include "mozilla/ClearOnShutdown.h"
#include "mozilla/gfx/Scale.h"
#include "GeckoProfiler.h"
#include "gfx2DGlue.h"
#include "gfxPrefs.h"
#include <algorithm>
namespace mozilla {
using namespace gfx;
using namespace layers;
namespace image {
using std::ceil;
using std::min;
#ifndef DEBUG
NS_IMPL_ISUPPORTS(RasterImage, imgIContainer, nsIProperties)
#else
NS_IMPL_ISUPPORTS(RasterImage, imgIContainer, nsIProperties,
imgIContainerDebug)
#endif
//******************************************************************************
RasterImage::RasterImage(ImageURL* aURI /* = nullptr */) :
ImageResource(aURI), // invoke superclass's constructor
mSize(0,0),
mLockCount(0),
mDecodeCount(0),
mImageProducerID(ImageContainer::AllocateProducerID()),
mLastFrameID(0),
mLastImageContainerDrawResult(DrawResult::NOT_READY),
#ifdef DEBUG
mFramesNotified(0),
#endif
mSourceBuffer(WrapNotNull(new SourceBuffer())),
mHasSize(false),
mTransient(false),
mSyncLoad(false),
mDiscardable(false),
mSomeSourceData(false),
mAllSourceData(false),
mHasBeenDecoded(false),
mPendingAnimation(false),
mAnimationFinished(false),
mWantFullDecode(false)
{
}
//******************************************************************************
RasterImage::~RasterImage()
{
// Make sure our SourceBuffer is marked as complete. This will ensure that any
// outstanding decoders terminate.
if (!mSourceBuffer->IsComplete()) {
mSourceBuffer->Complete(NS_ERROR_ABORT);
}
// Release all frames from the surface cache.
SurfaceCache::RemoveImage(ImageKey(this));
// Record Telemetry.
Telemetry::Accumulate(Telemetry::IMAGE_DECODE_COUNT, mDecodeCount);
}
nsresult
RasterImage::Init(const char* aMimeType,
uint32_t aFlags)
{
// We don't support re-initialization
if (mInitialized) {
return NS_ERROR_ILLEGAL_VALUE;
}
// Not sure an error can happen before init, but be safe
if (mError) {
return NS_ERROR_FAILURE;
}
// We want to avoid redecodes for transient images.
MOZ_ASSERT_IF(aFlags & INIT_FLAG_TRANSIENT,
!(aFlags & INIT_FLAG_DISCARDABLE));
// Store initialization data
mDiscardable = !!(aFlags & INIT_FLAG_DISCARDABLE);
mWantFullDecode = !!(aFlags & INIT_FLAG_DECODE_IMMEDIATELY);
mTransient = !!(aFlags & INIT_FLAG_TRANSIENT);
mSyncLoad = !!(aFlags & INIT_FLAG_SYNC_LOAD);
// Use the MIME type to select a decoder type, and make sure there *is* a
// decoder for this MIME type.
NS_ENSURE_ARG_POINTER(aMimeType);
mDecoderType = DecoderFactory::GetDecoderType(aMimeType);
if (mDecoderType == DecoderType::UNKNOWN) {
return NS_ERROR_FAILURE;
}
// Lock this image's surfaces in the SurfaceCache if we're not discardable.
if (!mDiscardable) {
mLockCount++;
SurfaceCache::LockImage(ImageKey(this));
}
// Mark us as initialized
mInitialized = true;
return NS_OK;
}
//******************************************************************************
NS_IMETHODIMP_(void)
RasterImage::RequestRefresh(const TimeStamp& aTime)
{
if (HadRecentRefresh(aTime)) {
return;
}
EvaluateAnimation();
if (!mAnimating) {
return;
}
RefreshResult res;
if (mAnimationState) {
MOZ_ASSERT(mFrameAnimator);
res = mFrameAnimator->RequestRefresh(*mAnimationState, aTime);
}
if (res.mFrameAdvanced) {
// Notify listeners that our frame has actually changed, but do this only
// once for all frames that we've now passed (if AdvanceFrame() was called
// more than once).
#ifdef DEBUG
mFramesNotified++;
#endif
NotifyProgress(NoProgress, res.mDirtyRect);
}
if (res.mAnimationFinished) {
mAnimationFinished = true;
EvaluateAnimation();
}
}
//******************************************************************************
NS_IMETHODIMP
RasterImage::GetWidth(int32_t* aWidth)
{
NS_ENSURE_ARG_POINTER(aWidth);
if (mError) {
*aWidth = 0;
return NS_ERROR_FAILURE;
}
*aWidth = mSize.width;
return NS_OK;
}
//******************************************************************************
NS_IMETHODIMP
RasterImage::GetHeight(int32_t* aHeight)
{
NS_ENSURE_ARG_POINTER(aHeight);
if (mError) {
*aHeight = 0;
return NS_ERROR_FAILURE;
}
*aHeight = mSize.height;
return NS_OK;
}
//******************************************************************************
NS_IMETHODIMP
RasterImage::GetIntrinsicSize(nsSize* aSize)
{
if (mError) {
return NS_ERROR_FAILURE;
}
*aSize = nsSize(nsPresContext::CSSPixelsToAppUnits(mSize.width),
nsPresContext::CSSPixelsToAppUnits(mSize.height));
return NS_OK;
}
//******************************************************************************
NS_IMETHODIMP
RasterImage::GetIntrinsicRatio(nsSize* aRatio)
{
if (mError) {
return NS_ERROR_FAILURE;
}
*aRatio = nsSize(mSize.width, mSize.height);
return NS_OK;
}
NS_IMETHODIMP_(Orientation)
RasterImage::GetOrientation()
{
return mOrientation;
}
//******************************************************************************
NS_IMETHODIMP
RasterImage::GetType(uint16_t* aType)
{
NS_ENSURE_ARG_POINTER(aType);
*aType = imgIContainer::TYPE_RASTER;
return NS_OK;
}
LookupResult
RasterImage::LookupFrameInternal(const IntSize& aSize,
uint32_t aFlags,
PlaybackType aPlaybackType)
{
if (mAnimationState && aPlaybackType == PlaybackType::eAnimated) {
MOZ_ASSERT(mFrameAnimator);
MOZ_ASSERT(ToSurfaceFlags(aFlags) == DefaultSurfaceFlags(),
"Can't composite frames with non-default surface flags");
return mFrameAnimator->GetCompositedFrame(*mAnimationState);
}
SurfaceFlags surfaceFlags = ToSurfaceFlags(aFlags);
// We don't want any substitution for sync decodes, and substitution would be
// illegal when high quality downscaling is disabled, so we use
// SurfaceCache::Lookup in this case.
if ((aFlags & FLAG_SYNC_DECODE) || !(aFlags & FLAG_HIGH_QUALITY_SCALING)) {
return SurfaceCache::Lookup(ImageKey(this),
RasterSurfaceKey(aSize,
surfaceFlags,
PlaybackType::eStatic));
}
// We'll return the best match we can find to the requested frame.
return SurfaceCache::LookupBestMatch(ImageKey(this),
RasterSurfaceKey(aSize,
surfaceFlags,
PlaybackType::eStatic));
}
DrawableSurface
RasterImage::LookupFrame(const IntSize& aSize,
uint32_t aFlags,
PlaybackType aPlaybackType)
{
MOZ_ASSERT(NS_IsMainThread());
// If we're opaque, we don't need to care about premultiplied alpha, because
// that can only matter for frames with transparency.
if (IsOpaque()) {
aFlags &= ~FLAG_DECODE_NO_PREMULTIPLY_ALPHA;
}
IntSize requestedSize = CanDownscaleDuringDecode(aSize, aFlags)
? aSize : mSize;
if (requestedSize.IsEmpty()) {
return DrawableSurface(); // Can't decode to a surface of zero size.
}
LookupResult result =
LookupFrameInternal(requestedSize, aFlags, aPlaybackType);
if (!result && !mHasSize) {
// We can't request a decode without knowing our intrinsic size. Give up.
return DrawableSurface();
}
if (result.Type() == MatchType::NOT_FOUND ||
result.Type() == MatchType::SUBSTITUTE_BECAUSE_NOT_FOUND ||
((aFlags & FLAG_SYNC_DECODE) && !result)) {
// We don't have a copy of this frame, and there's no decoder working on
// one. (Or we're sync decoding and the existing decoder hasn't even started
// yet.) Trigger decoding so it'll be available next time.
MOZ_ASSERT(aPlaybackType != PlaybackType::eAnimated ||
!mAnimationState || mAnimationState->KnownFrameCount() < 1,
"Animated frames should be locked");
bool ranSync = Decode(requestedSize, aFlags, aPlaybackType);
// If we can or did sync decode, we should already have the frame.
if (ranSync || (aFlags & FLAG_SYNC_DECODE)) {
result = LookupFrameInternal(requestedSize, aFlags, aPlaybackType);
}
}
if (!result) {
// We still weren't able to get a frame. Give up.
return DrawableSurface();
}
if (result.Surface()->GetCompositingFailed()) {
return DrawableSurface();
}
MOZ_ASSERT(!result.Surface()->GetIsPaletted(),
"Should not have a paletted frame");
// Sync decoding guarantees that we got the frame, but if it's owned by an
// async decoder that's currently running, the contents of the frame may not
// be available yet. Make sure we get everything.
if (mAllSourceData && (aFlags & FLAG_SYNC_DECODE)) {
result.Surface()->WaitUntilFinished();
}
// If we could have done some decoding in this function we need to check if
// that decoding encountered an error and hence aborted the surface. We want
// to avoid calling IsAborted if we weren't passed any sync decode flag because
// IsAborted acquires the monitor for the imgFrame.
if (aFlags & (FLAG_SYNC_DECODE | FLAG_SYNC_DECODE_IF_FAST) &&
result.Surface()->IsAborted()) {
return DrawableSurface();
}
return Move(result.Surface());
}
bool
RasterImage::IsOpaque()
{
if (mError) {
return false;
}
Progress progress = mProgressTracker->GetProgress();
// If we haven't yet finished decoding, the safe answer is "not opaque".
if (!(progress & FLAG_DECODE_COMPLETE)) {
return false;
}
// Other, we're opaque if FLAG_HAS_TRANSPARENCY is not set.
return !(progress & FLAG_HAS_TRANSPARENCY);
}
NS_IMETHODIMP_(bool)
RasterImage::WillDrawOpaqueNow()
{
if (!IsOpaque()) {
return false;
}
if (mAnimationState) {
// We never discard frames of animated images.
return true;
}
// If we are not locked our decoded data could get discard at any time (ie
// between the call to this function and when we are asked to draw), so we
// have to return false if we are unlocked.
if (IsUnlocked()) {
return false;
}
LookupResult result =
SurfaceCache::LookupBestMatch(ImageKey(this),
RasterSurfaceKey(mSize,
DefaultSurfaceFlags(),
PlaybackType::eStatic));
MatchType matchType = result.Type();
if (matchType == MatchType::NOT_FOUND || matchType == MatchType::PENDING ||
!result.Surface()->IsFinished()) {
return false;
}
return true;
}
void
RasterImage::OnSurfaceDiscarded(const SurfaceKey& aSurfaceKey)
{
MOZ_ASSERT(mProgressTracker);
if (mAnimationState && aSurfaceKey.Playback() == PlaybackType::eAnimated) {
MOZ_ASSERT(gfxPrefs::ImageMemAnimatedDiscardable());
mAnimationState->SetDiscarded(true);
}
NS_DispatchToMainThread(NewRunnableMethod("ProgressTracker::OnDiscard",
mProgressTracker, &ProgressTracker::OnDiscard));
}
//******************************************************************************
NS_IMETHODIMP
RasterImage::GetAnimated(bool* aAnimated)
{
if (mError) {
return NS_ERROR_FAILURE;
}
NS_ENSURE_ARG_POINTER(aAnimated);
// If we have an AnimationState, we can know for sure.
if (mAnimationState) {
*aAnimated = true;
return NS_OK;
}
// Otherwise, we need to have been decoded to know for sure, since if we were
// decoded at least once mAnimationState would have been created for animated
// images. This is true even though we check for animation during the
// metadata decode, because we may still discover animation only during the
// full decode for corrupt images.
if (!mHasBeenDecoded) {
return NS_ERROR_NOT_AVAILABLE;
}
// We know for sure
*aAnimated = false;
return NS_OK;
}
//******************************************************************************
NS_IMETHODIMP_(int32_t)
RasterImage::GetFirstFrameDelay()
{
if (mError) {
return -1;
}
bool animated = false;
if (NS_FAILED(GetAnimated(&animated)) || !animated) {
return -1;
}
MOZ_ASSERT(mAnimationState, "Animated images should have an AnimationState");
return mAnimationState->FirstFrameTimeout().AsEncodedValueDeprecated();
}
NS_IMETHODIMP_(already_AddRefed<SourceSurface>)
RasterImage::GetFrame(uint32_t aWhichFrame,
uint32_t aFlags)
{
return GetFrameAtSize(mSize, aWhichFrame, aFlags);
}
NS_IMETHODIMP_(already_AddRefed<SourceSurface>)
RasterImage::GetFrameAtSize(const IntSize& aSize,
uint32_t aWhichFrame,
uint32_t aFlags)
{
RefPtr<SourceSurface> surf =
GetFrameInternal(aSize, aWhichFrame, aFlags).second().forget();
// If we are here, it suggests the image is embedded in a canvas or some
// other path besides layers, and we won't need the file handle.
MarkSurfaceShared(surf);
return surf.forget();
}
Pair<DrawResult, RefPtr<SourceSurface>>
RasterImage::GetFrameInternal(const IntSize& aSize,
uint32_t aWhichFrame,
uint32_t aFlags)
{
MOZ_ASSERT(aWhichFrame <= FRAME_MAX_VALUE);
if (aSize.IsEmpty()) {
return MakePair(DrawResult::BAD_ARGS, RefPtr<SourceSurface>());
}
if (aWhichFrame > FRAME_MAX_VALUE) {
return MakePair(DrawResult::BAD_ARGS, RefPtr<SourceSurface>());
}
if (mError) {
return MakePair(DrawResult::BAD_IMAGE, RefPtr<SourceSurface>());
}
// Get the frame. If it's not there, it's probably the caller's fault for
// not waiting for the data to be loaded from the network or not passing
// FLAG_SYNC_DECODE.
DrawableSurface surface =
LookupFrame(aSize, aFlags, ToPlaybackType(aWhichFrame));
if (!surface) {
// The OS threw this frame away and we couldn't redecode it.
return MakePair(DrawResult::TEMPORARY_ERROR, RefPtr<SourceSurface>());
}
RefPtr<SourceSurface> sourceSurface = surface->GetSourceSurface();
if (!surface->IsFinished()) {
return MakePair(DrawResult::INCOMPLETE, Move(sourceSurface));
}
return MakePair(DrawResult::SUCCESS, Move(sourceSurface));
}
Pair<DrawResult, RefPtr<layers::Image>>
RasterImage::GetCurrentImage(ImageContainer* aContainer, uint32_t aFlags)
{
MOZ_ASSERT(NS_IsMainThread());
MOZ_ASSERT(aContainer);
DrawResult drawResult;
RefPtr<SourceSurface> surface;
Tie(drawResult, surface) =
GetFrameInternal(mSize, FRAME_CURRENT, aFlags | FLAG_ASYNC_NOTIFY);
if (!surface) {
// The OS threw out some or all of our buffer. We'll need to wait for the
// redecode (which was automatically triggered by GetFrame) to complete.
return MakePair(drawResult, RefPtr<layers::Image>());
}
RefPtr<layers::Image> image = new layers::SourceSurfaceImage(surface);
return MakePair(drawResult, Move(image));
}
NS_IMETHODIMP_(bool)
RasterImage::IsImageContainerAvailable(LayerManager* aManager, uint32_t aFlags)
{
int32_t maxTextureSize = aManager->GetMaxTextureSize();
if (!mHasSize ||
mSize.width > maxTextureSize ||
mSize.height > maxTextureSize) {
return false;
}
return true;
}
NS_IMETHODIMP_(already_AddRefed<ImageContainer>)
RasterImage::GetImageContainer(LayerManager* aManager, uint32_t aFlags)
{
MOZ_ASSERT(NS_IsMainThread());
MOZ_ASSERT(aManager);
MOZ_ASSERT((aFlags & ~(FLAG_SYNC_DECODE |
FLAG_SYNC_DECODE_IF_FAST |
FLAG_ASYNC_NOTIFY))
== FLAG_NONE,
"Unsupported flag passed to GetImageContainer");
int32_t maxTextureSize = aManager->GetMaxTextureSize();
if (!mHasSize ||
mSize.width > maxTextureSize ||
mSize.height > maxTextureSize) {
return nullptr;
}
if (IsUnlocked()) {
SendOnUnlockedDraw(aFlags);
}
RefPtr<layers::ImageContainer> container = mImageContainer.get();
bool mustRedecode =
(aFlags & (FLAG_SYNC_DECODE | FLAG_SYNC_DECODE_IF_FAST)) &&
mLastImageContainerDrawResult != DrawResult::SUCCESS &&
mLastImageContainerDrawResult != DrawResult::BAD_IMAGE;
if (container && !mustRedecode) {
return container.forget();
}
// We need a new ImageContainer, so create one.
container = LayerManager::CreateImageContainer();
DrawResult drawResult;
RefPtr<layers::Image> image;
Tie(drawResult, image) = GetCurrentImage(container, aFlags);
if (!image) {
return nullptr;
}
// |image| holds a reference to a SourceSurface which in turn holds a lock on
// the current frame's data buffer, ensuring that it doesn't get freed as
// long as the layer system keeps this ImageContainer alive.
AutoTArray<ImageContainer::NonOwningImage, 1> imageList;
imageList.AppendElement(ImageContainer::NonOwningImage(image, TimeStamp(),
mLastFrameID++,
mImageProducerID));
container->SetCurrentImagesInTransaction(imageList);
mLastImageContainerDrawResult = drawResult;
mImageContainer = container;
return container.forget();
}
void
RasterImage::UpdateImageContainer()
{
MOZ_ASSERT(NS_IsMainThread());
RefPtr<layers::ImageContainer> container = mImageContainer.get();
if (!container) {
return;
}
DrawResult drawResult;
RefPtr<layers::Image> image;
Tie(drawResult, image) = GetCurrentImage(container, FLAG_NONE);
if (!image) {
return;
}
mLastImageContainerDrawResult = drawResult;
AutoTArray<ImageContainer::NonOwningImage, 1> imageList;
imageList.AppendElement(ImageContainer::NonOwningImage(image, TimeStamp(),
mLastFrameID++,
mImageProducerID));
container->SetCurrentImages(imageList);
}
size_t
RasterImage::SizeOfSourceWithComputedFallback(MallocSizeOf aMallocSizeOf) const
{
return mSourceBuffer->SizeOfIncludingThisWithComputedFallback(aMallocSizeOf);
}
void
RasterImage::CollectSizeOfSurfaces(nsTArray<SurfaceMemoryCounter>& aCounters,
MallocSizeOf aMallocSizeOf) const
{
SurfaceCache::CollectSizeOfSurfaces(ImageKey(this), aCounters, aMallocSizeOf);
if (mFrameAnimator) {
mFrameAnimator->CollectSizeOfCompositingSurfaces(aCounters, aMallocSizeOf);
}
}
bool
RasterImage::SetMetadata(const ImageMetadata& aMetadata,
bool aFromMetadataDecode)
{
MOZ_ASSERT(NS_IsMainThread());
if (mError) {
return true;
}
if (aMetadata.HasSize()) {
IntSize size = aMetadata.GetSize();
if (size.width < 0 || size.height < 0) {
NS_WARNING("Image has negative intrinsic size");
DoError();
return true;
}
MOZ_ASSERT(aMetadata.HasOrientation());
Orientation orientation = aMetadata.GetOrientation();
// If we already have a size, check the new size against the old one.
if (mHasSize && (size != mSize || orientation != mOrientation)) {
NS_WARNING("Image changed size or orientation on redecode! "
"This should not happen!");
DoError();
return true;
}
// Set the size and flag that we have it.
mSize = size;
mOrientation = orientation;
mHasSize = true;
}
if (mHasSize && aMetadata.HasAnimation() && !mAnimationState) {
// We're becoming animated, so initialize animation stuff.
mAnimationState.emplace(mAnimationMode);
mFrameAnimator = MakeUnique<FrameAnimator>(this, mSize);
// We don't support discarding animated images (See bug 414259).
// Lock the image and throw away the key.
LockImage();
if (!aFromMetadataDecode) {
// The metadata decode reported that this image isn't animated, but we
// discovered that it actually was during the full decode. This is a
// rare failure that only occurs for corrupt images. To recover, we need
// to discard all existing surfaces and redecode.
return false;
}
}
if (mAnimationState) {
mAnimationState->SetLoopCount(aMetadata.GetLoopCount());
mAnimationState->SetFirstFrameTimeout(aMetadata.GetFirstFrameTimeout());
if (aMetadata.HasLoopLength()) {
mAnimationState->SetLoopLength(aMetadata.GetLoopLength());
}
if (aMetadata.HasFirstFrameRefreshArea()) {
mAnimationState
->SetFirstFrameRefreshArea(aMetadata.GetFirstFrameRefreshArea());
}
}
if (aMetadata.HasHotspot()) {
IntPoint hotspot = aMetadata.GetHotspot();
nsCOMPtr<nsISupportsPRUint32> intwrapx =
do_CreateInstance(NS_SUPPORTS_PRUINT32_CONTRACTID);
nsCOMPtr<nsISupportsPRUint32> intwrapy =
do_CreateInstance(NS_SUPPORTS_PRUINT32_CONTRACTID);
intwrapx->SetData(hotspot.x);
intwrapy->SetData(hotspot.y);
Set("hotspotX", intwrapx);
Set("hotspotY", intwrapy);
}
return true;
}
NS_IMETHODIMP
RasterImage::SetAnimationMode(uint16_t aAnimationMode)
{
if (mAnimationState) {
mAnimationState->SetAnimationMode(aAnimationMode);
}
return SetAnimationModeInternal(aAnimationMode);
}
//******************************************************************************
nsresult
RasterImage::StartAnimation()
{
if (mError) {
return NS_ERROR_FAILURE;
}
MOZ_ASSERT(ShouldAnimate(), "Should not animate!");
// If we're not ready to animate, then set mPendingAnimation, which will cause
// us to start animating if and when we do become ready.
mPendingAnimation = !mAnimationState || mAnimationState->KnownFrameCount() < 1;
if (mPendingAnimation) {
return NS_OK;
}
// Don't bother to animate if we're displaying the first frame forever.
if (mAnimationState->GetCurrentAnimationFrameIndex() == 0 &&
mAnimationState->FirstFrameTimeout() == FrameTimeout::Forever()) {
mAnimationFinished = true;
return NS_ERROR_ABORT;
}
// We need to set the time that this initial frame was first displayed, as
// this is used in AdvanceFrame().
mAnimationState->InitAnimationFrameTimeIfNecessary();
return NS_OK;
}
//******************************************************************************
nsresult
RasterImage::StopAnimation()
{
MOZ_ASSERT(mAnimating, "Should be animating!");
nsresult rv = NS_OK;
if (mError) {
rv = NS_ERROR_FAILURE;
} else {
mAnimationState->SetAnimationFrameTime(TimeStamp());
}
mAnimating = false;
return rv;
}
//******************************************************************************
NS_IMETHODIMP
RasterImage::ResetAnimation()
{
if (mError) {
return NS_ERROR_FAILURE;
}
mPendingAnimation = false;
if (mAnimationMode == kDontAnimMode || !mAnimationState ||
mAnimationState->GetCurrentAnimationFrameIndex() == 0) {
return NS_OK;
}
mAnimationFinished = false;
if (mAnimating) {
StopAnimation();
}
MOZ_ASSERT(mAnimationState, "Should have AnimationState");
mAnimationState->ResetAnimation();
NotifyProgress(NoProgress, mAnimationState->FirstFrameRefreshArea());
// Start the animation again. It may not have been running before, if
// mAnimationFinished was true before entering this function.
EvaluateAnimation();
return NS_OK;
}
//******************************************************************************
NS_IMETHODIMP_(void)
RasterImage::SetAnimationStartTime(const TimeStamp& aTime)
{
if (mError || mAnimationMode == kDontAnimMode || mAnimating || !mAnimationState) {
return;
}
mAnimationState->SetAnimationFrameTime(aTime);
}
NS_IMETHODIMP_(float)
RasterImage::GetFrameIndex(uint32_t aWhichFrame)
{
MOZ_ASSERT(aWhichFrame <= FRAME_MAX_VALUE, "Invalid argument");
return (aWhichFrame == FRAME_FIRST || !mAnimationState)
? 0.0f
: mAnimationState->GetCurrentAnimationFrameIndex();
}
NS_IMETHODIMP_(IntRect)
RasterImage::GetImageSpaceInvalidationRect(const IntRect& aRect)
{
return aRect;
}
nsresult
RasterImage::OnImageDataComplete(nsIRequest*, nsISupports*, nsresult aStatus,
bool aLastPart)
{
MOZ_ASSERT(NS_IsMainThread());
// Record that we have all the data we're going to get now.
mAllSourceData = true;
// Let decoders know that there won't be any more data coming.
mSourceBuffer->Complete(aStatus);
// Allow a synchronous metadata decode if mSyncLoad was set, or if we're
// running on a single thread (in which case waiting for the async metadata
// decoder could delay this image's load event quite a bit), or if this image
// is transient.
bool canSyncDecodeMetadata = mSyncLoad || mTransient ||
DecodePool::NumberOfCores() < 2;
if (canSyncDecodeMetadata && !mHasSize) {
// We're loading this image synchronously, so it needs to be usable after
// this call returns. Since we haven't gotten our size yet, we need to do a
// synchronous metadata decode here.
DecodeMetadata(FLAG_SYNC_DECODE);
}
// Determine our final status, giving precedence to Necko failure codes. We
// check after running the metadata decode in case it triggered an error.
nsresult finalStatus = mError ? NS_ERROR_FAILURE : NS_OK;
if (NS_FAILED(aStatus)) {
finalStatus = aStatus;
}
// If loading failed, report an error.
if (NS_FAILED(finalStatus)) {
DoError();
}
Progress loadProgress = LoadCompleteProgress(aLastPart, mError, finalStatus);
if (!mHasSize && !mError) {
// We don't have our size yet, so we'll fire the load event in SetSize().
MOZ_ASSERT(!canSyncDecodeMetadata,
"Firing load async after metadata sync decode?");
NotifyProgress(FLAG_ONLOAD_BLOCKED);
mLoadProgress = Some(loadProgress);
return finalStatus;
}
NotifyForLoadEvent(loadProgress);
return finalStatus;
}
void
RasterImage::NotifyForLoadEvent(Progress aProgress)
{
MOZ_ASSERT(mHasSize || mError, "Need to know size before firing load event");
MOZ_ASSERT(!mHasSize ||
(mProgressTracker->GetProgress() & FLAG_SIZE_AVAILABLE),
"Should have notified that the size is available if we have it");
// If we encountered an error, make sure we notify for that as well.
if (mError) {
aProgress |= FLAG_HAS_ERROR;
}
// Notify our listeners, which will fire this image's load event.
NotifyProgress(aProgress);
}
nsresult
RasterImage::OnImageDataAvailable(nsIRequest*,
nsISupports*,
nsIInputStream* aInputStream,
uint64_t,
uint32_t aCount)
{
nsresult rv = mSourceBuffer->AppendFromInputStream(aInputStream, aCount);
if (NS_SUCCEEDED(rv) && !mSomeSourceData) {
mSomeSourceData = true;
if (!mSyncLoad) {
// Create an async metadata decoder and verify we succeed in doing so.
rv = DecodeMetadata(DECODE_FLAGS_DEFAULT);
}
}
if (NS_FAILED(rv)) {
DoError();
}
return rv;
}
nsresult
RasterImage::SetSourceSizeHint(uint32_t aSizeHint)
{
return mSourceBuffer->ExpectLength(aSizeHint);
}
/********* Methods to implement lazy allocation of nsIProperties object *******/
NS_IMETHODIMP
RasterImage::Get(const char* prop, const nsIID& iid, void** result)
{
if (!mProperties) {
return NS_ERROR_FAILURE;
}
return mProperties->Get(prop, iid, result);
}
NS_IMETHODIMP
RasterImage::Set(const char* prop, nsISupports* value)
{
if (!mProperties) {
mProperties = do_CreateInstance("@mozilla.org/properties;1");
}
if (!mProperties) {
return NS_ERROR_OUT_OF_MEMORY;
}
return mProperties->Set(prop, value);
}
NS_IMETHODIMP
RasterImage::Has(const char* prop, bool* _retval)
{
NS_ENSURE_ARG_POINTER(_retval);
if (!mProperties) {
*_retval = false;