File: CanvasChild.cpp

package info (click to toggle)
firefox 147.0.3-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 4,683,320 kB
  • sloc: cpp: 7,607,359; javascript: 6,533,295; ansic: 3,775,223; python: 1,415,500; xml: 634,561; asm: 438,949; java: 186,241; sh: 62,752; makefile: 18,079; objc: 13,092; perl: 12,808; yacc: 4,583; cs: 3,846; pascal: 3,448; lex: 1,720; ruby: 1,003; php: 436; lisp: 258; awk: 247; sql: 66; sed: 54; csh: 10; exp: 6
file content (834 lines) | stat: -rw-r--r-- 26,919 bytes parent folder | download
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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* 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/. */

#include "CanvasChild.h"

#include "MainThreadUtils.h"
#include "mozilla/dom/WorkerPrivate.h"
#include "mozilla/dom/WorkerRef.h"
#include "mozilla/dom/WorkerRunnable.h"
#include "mozilla/gfx/CanvasManagerChild.h"
#include "mozilla/gfx/CanvasShutdownManager.h"
#include "mozilla/gfx/DrawTargetRecording.h"
#include "mozilla/gfx/gfxVars.h"
#include "mozilla/gfx/Tools.h"
#include "mozilla/gfx/Rect.h"
#include "mozilla/gfx/Point.h"
#include "mozilla/ipc/Endpoint.h"
#include "mozilla/ipc/ProcessChild.h"
#include "mozilla/ipc/SharedMemoryHandle.h"
#include "mozilla/layers/CanvasDrawEventRecorder.h"
#include "mozilla/layers/ImageDataSerializer.h"
#include "mozilla/layers/SourceSurfaceSharedData.h"
#include "mozilla/AppShutdown.h"
#include "mozilla/Mutex.h"
#include "mozilla/StaticPrefs_gfx.h"
#include "nsIObserverService.h"
#include "nsICanvasRenderingContextInternal.h"
#include "RecordedCanvasEventImpl.h"

namespace mozilla {
namespace layers {

class RecorderHelpers final : public CanvasDrawEventRecorder::Helpers {
 public:
  NS_DECL_OWNINGTHREAD

  explicit RecorderHelpers(const RefPtr<CanvasChild>& aCanvasChild)
      : mCanvasChild(aCanvasChild) {}

  ~RecorderHelpers() override = default;

  bool InitTranslator(
      TextureType aTextureType, TextureType aWebglTextureType,
      gfx::BackendType aBackendType,
      ipc::MutableSharedMemoryHandle&& aReadHandle,
      nsTArray<ipc::ReadOnlySharedMemoryHandle>&& aBufferHandles,
      CrossProcessSemaphoreHandle&& aReaderSem,
      CrossProcessSemaphoreHandle&& aWriterSem) override {
    NS_ASSERT_OWNINGTHREAD(RecorderHelpers);
    if (NS_WARN_IF(!mCanvasChild)) {
      return false;
    }
    return mCanvasChild->SendInitTranslator(
        aTextureType, aWebglTextureType, aBackendType, std::move(aReadHandle),
        std::move(aBufferHandles), std::move(aReaderSem),
        std::move(aWriterSem));
  }

  bool AddBuffer(ipc::ReadOnlySharedMemoryHandle&& aBufferHandle) override {
    NS_ASSERT_OWNINGTHREAD(RecorderHelpers);
    if (!mCanvasChild) {
      return false;
    }
    return mCanvasChild->SendAddBuffer(std::move(aBufferHandle));
  }

  bool ReaderClosed() override {
    NS_ASSERT_OWNINGTHREAD(RecorderHelpers);
    if (!mCanvasChild) {
      return false;
    }
    return !mCanvasChild->CanSend() || AppShutdown::IsShutdownImpending();
  }

  bool RestartReader() override {
    NS_ASSERT_OWNINGTHREAD(RecorderHelpers);
    if (!mCanvasChild) {
      return false;
    }
    return mCanvasChild->SendRestartTranslation();
  }

  already_AddRefed<CanvasChild> GetCanvasChild() const override {
    RefPtr<CanvasChild> canvasChild(mCanvasChild);
    return canvasChild.forget();
  }

 private:
  const WeakPtr<CanvasChild> mCanvasChild;
};

// Limit the number of in-flight export surfaces
static Atomic<uint32_t> sCurrentExportSurfaces(0);
// Limit the memory used by in-flight export surfaces
static Atomic<size_t> sCurrentExportSurfaceMemory(0);

class SourceSurfaceCanvasRecording final : public gfx::SourceSurface {
 public:
  MOZ_DECLARE_REFCOUNTED_VIRTUAL_TYPENAME(SourceSurfaceCanvasRecording, final)

  SourceSurfaceCanvasRecording(
      const RemoteTextureOwnerId aTextureOwnerId,
      const RefPtr<gfx::SourceSurface>& aRecordedSuface,
      CanvasChild* aCanvasChild,
      const RefPtr<CanvasDrawEventRecorder>& aRecorder)
      : mTextureOwnerId(aTextureOwnerId),
        mRecordedSurface(aRecordedSuface),
        mCanvasChild(aCanvasChild),
        mRecorder(aRecorder) {
    // It's important that AddStoredObject is called first because that will
    // run any pending processing required by recorded objects that have been
    // deleted off the main thread.
    mRecorder->AddStoredObject(this);
    mRecorder->RecordEvent(RecordedAddSurfaceAlias(this, aRecordedSuface));
  }

  ~SourceSurfaceCanvasRecording() {
    ReferencePtr surfaceAlias = this;
    ReferencePtr exportID = mExportID;
    if (NS_IsMainThread()) {
      ReleaseOnMainThread(std::move(mRecorder), surfaceAlias,
                          std::move(mRecordedSurface), std::move(mCanvasChild),
                          exportID);
      return;
    }

    mRecorder->AddPendingDeletion(
        [recorder = std::move(mRecorder), surfaceAlias,
         aliasedSurface = std::move(mRecordedSurface),
         canvasChild = std::move(mCanvasChild), exportID]() mutable -> void {
          ReleaseOnMainThread(std::move(recorder), surfaceAlias,
                              std::move(aliasedSurface), std::move(canvasChild),
                              exportID);
        });
  }

  gfx::SurfaceType GetType() const final { return mRecordedSurface->GetType(); }

  gfx::IntSize GetSize() const final { return mRecordedSurface->GetSize(); }

  gfx::SurfaceFormat GetFormat() const final {
    return mRecordedSurface->GetFormat();
  }

  already_AddRefed<gfx::DataSourceSurface> GetDataSurface() final {
    EnsureDataSurfaceOnMainThread();
    return do_AddRef(mDataSourceSurface);
  }

  void AttachSurface() { mDetached = false; }
  void DetachSurface() { mDetached = true; }

  void InvalidateDataSurface() {
    if (mDataSourceSurface && mMayInvalidate) {
      // This must be the only reference to the data left.
      MOZ_ASSERT(mDataSourceSurface->hasOneRef());
      mDataSourceSurface =
          gfx::Factory::CopyDataSourceSurface(mDataSourceSurface);
      mMayInvalidate = false;
    }
  }

  already_AddRefed<gfx::SourceSurface> ExtractSubrect(
      const gfx::IntRect& aRect) final {
    return mRecordedSurface->ExtractSubrect(aRect);
  }

  static size_t GetExportSurfaceSize(gfx::SourceSurface* aSurface) {
    return ImageDataSerializer::ComputeRGBBufferSize(aSurface->GetSize(),
                                                     aSurface->GetFormat());
  }

  bool GetSurfaceDescriptor(SurfaceDescriptor& aDesc) final {
    static Atomic<uintptr_t> sNextExportID(0);
    if (!mExportID) {
      if (++sCurrentExportSurfaces >
          StaticPrefs::gfx_canvas_accelerated_max_export_surfaces()) {
        --sCurrentExportSurfaces;
        return false;
      }
      size_t bytes = GetExportSurfaceSize(mRecordedSurface);
      if ((sCurrentExportSurfaceMemory += bytes) >
          StaticPrefs::gfx_canvas_accelerated_max_export_surface_memory()) {
        --sCurrentExportSurfaces;
        sCurrentExportSurfaceMemory -= bytes;
        return false;
      }
      mExportID = gfx::ReferencePtr(++sNextExportID);
      mRecorder->RecordEvent(RecordedAddExportSurface(mExportID, this));
    }
    aDesc = SurfaceDescriptorCanvasSurface(
        static_cast<gfx::CanvasManagerChild*>(mCanvasChild->Manager())->Id(),
        mCanvasChild->Id(), uintptr_t(mExportID));
    return true;
  }

 private:
  void EnsureDataSurfaceOnMainThread() {
    // The data can only be retrieved on the main thread.
    if (!mDataSourceSurface && NS_IsMainThread()) {
      mDataSourceSurface = mCanvasChild->GetDataSurface(
          mTextureOwnerId, mRecordedSurface, mDetached, mMayInvalidate);
    }
  }

  // Used to ensure that clean-up that requires it is done on the main thread.
  static void ReleaseOnMainThread(RefPtr<CanvasDrawEventRecorder> aRecorder,
                                  ReferencePtr aSurfaceAlias,
                                  RefPtr<gfx::SourceSurface> aAliasedSurface,
                                  RefPtr<CanvasChild> aCanvasChild,
                                  ReferencePtr aExportID) {
    MOZ_ASSERT(NS_IsMainThread());

    aRecorder->RemoveStoredObject(aSurfaceAlias);
    aRecorder->RecordEvent(RecordedRemoveSurfaceAlias(aSurfaceAlias));
    if (aExportID) {
      aRecorder->RecordEvent(RecordedRemoveExportSurface(aExportID));
      --sCurrentExportSurfaces;
      size_t bytes = GetExportSurfaceSize(aAliasedSurface);
      sCurrentExportSurfaceMemory -= bytes;
    }
    aAliasedSurface = nullptr;
    aCanvasChild = nullptr;
    aRecorder = nullptr;
  }

  const RemoteTextureOwnerId mTextureOwnerId;
  RefPtr<gfx::SourceSurface> mRecordedSurface;
  RefPtr<CanvasChild> mCanvasChild;
  RefPtr<CanvasDrawEventRecorder> mRecorder;
  RefPtr<gfx::DataSourceSurface> mDataSourceSurface;
  bool mDetached = false;
  bool mMayInvalidate = false;
  ReferencePtr mExportID;
};

class CanvasDataShmemHolder {
 public:
  CanvasDataShmemHolder(
      const std::shared_ptr<ipc::ReadOnlySharedMemoryMapping>& aShmem,
      CanvasChild* aCanvasChild)
      : mMutex("CanvasChild::DataShmemHolder::mMutex"),
        mShmem(aShmem),
        mCanvasChild(aCanvasChild) {}

  bool Init(dom::ThreadSafeWorkerRef* aWorkerRef) {
    if (!aWorkerRef) {
      return true;
    }

    RefPtr<dom::StrongWorkerRef> workerRef = dom::StrongWorkerRef::Create(
        aWorkerRef->Private(), "CanvasChild::DataShmemHolder",
        [this]() { DestroyWorker(); });
    if (NS_WARN_IF(!workerRef)) {
      return false;
    }

    MutexAutoLock lock(mMutex);
    mWorkerRef = new dom::ThreadSafeWorkerRef(workerRef);
    return true;
  }

  void Destroy() {
    class DestroyRunnable final : public dom::WorkerThreadRunnable {
     public:
      explicit DestroyRunnable(CanvasDataShmemHolder* aShmemHolder)
          : dom::WorkerThreadRunnable("CanvasDataShmemHolder::Destroy"),
            mShmemHolder(aShmemHolder) {}

      bool WorkerRun(JSContext* aCx,
                     dom::WorkerPrivate* aWorkerPrivate) override {
        mShmemHolder->Destroy();
        return true;
      }

      void PostRun(JSContext* aCx, dom::WorkerPrivate* aWorkerPrivate,
                   bool aRunResult) override {}

      bool PreDispatch(dom::WorkerPrivate* aWorkerPrivate) override {
        return true;
      }

      void PostDispatch(dom::WorkerPrivate* aWorkerPrivate,
                        bool aDispatchResult) override {}

     private:
      CanvasDataShmemHolder* mShmemHolder;
    };

    mMutex.Lock();

    if (mCanvasChild) {
      if (mWorkerRef) {
        if (!mWorkerRef->Private()->IsOnCurrentThread()) {
          auto task = MakeRefPtr<DestroyRunnable>(this);
          dom::WorkerPrivate* worker = mWorkerRef->Private();
          mMutex.Unlock();
          task->Dispatch(worker);
          return;
        }
      } else if (!NS_IsMainThread()) {
        mMutex.Unlock();
        NS_DispatchToMainThread(NS_NewRunnableFunction(
            "CanvasDataShmemHolder::Destroy", [this]() { Destroy(); }));
        return;
      }

      mCanvasChild->ReturnDataSurfaceShmem(std::move(mShmem));
      mCanvasChild = nullptr;
      mWorkerRef = nullptr;
    }

    mMutex.Unlock();
    delete this;
  }

  void DestroyWorker() {
    MutexAutoLock lock(mMutex);
    mCanvasChild = nullptr;
    mWorkerRef = nullptr;
  }

 private:
  Mutex mMutex;
  std::shared_ptr<ipc::ReadOnlySharedMemoryMapping> mShmem;
  RefPtr<CanvasChild> mCanvasChild MOZ_GUARDED_BY(mMutex);
  RefPtr<dom::ThreadSafeWorkerRef> mWorkerRef MOZ_GUARDED_BY(mMutex);
};

CanvasChild::CanvasChild(dom::ThreadSafeWorkerRef* aWorkerRef)
    : mWorkerRef(aWorkerRef) {}

CanvasChild::~CanvasChild() { MOZ_ASSERT(!mWorkerRef); }

static void NotifyCanvasDeviceChanged() {
  nsCOMPtr<nsIObserverService> obs = services::GetObserverService();
  if (obs) {
    obs->NotifyObservers(nullptr, "canvas-device-reset", nullptr);
  }
}

ipc::IPCResult CanvasChild::RecvNotifyDeviceReset(
    const nsTArray<RemoteTextureOwnerId>& aOwnerIds) {
  NS_ASSERT_OWNINGTHREAD(CanvasChild);

  if (auto* manager = gfx::CanvasShutdownManager::MaybeGet()) {
    manager->OnRemoteCanvasReset(aOwnerIds);
  }

  mRecorder->RecordEvent(RecordedDeviceResetAcknowledged());
  return IPC_OK();
}

/* static */ bool CanvasChild::mDeactivated = false;

ipc::IPCResult CanvasChild::RecvDeactivate() {
  NS_ASSERT_OWNINGTHREAD(CanvasChild);

  RefPtr<CanvasChild> self(this);
  mDeactivated = true;
  if (auto* cm = gfx::CanvasManagerChild::Get()) {
    cm->DeactivateCanvas();
  }
  NotifyCanvasDeviceChanged();
  return IPC_OK();
}

ipc::IPCResult CanvasChild::RecvBlockCanvas() {
  mBlocked = true;
  if (auto* cm = gfx::CanvasManagerChild::Get()) {
    cm->BlockCanvas();
  }
  return IPC_OK();
}

bool CanvasChild::EnsureRecorder(gfx::IntSize aSize, gfx::SurfaceFormat aFormat,
                                 TextureType aTextureType,
                                 TextureType aWebglTextureType) {
  NS_ASSERT_OWNINGTHREAD(CanvasChild);

  if (!mRecorder) {
    gfx::BackendType backendType =
        gfxPlatform::GetPlatform()->GetPreferredCanvasBackend();
    auto recorder = MakeRefPtr<CanvasDrawEventRecorder>(mWorkerRef);
    if (!recorder->Init(aTextureType, aWebglTextureType, backendType,
                        MakeUnique<RecorderHelpers>(this))) {
      return false;
    }

    mRecorder = recorder.forget();
  }

  if (NS_WARN_IF(mRecorder->GetTextureType() != aTextureType)) {
    // The recorder has already been initialized with a different type. This can
    // happen if there is a device reset or fallback that causes a switch to a
    // different unaccelerated texture type (i.e. unknown). In that case, just
    // fall back to non-remote rendering.
    return false;
  }

  EnsureDataSurfaceShmem(aSize, aFormat);

  return true;
}

void CanvasChild::ActorDestroy(ActorDestroyReason aWhy) {
  NS_ASSERT_OWNINGTHREAD(CanvasChild);

  if (mRecorder) {
    mRecorder->DetachResources();
  }
  mTextureInfo.clear();
}

void CanvasChild::Destroy() {
  NS_ASSERT_OWNINGTHREAD(CanvasChild);

  if (CanSend()) {
    Send__delete__(this);
  }

  mWorkerRef = nullptr;
}

bool CanvasChild::EnsureBeginTransaction() {
  NS_ASSERT_OWNINGTHREAD(CanvasChild);

  if (!mIsInTransaction) {
    RecordEvent(RecordedCanvasBeginTransaction());
    mIsInTransaction = true;
  }

  return true;
}

void CanvasChild::EndTransaction() {
  NS_ASSERT_OWNINGTHREAD(CanvasChild);

  if (mIsInTransaction) {
    RecordEvent(RecordedCanvasEndTransaction());
    mIsInTransaction = false;
    mDormant = false;
  } else if (mRecorder) {
    // Schedule to drop free buffers if we have no non-empty transactions.
    if (!mDormant) {
      mDormant = true;
      NS_DelayedDispatchToCurrentThread(
          NewRunnableMethod("CanvasChild::DropFreeBuffersWhenDormant", this,
                            &CanvasChild::DropFreeBuffersWhenDormant),
          StaticPrefs::gfx_canvas_remote_drop_buffer_milliseconds());
    }
  }

  // If we are continuously drawing/recording, then we need to periodically
  // flush our external surface/image references, to ensure they actually get
  // freed on a timely basis.
  if (mRecorder) {
    mRecorder->ClearProcessedExternalSurfaces();
    mRecorder->ClearProcessedExternalImages();
  }

  ++mTransactionsSinceGetDataSurface;
}

void CanvasChild::DropFreeBuffersWhenDormant() {
  NS_ASSERT_OWNINGTHREAD(CanvasChild);
  // Drop any free buffers if we have not had any non-empty transactions.
  if (mDormant && mRecorder) {
    mRecorder->DropFreeBuffers();
    // Notify CanvasTranslator it is dormant.
    SendDropFreeBuffersWhenDormant();
  }
}

void CanvasChild::ClearCachedResources() {
  NS_ASSERT_OWNINGTHREAD(CanvasChild);
  if (mRecorder) {
    mRecorder->DropFreeBuffers();
    // Notify CanvasTranslator it is about to be minimized.
    SendClearCachedResources();
  }
}

bool CanvasChild::ShouldBeCleanedUp() const {
  NS_ASSERT_OWNINGTHREAD(CanvasChild);

  // Always return true if we've been deactivated.
  if (Deactivated()) {
    return true;
  }

  // We can only be cleaned up if nothing else references our recorder.
  return !mRecorder || (mRecorder->hasOneRef() && mTextureInfo.empty());
}

already_AddRefed<gfx::DrawTargetRecording> CanvasChild::CreateDrawTarget(
    const RemoteTextureOwnerId& aTextureOwnerId, gfx::IntSize aSize,
    gfx::SurfaceFormat aFormat) {
  NS_ASSERT_OWNINGTHREAD(CanvasChild);
  MOZ_ASSERT(mTextureInfo.find(aTextureOwnerId) == mTextureInfo.end());

  if (!mRecorder) {
    return nullptr;
  }

  RefPtr<gfx::DrawTarget> dummyDt = gfx::Factory::CreateDrawTarget(
      gfx::BackendType::SKIA, gfx::IntSize(1, 1), aFormat);
  RefPtr<gfx::DrawTargetRecording> dt = MakeAndAddRef<gfx::DrawTargetRecording>(
      mRecorder, aTextureOwnerId, dummyDt, aSize);
  dt->SetOptimizeTransform(true);

  mTextureInfo.insert({aTextureOwnerId, {}});

  return dt.forget();
}

size_t CanvasChild::SizeOfDataSurfaceShmem(gfx::IntSize aSize,
                                           gfx::SurfaceFormat aFormat) {
  if (!mRecorder) {
    return 0;
  }
  size_t sizeRequired =
      ImageDataSerializer::ComputeRGBBufferSize(aSize, aFormat);
  return sizeRequired > 0 ? ipc::shared_memory::PageAlignedSize(sizeRequired)
                          : 0;
}

bool CanvasChild::ShouldGrowDataSurfaceShmem(size_t aSizeRequired) {
  return aSizeRequired > 0 && (!mDataSurfaceShmemAvailable ||
                               mDataSurfaceShmem->Size() < aSizeRequired);
}

bool CanvasChild::EnsureDataSurfaceShmem(size_t aSizeRequired) {
  NS_ASSERT_OWNINGTHREAD(CanvasChild);

  if (!aSizeRequired) {
    return false;
  }

  if (ShouldGrowDataSurfaceShmem(aSizeRequired)) {
    RecordEvent(RecordedPauseTranslation());
    auto shmemHandle = ipc::shared_memory::Create(aSizeRequired);
    if (!shmemHandle) {
      return false;
    }

    auto roMapping = shmemHandle.AsReadOnly().Map();
    if (!roMapping) {
      return false;
    }

    auto id = ++mNextDataSurfaceShmemId;
    if (!id) {
      // If ids overflow, ensure that zero is reserved.
      id = ++mNextDataSurfaceShmemId;
    }
    if (!SendSetDataSurfaceBuffer(id, std::move(shmemHandle))) {
      return false;
    }

    mDataSurfaceShmem = std::make_shared<ipc::ReadOnlySharedMemoryMapping>(
        std::move(roMapping));
    mDataSurfaceShmemAvailable = true;
  }

  MOZ_ASSERT(mDataSurfaceShmemAvailable);
  return true;
}

bool CanvasChild::EnsureDataSurfaceShmem(gfx::IntSize aSize,
                                         gfx::SurfaceFormat aFormat) {
  size_t sizeRequired = SizeOfDataSurfaceShmem(aSize, aFormat);
  if (!sizeRequired) {
    return false;
  }

  return EnsureDataSurfaceShmem(sizeRequired);
}

void CanvasChild::RecordEvent(const gfx::RecordedEvent& aEvent) {
  NS_ASSERT_OWNINGTHREAD(CanvasChild);

  // We drop mRecorder in ActorDestroy to break the reference cycle.
  if (!mRecorder) {
    return;
  }

  mRecorder->RecordEvent(aEvent);
}

int64_t CanvasChild::CreateCheckpoint() {
  NS_ASSERT_OWNINGTHREAD(CanvasChild);
  return mRecorder->CreateCheckpoint();
}

already_AddRefed<gfx::DataSourceSurface> CanvasChild::GetDataSurface(
    const RemoteTextureOwnerId aTextureOwnerId,
    const gfx::SourceSurface* aSurface, bool aDetached, bool& aMayInvalidate) {
  NS_ASSERT_OWNINGTHREAD(CanvasChild);
  MOZ_ASSERT(aSurface);

  // mTransactionsSinceGetDataSurface is used to determine if we want to prepare
  // a DataSourceSurface in the GPU process up front at the end of the
  // transaction, but that only makes sense if the canvas JS is requesting data
  // in between transactions.
  if (!mIsInTransaction) {
    mTransactionsSinceGetDataSurface = 0;
  }

  if (!EnsureBeginTransaction()) {
    return nullptr;
  }

  gfx::IntSize ssSize = aSurface->GetSize();
  gfx::SurfaceFormat ssFormat = aSurface->GetFormat();
  auto stride = ImageDataSerializer::ComputeRGBStride(ssFormat, ssSize.width);

  // Shmem is only valid if the surface is the latest snapshot (not detached).
  if (!aDetached) {
    // If there is a shmem associated with this snapshot id, then we want to try
    // use that directly without having to allocate a new shmem for retrieval.
    auto it = mTextureInfo.find(aTextureOwnerId);
    if (it != mTextureInfo.end() && it->second.mSnapshotShmem) {
      const auto* shmemPtr = it->second.mSnapshotShmem->DataAs<uint8_t>();
      MOZ_ASSERT(shmemPtr);
      mRecorder->RecordEvent(RecordedPrepareShmem(aTextureOwnerId));
      auto checkpoint = CreateCheckpoint();
      if (NS_WARN_IF(!mRecorder->WaitForCheckpoint(checkpoint))) {
        return nullptr;
      }
      auto* closure =
          new CanvasDataShmemHolder(it->second.mSnapshotShmem, this);
      if (NS_WARN_IF(!closure->Init(mWorkerRef))) {
        delete closure;
        return nullptr;
      }
      // We can cast away the const of `shmemPtr` to match the call because the
      // DataSourceSurface will not be written to.
      RefPtr<gfx::DataSourceSurface> dataSurface =
          gfx::Factory::CreateWrappingDataSourceSurface(
              const_cast<uint8_t*>(shmemPtr), stride, ssSize, ssFormat,
              ReleaseDataShmemHolder, closure);
      aMayInvalidate = true;
      return dataSurface.forget();
    }
  }

  size_t sizeRequired = SizeOfDataSurfaceShmem(ssSize, ssFormat);
  if (!sizeRequired) {
    return nullptr;
  }

  RecordEvent(RecordedCacheDataSurface(aSurface));

  if (!EnsureDataSurfaceShmem(sizeRequired)) {
    return nullptr;
  }

  RecordEvent(RecordedGetDataForSurface(mNextDataSurfaceShmemId, aSurface));
  auto checkpoint = CreateCheckpoint();
  if (NS_WARN_IF(!mRecorder->WaitForCheckpoint(checkpoint))) {
    return nullptr;
  }

  auto* closure = new CanvasDataShmemHolder(mDataSurfaceShmem, this);
  if (NS_WARN_IF(!closure->Init(mWorkerRef))) {
    delete closure;
    return nullptr;
  }

  mDataSurfaceShmemAvailable = false;

  const auto* data = mDataSurfaceShmem->DataAs<uint8_t>();

  // We can cast away the const of `data` to match the call because the
  // DataSourceSurface will not be written to.
  RefPtr<gfx::DataSourceSurface> dataSurface =
      gfx::Factory::CreateWrappingDataSourceSurface(
          const_cast<uint8_t*>(data), stride, ssSize, ssFormat,
          ReleaseDataShmemHolder, closure);
  aMayInvalidate = false;
  return dataSurface.forget();
}

/* static */ void CanvasChild::ReleaseDataShmemHolder(void* aClosure) {
  auto* shmemHolder = static_cast<CanvasDataShmemHolder*>(aClosure);
  shmemHolder->Destroy();
}

already_AddRefed<gfx::SourceSurface> CanvasChild::WrapSurface(
    const RefPtr<gfx::SourceSurface>& aSurface,
    const RemoteTextureOwnerId aTextureOwnerId) {
  NS_ASSERT_OWNINGTHREAD(CanvasChild);

  if (!aSurface) {
    return nullptr;
  }

  return MakeAndAddRef<SourceSurfaceCanvasRecording>(aTextureOwnerId, aSurface,
                                                     this, mRecorder);
}

void CanvasChild::ReturnDataSurfaceShmem(
    std::shared_ptr<ipc::ReadOnlySharedMemoryMapping>&& aDataSurfaceShmem) {
  // We can only reuse the latest data surface shmem.
  if (aDataSurfaceShmem == mDataSurfaceShmem) {
    MOZ_ASSERT(!mDataSurfaceShmemAvailable);
    mDataSurfaceShmemAvailable = true;
  }
}

void CanvasChild::AttachSurface(const RefPtr<gfx::SourceSurface>& aSurface) {
  if (auto* surface =
          static_cast<SourceSurfaceCanvasRecording*>(aSurface.get())) {
    surface->AttachSurface();
  }
}

void CanvasChild::DetachSurface(const RefPtr<gfx::SourceSurface>& aSurface,
                                bool aInvalidate) {
  if (auto* surface =
          static_cast<SourceSurfaceCanvasRecording*>(aSurface.get())) {
    surface->DetachSurface();
    if (aInvalidate) {
      surface->InvalidateDataSurface();
    }
  }
}

ipc::IPCResult CanvasChild::RecvNotifyRequiresRefresh(
    const RemoteTextureOwnerId aTextureOwnerId) {
  auto it = mTextureInfo.find(aTextureOwnerId);
  if (it != mTextureInfo.end()) {
    it->second.mRequiresRefresh = true;
  }
  return IPC_OK();
}

bool CanvasChild::RequiresRefresh(
    const RemoteTextureOwnerId aTextureOwnerId) const {
  if (mBlocked) {
    return true;
  }
  auto it = mTextureInfo.find(aTextureOwnerId);
  if (it != mTextureInfo.end()) {
    return it->second.mRequiresRefresh;
  }
  return false;
}

ipc::IPCResult CanvasChild::RecvSnapshotShmem(
    const RemoteTextureOwnerId aTextureOwnerId,
    ipc::ReadOnlySharedMemoryHandle&& aShmemHandle,
    SnapshotShmemResolver&& aResolve) {
  auto it = mTextureInfo.find(aTextureOwnerId);
  if (it != mTextureInfo.end()) {
    auto shmem = aShmemHandle.Map();
    if (NS_WARN_IF(!shmem)) {
      shmem = nullptr;
    } else {
      it->second.mSnapshotShmem =
          std::make_shared<ipc::ReadOnlySharedMemoryMapping>(std::move(shmem));
    }
    aResolve(true);
  } else {
    aResolve(false);
  }
  return IPC_OK();
}

ipc::IPCResult CanvasChild::RecvNotifyTextureDestruction(
    const RemoteTextureOwnerId aTextureOwnerId) {
  auto it = mTextureInfo.find(aTextureOwnerId);
  if (it == mTextureInfo.end()) {
    MOZ_ASSERT(!CanSend());
    return IPC_OK();
  }

  mTextureInfo.erase(aTextureOwnerId);
  return IPC_OK();
}

already_AddRefed<gfx::SourceSurface> CanvasChild::SnapshotExternalCanvas(
    gfx::DrawTargetRecording* aTarget,
    nsICanvasRenderingContextInternal* aCanvas,
    mozilla::ipc::IProtocol* aActor) {
  // SnapshotExternalCanvas is only valid to use if using Accelerated Canvas2D
  // with the pending events queue enabled. This ensures WebGL and AC2D are
  // running under the same thread, and that events can be paused or resumed
  // while synchronizing between WebGL and AC2D.
  if (!gfx::gfxVars::UseAcceleratedCanvas2D() ||
      !StaticPrefs::gfx_canvas_remote_use_canvas_translator_event_AtStartup()) {
    return nullptr;
  }

  gfx::SurfaceFormat format = aCanvas->GetIsOpaque()
                                  ? gfx::SurfaceFormat::B8G8R8X8
                                  : gfx::SurfaceFormat::B8G8R8A8;
  gfx::IntSize size(aCanvas->GetWidth(), aCanvas->GetHeight());
  // Create a source sourface that will be associated with the snapshot.
  RefPtr<gfx::SourceSurface> surface =
      aTarget->CreateExternalSourceSurface(size, format);
  if (!surface) {
    return nullptr;
  }

  // Pause translation until the sync-id identifying the snapshot is received.
  uint64_t syncId = ++mLastSyncId;
  mRecorder->RecordEvent(RecordedAwaitTranslationSync(syncId));

  // Flush WebGL to cause any IPDL messages to get sent at this sync point.
  aCanvas->SyncSnapshot();

  // Once the IPDL message is sent to generate the snapshot, resolve the sync-id
  // to a surface in the recording stream. The AwaitTranslationSync above will
  // ensure this event is not translated until the snapshot is generated first.
  mRecorder->RecordEvent(aTarget,
                         RecordedResolveExternalSnapshot(
                             syncId, gfx::ReferencePtr(surface), size, format));

  uint32_t managerId = static_cast<gfx::CanvasManagerChild*>(Manager())->Id();
  ActorId canvasId = aActor->Id();

  // Actually send the request via IPDL to snapshot the external WebGL canvas.
  SendSnapshotExternalCanvas(syncId, managerId, canvasId);

  return surface.forget();
}

}  // namespace layers
}  // namespace mozilla