summaryrefslogtreecommitdiffstats
path: root/dom/media/webrtc/libwebrtcglue/TaskQueueWrapper.h
blob: da11bfdf8b28bf892691326b3d42047def9c0640 (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
/* -*- 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/. */

#ifndef DOM_MEDIA_WEBRTC_LIBWEBRTCGLUE_TASKQUEUEWRAPPER_H_
#define DOM_MEDIA_WEBRTC_LIBWEBRTCGLUE_TASKQUEUEWRAPPER_H_

#include "api/task_queue/task_queue_factory.h"
#include "mozilla/DataMutex.h"
#include "mozilla/RecursiveMutex.h"
#include "mozilla/ProfilerRunnable.h"
#include "mozilla/TaskQueue.h"
#include "VideoUtils.h"
#include "mozilla/media/MediaUtils.h"  // For media::Await

namespace mozilla {

enum class DeletionPolicy : uint8_t { Blocking, NonBlocking };

/**
 * A wrapper around Mozilla TaskQueues in the shape of a libwebrtc TaskQueue.
 *
 * Allows libwebrtc to use Mozilla threads where tooling, e.g. profiling, is set
 * up and just works.
 *
 * Mozilla APIs like Runnables, MozPromise, etc. can also be used with the
 * wrapped TaskQueue to run things on the right thread when interacting with
 * libwebrtc.
 */
template <DeletionPolicy Deletion>
class TaskQueueWrapper : public webrtc::TaskQueueBase {
 public:
  TaskQueueWrapper(RefPtr<TaskQueue> aTaskQueue, nsCString aName)
      : mTaskQueue(std::move(aTaskQueue)), mName(std::move(aName)) {}
  ~TaskQueueWrapper() = default;

  void Delete() override {
    {
      // Scope this to make sure it does not race against the promise chain we
      // set up below.
      auto hasShutdown = mHasShutdown.Lock();
      *hasShutdown = true;
    }

    MOZ_RELEASE_ASSERT(Deletion == DeletionPolicy::NonBlocking ||
                       !mTaskQueue->IsOnCurrentThread());

    nsCOMPtr<nsISerialEventTarget> backgroundTaskQueue;
    NS_CreateBackgroundTaskQueue(__func__, getter_AddRefs(backgroundTaskQueue));
    if (NS_WARN_IF(!backgroundTaskQueue)) {
      // Ok... that's pretty broken. Try main instead.
      MOZ_ASSERT(false);
      backgroundTaskQueue = GetMainThreadSerialEventTarget();
    }

    RefPtr<GenericPromise> shutdownPromise = mTaskQueue->BeginShutdown()->Then(
        backgroundTaskQueue, __func__, [this] {
          // Wait until shutdown is complete, then delete for real. Although we
          // prevent queued tasks from executing with mHasShutdown, that is a
          // member variable, which means we still need to ensure that the
          // queue is done executing tasks before destroying it.
          delete this;
          return GenericPromise::CreateAndResolve(true, __func__);
        });
    if constexpr (Deletion == DeletionPolicy::Blocking) {
      media::Await(backgroundTaskQueue.forget(), shutdownPromise);
    } else {
      Unused << shutdownPromise;
    }
  }

  already_AddRefed<Runnable> CreateTaskRunner(
      absl::AnyInvocable<void() &&> aTask) {
    return NS_NewRunnableFunction(
        "TaskQueueWrapper::CreateTaskRunner",
        [this, task = std::move(aTask),
         name = nsPrintfCString("TQ %s: webrtc::QueuedTask",
                                mName.get())]() mutable {
          CurrentTaskQueueSetter current(this);
          auto hasShutdown = mHasShutdown.Lock();
          if (*hasShutdown) {
            return;
          }
          AUTO_PROFILE_FOLLOWING_RUNNABLE(name);
          std::move(task)();
        });
  }

  already_AddRefed<Runnable> CreateTaskRunner(nsCOMPtr<nsIRunnable> aRunnable) {
    return NS_NewRunnableFunction(
        "TaskQueueWrapper::CreateTaskRunner",
        [this, runnable = std::move(aRunnable)]() mutable {
          CurrentTaskQueueSetter current(this);
          auto hasShutdown = mHasShutdown.Lock();
          if (*hasShutdown) {
            return;
          }
          AUTO_PROFILE_FOLLOWING_RUNNABLE(runnable);
          runnable->Run();
        });
  }

  void PostTask(absl::AnyInvocable<void() &&> aTask) override {
    MOZ_ALWAYS_SUCCEEDS(
        mTaskQueue->Dispatch(CreateTaskRunner(std::move(aTask))));
  }

  void PostDelayedTask(absl::AnyInvocable<void() &&> aTask,
                       webrtc::TimeDelta aDelay) override {
    if (aDelay.ms() == 0) {
      // AbstractThread::DelayedDispatch doesn't support delay 0
      PostTask(std::move(aTask));
      return;
    }
    MOZ_ALWAYS_SUCCEEDS(mTaskQueue->DelayedDispatch(
        CreateTaskRunner(std::move(aTask)), aDelay.ms()));
  }

  void PostDelayedHighPrecisionTask(absl::AnyInvocable<void() &&> aTask,
                                    webrtc::TimeDelta aDelay) override {
    PostDelayedTask(std::move(aTask), aDelay);
  }

  const RefPtr<TaskQueue> mTaskQueue;
  const nsCString mName;

  // This is a recursive mutex because a TaskRunner holding this mutex while
  // running its runnable may end up running other - tail dispatched - runnables
  // too, and they'll again try to grab the mutex.
  // The mutex must be held while running the runnable since otherwise there'd
  // be a race between shutting down the underlying task queue and the runnable
  // dispatching to that task queue (and we assert it succeeds in e.g.,
  // PostTask()).
  DataMutexBase<bool, RecursiveMutex> mHasShutdown{
      false, "TaskQueueWrapper::mHasShutdown"};
};

template <DeletionPolicy Deletion>
class DefaultDelete<TaskQueueWrapper<Deletion>>
    : public webrtc::TaskQueueDeleter {
 public:
  void operator()(TaskQueueWrapper<Deletion>* aPtr) const {
    webrtc::TaskQueueDeleter::operator()(aPtr);
  }
};

class SharedThreadPoolWebRtcTaskQueueFactory : public webrtc::TaskQueueFactory {
 public:
  SharedThreadPoolWebRtcTaskQueueFactory() {}

  template <DeletionPolicy Deletion>
  UniquePtr<TaskQueueWrapper<Deletion>> CreateTaskQueueWrapper(
      absl::string_view aName, bool aSupportTailDispatch, Priority aPriority,
      MediaThreadType aThreadType = MediaThreadType::WEBRTC_WORKER) const {
    // XXX Do something with aPriority
    nsCString name(aName.data(), aName.size());
    auto taskQueue = TaskQueue::Create(GetMediaThreadPool(aThreadType),
                                       name.get(), aSupportTailDispatch);
    return MakeUnique<TaskQueueWrapper<Deletion>>(std::move(taskQueue),
                                                  std::move(name));
  }

  std::unique_ptr<webrtc::TaskQueueBase, webrtc::TaskQueueDeleter>
  CreateTaskQueue(absl::string_view aName, Priority aPriority) const override {
    // libwebrtc will dispatch some tasks sync, i.e., block the origin thread
    // until they've run, and that doesn't play nice with tail dispatching since
    // there will never be a tail.
    // DeletionPolicy::Blocking because this is for libwebrtc use and that's
    // what they expect.
    constexpr bool supportTailDispatch = false;
    return std::unique_ptr<webrtc::TaskQueueBase, webrtc::TaskQueueDeleter>(
        CreateTaskQueueWrapper<DeletionPolicy::Blocking>(
            std::move(aName), supportTailDispatch, aPriority)
            .release(),
        webrtc::TaskQueueDeleter());
  }
};

}  // namespace mozilla

#endif