summaryrefslogtreecommitdiffstats
path: root/gfx/layers/ipc/CanvasTranslator.cpp
blob: 81c40270fb89493794c3ac6e93ef74f4309241ac (plain)
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
/* -*- 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 https://mozilla.org/MPL/2.0/. */

#include "CanvasTranslator.h"

#include "gfxGradientCache.h"
#include "mozilla/gfx/2D.h"
#include "mozilla/gfx/GPUParent.h"
#include "mozilla/gfx/Logging.h"
#include "mozilla/ipc/Endpoint.h"
#include "mozilla/layers/SharedSurfacesParent.h"
#include "mozilla/layers/TextureClient.h"
#include "mozilla/SyncRunnable.h"
#include "mozilla/Telemetry.h"
#include "nsTHashSet.h"
#include "RecordedCanvasEventImpl.h"

#if defined(XP_WIN)
#  include "mozilla/gfx/DeviceManagerDx.h"
#  include "mozilla/layers/TextureD3D11.h"
#endif

namespace mozilla {
namespace layers {

// When in a transaction we wait for a short time because we're expecting more
// events from the content process. We don't want to wait for too long in case
// other content processes are waiting for events to process.
static const TimeDuration kReadEventTimeout = TimeDuration::FromMilliseconds(5);

static const TimeDuration kDescriptorTimeout =
    TimeDuration::FromMilliseconds(10000);

class RingBufferReaderServices final
    : public CanvasEventRingBuffer::ReaderServices {
 public:
  explicit RingBufferReaderServices(RefPtr<CanvasTranslator> aCanvasTranslator)
      : mCanvasTranslator(std::move(aCanvasTranslator)) {}

  ~RingBufferReaderServices() final = default;

  bool WriterClosed() final {
    return !mCanvasTranslator->GetIPCChannel()->CanSend();
  }

 private:
  RefPtr<CanvasTranslator> mCanvasTranslator;
};

TextureData* CanvasTranslator::CreateTextureData(TextureType aTextureType,
                                                 const gfx::IntSize& aSize,
                                                 gfx::SurfaceFormat aFormat) {
  TextureData* textureData = nullptr;
  switch (aTextureType) {
#ifdef XP_WIN
    case TextureType::D3D11: {
      textureData =
          D3D11TextureData::Create(aSize, aFormat, ALLOC_CLEAR_BUFFER, mDevice);
      break;
    }
#endif
    default:
      MOZ_CRASH("Unsupported TextureType for CanvasTranslator.");
  }

  return textureData;
}

typedef nsTHashSet<RefPtr<CanvasTranslator>> CanvasTranslatorSet;

static CanvasTranslatorSet& CanvasTranslators() {
  MOZ_ASSERT(CanvasThreadHolder::IsInCanvasThread());
  static CanvasTranslatorSet* sCanvasTranslator = new CanvasTranslatorSet();
  return *sCanvasTranslator;
}

static void EnsureAllClosed() {
  for (const auto& key : CanvasTranslators()) {
    key->Close();
  }
}

/* static */ void CanvasTranslator::Shutdown() {
  // If the dispatch fails there is no canvas thread and so no translators.
  CanvasThreadHolder::MaybeDispatchToCanvasThread(NewRunnableFunction(
      "CanvasTranslator::EnsureAllClosed", &EnsureAllClosed));
}

/* static */ already_AddRefed<CanvasTranslator> CanvasTranslator::Create(
    ipc::Endpoint<PCanvasParent>&& aEndpoint) {
  MOZ_ASSERT(NS_IsInCompositorThread());

  RefPtr<CanvasThreadHolder> threadHolder =
      CanvasThreadHolder::EnsureCanvasThread();
  RefPtr<CanvasTranslator> canvasTranslator =
      new CanvasTranslator(do_AddRef(threadHolder));
  threadHolder->DispatchToCanvasThread(
      NewRunnableMethod<Endpoint<PCanvasParent>&&>(
          "CanvasTranslator::Bind", canvasTranslator, &CanvasTranslator::Bind,
          std::move(aEndpoint)));
  return canvasTranslator.forget();
}

CanvasTranslator::CanvasTranslator(
    already_AddRefed<CanvasThreadHolder> aCanvasThreadHolder)
    : gfx::InlineTranslator(), mCanvasThreadHolder(aCanvasThreadHolder) {
  // Track when remote canvas has been activated.
  Telemetry::ScalarAdd(Telemetry::ScalarID::GFX_CANVAS_REMOTE_ACTIVATED, 1);
}

CanvasTranslator::~CanvasTranslator() {
  // The textures need to be the last thing holding their DrawTargets, so that
  // they can destroy them within a lock.
  mDrawTargets.Clear();
  mBaseDT = nullptr;
}

void CanvasTranslator::Bind(Endpoint<PCanvasParent>&& aEndpoint) {
  if (!aEndpoint.Bind(this)) {
    return;
  }

  CanvasTranslators().Insert(this);
}

mozilla::ipc::IPCResult CanvasTranslator::RecvInitTranslator(
    const TextureType& aTextureType,
    ipc::SharedMemoryBasic::Handle&& aReadHandle,
    CrossProcessSemaphoreHandle&& aReaderSem,
    CrossProcessSemaphoreHandle&& aWriterSem) {
  if (mStream) {
    return IPC_FAIL(this, "RecvInitTranslator called twice.");
  }

  mTextureType = aTextureType;

  // We need to initialize the stream first, because it might be used to
  // communicate other failures back to the writer.
  mStream = MakeUnique<CanvasEventRingBuffer>();
  if (!mStream->InitReader(std::move(aReadHandle), std::move(aReaderSem),
                           std::move(aWriterSem),
                           MakeUnique<RingBufferReaderServices>(this))) {
    return IPC_FAIL(this, "Failed to initialize ring buffer reader.");
  }

#if defined(XP_WIN)
  if (!CheckForFreshCanvasDevice(__LINE__)) {
    gfxCriticalNote << "GFX: CanvasTranslator failed to get device";
    return IPC_OK();
  }
#endif

  mTranslationTaskQueue = mCanvasThreadHolder->CreateWorkerTaskQueue();
  return RecvResumeTranslation();
}

ipc::IPCResult CanvasTranslator::RecvResumeTranslation() {
  if (mDeactivated) {
    // The other side might have sent a resume message before we deactivated.
    return IPC_OK();
  }

  MOZ_ALWAYS_SUCCEEDS(mTranslationTaskQueue->Dispatch(
      NewRunnableMethod("CanvasTranslator::StartTranslation", this,
                        &CanvasTranslator::StartTranslation)));

  return IPC_OK();
}

void CanvasTranslator::StartTranslation() {
  if (!TranslateRecording() && GetIPCChannel()->CanSend()) {
    MOZ_ALWAYS_SUCCEEDS(mTranslationTaskQueue->Dispatch(
        NewRunnableMethod("CanvasTranslator::StartTranslation", this,
                          &CanvasTranslator::StartTranslation)));
  }

  // If the stream has been marked as bad and the Writer hasn't failed,
  // deactivate remote canvas.
  if (!mStream->good() && !mStream->WriterFailed()) {
    Telemetry::ScalarAdd(
        Telemetry::ScalarID::GFX_CANVAS_REMOTE_DEACTIVATED_BAD_STREAM, 1);
    Deactivate();
  }
}

void CanvasTranslator::ActorDestroy(ActorDestroyReason why) {
  MOZ_ASSERT(CanvasThreadHolder::IsInCanvasThread());

  if (!mTranslationTaskQueue) {
    return FinishShutdown();
  }

  mTranslationTaskQueue->BeginShutdown()->Then(
      GetCurrentSerialEventTarget(), __func__, this,
      &CanvasTranslator::FinishShutdown, &CanvasTranslator::FinishShutdown);
}

void CanvasTranslator::FinishShutdown() {
  MOZ_ASSERT(CanvasThreadHolder::IsInCanvasThread());

  // mTranslationTaskQueue has shutdown we can safely drop the ring buffer to
  // break the cycle caused by RingBufferReaderServices.
  mStream = nullptr;

  // CanvasTranslators has a MOZ_ASSERT(CanvasThreadHolder::IsInCanvasThread())
  // to ensure it is only called on the Canvas Thread. This takes a lock on
  // CanvasThreadHolder::sCanvasThreadHolder, which is also locked in
  // CanvasThreadHolder::StaticRelease on the compositor thread from
  // ReleaseOnCompositorThread below. If that lock wins the race with the one in
  // IsInCanvasThread and it is the last CanvasThreadHolder reference then it
  // shuts down the canvas thread waiting for it to finish. However
  // IsInCanvasThread is waiting for the lock on the canvas thread and we
  // deadlock. So, we need to call CanvasTranslators before
  // ReleaseOnCompositorThread.
  CanvasTranslatorSet& canvasTranslators = CanvasTranslators();
  CanvasThreadHolder::ReleaseOnCompositorThread(mCanvasThreadHolder.forget());
  canvasTranslators.Remove(this);
}

void CanvasTranslator::Deactivate() {
  if (mDeactivated) {
    return;
  }
  mDeactivated = true;

  // We need to tell the other side to deactivate. Make sure the stream is
  // marked as bad so that the writing side won't wait for space to write.
  mStream->SetIsBad();
  mCanvasThreadHolder->DispatchToCanvasThread(
      NewRunnableMethod("CanvasTranslator::SendDeactivate", this,
                        &CanvasTranslator::SendDeactivate));

  // Unlock all of our textures.
  for (auto const& entry : mTextureDatas) {
    entry.second->Unlock();
  }

  // Also notify anyone waiting for a surface descriptor. This must be done
  // after mDeactivated is set to true.
  mSurfaceDescriptorsMonitor.NotifyAll();
}

bool CanvasTranslator::TranslateRecording() {
  MOZ_ASSERT(CanvasThreadHolder::IsInCanvasWorker());

  int32_t eventType = mStream->ReadNextEvent();
  while (mStream->good()) {
    bool success = RecordedEvent::DoWithEventFromStream(
        *mStream, static_cast<RecordedEvent::EventType>(eventType),
        [&](RecordedEvent* recordedEvent) -> bool {
          // Make sure that the whole event was read from the stream.
          if (!mStream->good()) {
            if (!GetIPCChannel()->CanSend()) {
              // The other side has closed only warn about read failure.
              gfxWarning() << "Failed to read event type: "
                           << recordedEvent->GetType();
            } else {
              gfxCriticalNote << "Failed to read event type: "
                              << recordedEvent->GetType();
            }
            return false;
          }

          return recordedEvent->PlayEvent(this);
        });

    // Check the stream is good here or we will log the issue twice.
    if (!mStream->good()) {
      return true;
    }

    if (!success && !HandleExtensionEvent(eventType)) {
      if (mDeviceResetInProgress) {
        // We've notified the recorder of a device change, so we are expecting
        // failures. Log as a warning to prevent crash reporting being flooded.
        gfxWarning() << "Failed to play canvas event type: " << eventType;
      } else {
        gfxCriticalNote << "Failed to play canvas event type: " << eventType;
      }
      if (!mStream->good()) {
        return true;
      }
    }

    if (!mIsInTransaction) {
      return mStream->StopIfEmpty();
    }

    if (!mStream->HasDataToRead()) {
      // We're going to wait for the next event, so take the opportunity to
      // flush the rendering.
      Flush();
      if (!mStream->WaitForDataToRead(kReadEventTimeout, 0)) {
        return true;
      }
    }

    eventType = mStream->ReadNextEvent();
  }

  return true;
}

#define READ_AND_PLAY_CANVAS_EVENT_TYPE(_typeenum, _class)             \
  case _typeenum: {                                                    \
    auto e = _class(*mStream);                                         \
    if (!mStream->good()) {                                            \
      if (!GetIPCChannel()->CanSend()) {                               \
        /* The other side has closed only warn about read failure. */  \
        gfxWarning() << "Failed to read event type: " << _typeenum;    \
      } else {                                                         \
        gfxCriticalNote << "Failed to read event type: " << _typeenum; \
      }                                                                \
      return false;                                                    \
    }                                                                  \
    return e.PlayCanvasEvent(this);                                    \
  }

bool CanvasTranslator::HandleExtensionEvent(int32_t aType) {
  // This is where we handle extensions to the Moz2D Recording events to handle
  // canvas specific things.
  switch (aType) {
    FOR_EACH_CANVAS_EVENT(READ_AND_PLAY_CANVAS_EVENT_TYPE)
    default:
      return false;
  }
}

void CanvasTranslator::BeginTransaction() { mIsInTransaction = true; }

void CanvasTranslator::Flush() {
#if defined(XP_WIN)
  // We can end up without a device, due to a reset and failure to re-create.
  if (!mDevice) {
    return;
  }

  gfx::AutoSerializeWithMoz2D serializeWithMoz2D(mBackendType);
  RefPtr<ID3D11DeviceContext> deviceContext;
  mDevice->GetImmediateContext(getter_AddRefs(deviceContext));
  deviceContext->Flush();
#endif
}

void CanvasTranslator::EndTransaction() {
  Flush();
  // At the end of a transaction is a good time to check if a new canvas device
  // has been created, even if a reset did not occur.
  Unused << CheckForFreshCanvasDevice(__LINE__);
  mIsInTransaction = false;
}

void CanvasTranslator::DeviceChangeAcknowledged() {
  mDeviceResetInProgress = false;
}

bool CanvasTranslator::CreateReferenceTexture() {
  if (mReferenceTextureData) {
    mReferenceTextureData->Unlock();
  }

  mReferenceTextureData.reset(CreateTextureData(
      mTextureType, gfx::IntSize(1, 1), gfx::SurfaceFormat::B8G8R8A8));
  if (!mReferenceTextureData) {
    return false;
  }

  mReferenceTextureData->Lock(OpenMode::OPEN_READ_WRITE);
  mBaseDT = mReferenceTextureData->BorrowDrawTarget();
  if (!mBaseDT) {
    // We might get a null draw target due to a device failure, just return
    // false so that we can recover.
    return false;
  }

  mBackendType = mBaseDT->GetBackendType();
  return true;
}

bool CanvasTranslator::CheckForFreshCanvasDevice(int aLineNumber) {
#if defined(XP_WIN)
  // If a new device has already been created, use that one.
  RefPtr<ID3D11Device> device = gfx::DeviceManagerDx::Get()->GetCanvasDevice();
  if (device && device != mDevice) {
    if (mDevice) {
      // We already had a device, notify child of change.
      NotifyDeviceChanged();
    }
    mDevice = device.forget();
    return CreateReferenceTexture();
  }

  if (mDevice) {
    if (mDevice->GetDeviceRemovedReason() == S_OK) {
      return false;
    }

    gfxCriticalNote << "GFX: CanvasTranslator detected a device reset at "
                    << aLineNumber;
    NotifyDeviceChanged();
  }

  RefPtr<Runnable> runnable = NS_NewRunnableFunction(
      "CanvasTranslator NotifyDeviceReset",
      []() { gfx::GPUParent::GetSingleton()->NotifyDeviceReset(); });

  // It is safe to wait here because only the Compositor thread waits on us and
  // the main thread doesn't wait on the compositor thread in the GPU process.
  SyncRunnable::DispatchToThread(GetMainThreadSerialEventTarget(), runnable,
                                 /*aForceDispatch*/ true);

  mDevice = gfx::DeviceManagerDx::Get()->GetCanvasDevice();
  if (!mDevice) {
    // We don't have a canvas device, we need to deactivate.
    Telemetry::ScalarAdd(
        Telemetry::ScalarID::GFX_CANVAS_REMOTE_DEACTIVATED_NO_DEVICE, 1);
    Deactivate();
    return false;
  }

  return CreateReferenceTexture();
#else
  return false;
#endif
}

void CanvasTranslator::NotifyDeviceChanged() {
  mDeviceResetInProgress = true;
  mCanvasThreadHolder->DispatchToCanvasThread(
      NewRunnableMethod("CanvasTranslator::SendNotifyDeviceChanged", this,
                        &CanvasTranslator::SendNotifyDeviceChanged));
}

void CanvasTranslator::AddSurfaceDescriptor(int64_t aTextureId,
                                            TextureData* aTextureData) {
  UniquePtr<SurfaceDescriptor> descriptor = MakeUnique<SurfaceDescriptor>();
  if (!aTextureData->Serialize(*descriptor)) {
    MOZ_CRASH("Failed to serialize");
  }

  MonitorAutoLock lock(mSurfaceDescriptorsMonitor);
  mSurfaceDescriptors[aTextureId] = std::move(descriptor);
  mSurfaceDescriptorsMonitor.Notify();
}

already_AddRefed<gfx::DrawTarget> CanvasTranslator::CreateDrawTarget(
    gfx::ReferencePtr aRefPtr, const gfx::IntSize& aSize,
    gfx::SurfaceFormat aFormat) {
  RefPtr<gfx::DrawTarget> dt;
  do {
    TextureData* textureData = CreateTextureData(mTextureType, aSize, aFormat);
    if (textureData) {
      MOZ_DIAGNOSTIC_ASSERT(mNextTextureId >= 0, "No texture ID set");
      textureData->Lock(OpenMode::OPEN_READ_WRITE);
      mTextureDatas[mNextTextureId] = UniquePtr<TextureData>(textureData);
      AddSurfaceDescriptor(mNextTextureId, textureData);
      dt = textureData->BorrowDrawTarget();
    }
  } while (!dt && CheckForFreshCanvasDevice(__LINE__));
  AddDrawTarget(aRefPtr, dt);
  mNextTextureId = -1;

  return dt.forget();
}

void CanvasTranslator::RemoveTexture(int64_t aTextureId) {
  mTextureDatas.erase(aTextureId);

  // It is possible that the texture from the content process has never been
  // forwarded to the GPU process, so make sure its descriptor is removed.
  MonitorAutoLock lock(mSurfaceDescriptorsMonitor);
  mSurfaceDescriptors.erase(aTextureId);
}

TextureData* CanvasTranslator::LookupTextureData(int64_t aTextureId) {
  TextureMap::const_iterator result = mTextureDatas.find(aTextureId);
  if (result == mTextureDatas.end()) {
    return nullptr;
  }
  return result->second.get();
}

UniquePtr<SurfaceDescriptor> CanvasTranslator::WaitForSurfaceDescriptor(
    int64_t aTextureId) {
  MonitorAutoLock lock(mSurfaceDescriptorsMonitor);
  DescriptorMap::iterator result;
  while ((result = mSurfaceDescriptors.find(aTextureId)) ==
         mSurfaceDescriptors.end()) {
    // If remote canvas has been deactivated just return null.
    if (mDeactivated) {
      return nullptr;
    }

    CVStatus status = mSurfaceDescriptorsMonitor.Wait(kDescriptorTimeout);
    if (status == CVStatus::Timeout) {
      // If something has gone wrong and the texture has already been destroyed,
      // it will have cleaned up its descriptor.
      return nullptr;
    }
  }

  UniquePtr<SurfaceDescriptor> descriptor = std::move(result->second);
  mSurfaceDescriptors.erase(aTextureId);
  return descriptor;
}

already_AddRefed<gfx::SourceSurface> CanvasTranslator::LookupExternalSurface(
    uint64_t aKey) {
  return SharedSurfacesParent::Get(wr::ToExternalImageId(aKey));
}

already_AddRefed<gfx::GradientStops> CanvasTranslator::GetOrCreateGradientStops(
    gfx::DrawTarget* aDrawTarget, gfx::GradientStop* aRawStops,
    uint32_t aNumStops, gfx::ExtendMode aExtendMode) {
  MOZ_ASSERT(aDrawTarget);
  nsTArray<gfx::GradientStop> rawStopArray(aRawStops, aNumStops);
  return gfx::gfxGradientCache::GetOrCreateGradientStops(
      aDrawTarget, rawStopArray, aExtendMode);
}

gfx::DataSourceSurface* CanvasTranslator::LookupDataSurface(
    gfx::ReferencePtr aRefPtr) {
  return mDataSurfaces.GetWeak(aRefPtr);
}

void CanvasTranslator::AddDataSurface(
    gfx::ReferencePtr aRefPtr, RefPtr<gfx::DataSourceSurface>&& aSurface) {
  mDataSurfaces.InsertOrUpdate(aRefPtr, std::move(aSurface));
}

void CanvasTranslator::RemoveDataSurface(gfx::ReferencePtr aRefPtr) {
  mDataSurfaces.Remove(aRefPtr);
}

void CanvasTranslator::SetPreparedMap(
    gfx::ReferencePtr aSurface,
    UniquePtr<gfx::DataSourceSurface::ScopedMap> aMap) {
  mMappedSurface = aSurface;
  mPreparedMap = std::move(aMap);
}

UniquePtr<gfx::DataSourceSurface::ScopedMap> CanvasTranslator::GetPreparedMap(
    gfx::ReferencePtr aSurface) {
  if (!mPreparedMap) {
    // We might fail to set the map during, for example, device resets.
    return nullptr;
  }

  MOZ_RELEASE_ASSERT(mMappedSurface == aSurface,
                     "aSurface must match previously stored surface.");

  mMappedSurface = nullptr;
  return std::move(mPreparedMap);
}

}  // namespace layers
}  // namespace mozilla