Connect global task queue factory and rtc::TaskQueue

This cl allows to overwrite TaskQueue implementation
by depending on and setting the global task queue factory.

Bug: webrtc:10191
Change-Id: I69ceb139d00078d3be90eeb4e240758b88829c20
Reviewed-on: https://webrtc-review.googlesource.com/c/118060
Reviewed-by: Karl Wiberg <kwiberg@webrtc.org>
Commit-Queue: Danil Chapovalov <danilchap@webrtc.org>
Cr-Commit-Position: refs/heads/master@{#26345}
diff --git a/api/task_queue/BUILD.gn b/api/task_queue/BUILD.gn
index ee35dab..11550e8 100644
--- a/api/task_queue/BUILD.gn
+++ b/api/task_queue/BUILD.gn
@@ -26,10 +26,14 @@
   ]
   sources = [
     "task_queue_base.cc",
+    "task_queue_impl.cc",
+    "task_queue_impl.h",
   ]
 
   deps = [
     ":task_queue",
+    "../../rtc_base:checks",
+    "../../rtc_base:rtc_task_queue_api",
     "//third_party/abseil-cpp/absl/base:core_headers",
     "//third_party/abseil-cpp/absl/strings",
   ]
@@ -49,6 +53,8 @@
   ]
 }
 
+# Linking with global_task_queue_factory adds link-time implementation of the
+# rtc::TaskQueue that allows run-time injection of the TaskQueue implementaion.
 rtc_source_set("global_task_queue_factory") {
   # TODO(danilchap): Remove this target when task queue factory propagated to
   # all components that create TaskQueues.
@@ -56,10 +62,16 @@
   sources = [
     "global_task_queue_factory.cc",
     "global_task_queue_factory.h",
+
+    # TODO(bugs.webrtc.org/10191): Move task_queue.cc to private build
+    # "rtc_task_queue" when "rtc_task_queue_api", "rtc_task_queue",
+    # and "rtc_task_queue_impl" can be joined.
+    "task_queue.cc",
   ]
   deps = [
     ":default_task_queue_factory",
     ":task_queue_factory",
     "../../rtc_base:checks",
+    "../../rtc_base:rtc_task_queue_api",
   ]
 }
diff --git a/api/task_queue/DEPS b/api/task_queue/DEPS
new file mode 100644
index 0000000..e480aa9
--- /dev/null
+++ b/api/task_queue/DEPS
@@ -0,0 +1,7 @@
+specific_include_rules = {
+  # temporary include to support both rtc::TaskQueue::Current() and
+  # webrtc::TaskQueueBase::Current() for implementaions of the TaskQueueBase.
+  "task_queue_impl\.h": [
+    "+rtc_base/task_queue.h",
+  ],
+}
diff --git a/api/task_queue/task_queue.cc b/api/task_queue/task_queue.cc
new file mode 100644
index 0000000..4a33d48
--- /dev/null
+++ b/api/task_queue/task_queue.cc
@@ -0,0 +1,63 @@
+/*
+ *  Copyright 2019 The WebRTC Project Authors. All rights reserved.
+ *
+ *  Use of this source code is governed by a BSD-style license
+ *  that can be found in the LICENSE file in the root of the source
+ *  tree. An additional intellectual property rights grant can be found
+ *  in the file PATENTS.  All contributing project authors may
+ *  be found in the AUTHORS file in the root of the source tree.
+ */
+#include "rtc_base/task_queue.h"
+
+#include "api/task_queue/global_task_queue_factory.h"
+#include "api/task_queue/task_queue_base.h"
+
+namespace rtc {
+
+TaskQueue::TaskQueue(const char* queue_name, Priority priority)
+    // For backward compatibility impl_ need to be scoped_refptr<Impl>,
+    // But this implementation treat impl_ as
+    // std::unique_ptr<webrtc::TaskQueueBase, webrtc::TaskQueueDeleter> abusing
+    // fact that both classes are wrappers around raw pointer.
+    : impl_(webrtc::GlobalTaskQueueFactory()
+                .CreateTaskQueue(queue_name, priority)
+                .release()) {
+  impl_->task_queue_ = this;
+}
+
+TaskQueue::~TaskQueue() {
+  // TODO(danilchap): change impl_ to webrtc::TaskQueueBase* when dependenent
+  // projects stop using link-injection to override task queue and thus do not
+  // rely on exact TaskQueue layout.
+  // There might running task that tries to rescheduler itself to the TaskQueue
+  // and not yet away TaskQueue destructor is called.
+  // Calling back to TaskQueue::PostTask need impl_ pointer still be valid, so
+  // Start the destruction first, ...
+  impl_->Delete();
+  // release the pointer later.
+  const_cast<rtc::scoped_refptr<Impl>&>(impl_).release();
+}
+
+// static
+TaskQueue* TaskQueue::Current() {
+  webrtc::TaskQueueBase* impl = webrtc::TaskQueueBase::Current();
+  if (impl == nullptr) {
+    return nullptr;
+  }
+  return impl->task_queue_;
+}
+
+bool TaskQueue::IsCurrent() const {
+  return Current() == this;
+}
+
+void TaskQueue::PostTask(std::unique_ptr<QueuedTask> task) {
+  return impl_->PostTask(std::move(task));
+}
+
+void TaskQueue::PostDelayedTask(std::unique_ptr<QueuedTask> task,
+                                uint32_t milliseconds) {
+  return impl_->PostDelayedTask(std::move(task), milliseconds);
+}
+
+}  // namespace rtc
diff --git a/api/task_queue/task_queue_base.h b/api/task_queue/task_queue_base.h
index a5163fe..175253b 100644
--- a/api/task_queue/task_queue_base.h
+++ b/api/task_queue/task_queue_base.h
@@ -13,6 +13,7 @@
 #include <memory>
 
 #include "api/task_queue/queued_task.h"
+#include "api/task_queue/task_queue_impl.h"
 
 namespace webrtc {
 
@@ -20,7 +21,10 @@
 // in FIFO order and that tasks never overlap. Tasks may always execute on the
 // same worker thread and they may not. To DCHECK that tasks are executing on a
 // known task queue, use IsCurrent().
-class TaskQueueBase {
+// TODO(bugs.webrtc.org/10191): Remove inheritence from rtc::TaskQueue::Impl
+// when all implementations switch to use TaskQueueFactory instead of link-time
+// injection.
+class TaskQueueBase : public rtc::TaskQueue::Impl {
  public:
   // Starts destruction of the task queue.
   // On return ensures no task are running and no new tasks are able to start
@@ -31,7 +35,7 @@
   // TaskQueue is deallocated and thus should not call any methods after Delete.
   // Code running on the TaskQueue should not call Delete, but can assume
   // TaskQueue still exists and may call other methods, e.g. PostTask.
-  virtual void Delete() = 0;
+  void Delete() override = 0;
 
   // Schedules a task to execute. Tasks are executed in FIFO order.
   // If |task->Run()| returns true, task is deleted on the task queue
@@ -41,14 +45,14 @@
   // TaskQueue or it may happen asynchronously after TaskQueue is deleted.
   // This may vary from one implementation to the next so assumptions about
   // lifetimes of pending tasks should not be made.
-  virtual void PostTask(std::unique_ptr<QueuedTask> task) = 0;
+  void PostTask(std::unique_ptr<QueuedTask> task) override = 0;
 
   // Schedules a task to execute a specified number of milliseconds from when
   // the call is made. The precision should be considered as "best effort"
   // and in some cases, such as on Windows when all high precision timers have
   // been used up, can be off by as much as 15 millseconds.
-  virtual void PostDelayedTask(std::unique_ptr<QueuedTask> task,
-                               uint32_t milliseconds) = 0;
+  void PostDelayedTask(std::unique_ptr<QueuedTask> task,
+                       uint32_t milliseconds) override = 0;
 
   // Until all TaskQueue implementations switch to  using CurrentTaskQueueSetter
   // below, this function may return nullptr even if code is executed by a
@@ -71,7 +75,7 @@
 
   // Users of the TaskQueue should call Delete instead of directly deleting
   // this object.
-  virtual ~TaskQueueBase() = default;
+  ~TaskQueueBase() override = default;
 };
 
 struct TaskQueueDeleter {
diff --git a/api/task_queue/task_queue_impl.cc b/api/task_queue/task_queue_impl.cc
new file mode 100644
index 0000000..0024085
--- /dev/null
+++ b/api/task_queue/task_queue_impl.cc
@@ -0,0 +1,31 @@
+/*
+ *  Copyright 2019 The WebRTC Project Authors. All rights reserved.
+ *
+ *  Use of this source code is governed by a BSD-style license
+ *  that can be found in the LICENSE file in the root of the source
+ *  tree. An additional intellectual property rights grant can be found
+ *  in the file PATENTS.  All contributing project authors may
+ *  be found in the AUTHORS file in the root of the source tree.
+ */
+#include "api/task_queue/task_queue_impl.h"
+
+#include "rtc_base/checks.h"
+
+namespace rtc {
+
+// Fake ref counting: implementers of the TaskQueueBase shouldn't expect it is
+// stored in a refererence counter pointer.
+void TaskQueue::Impl::AddRef() {
+  // AddRef should be called exactly once by rtc::TaskQueue constructor when
+  // raw pointer converted into scoped_refptr<Impl>,
+  // just before TaskQueue constructor assign task_queue_ member.
+  RTC_CHECK(task_queue_ == nullptr);
+}
+
+void TaskQueue::Impl::Release() {
+  // TaskQueue destructor manually destroyes this object, thus Release should
+  // never be called.
+  RTC_CHECK(false);
+}
+
+}  // namespace rtc
diff --git a/api/task_queue/task_queue_impl.h b/api/task_queue/task_queue_impl.h
new file mode 100644
index 0000000..a3b676d
--- /dev/null
+++ b/api/task_queue/task_queue_impl.h
@@ -0,0 +1,40 @@
+/*
+ *  Copyright 2019 The WebRTC Project Authors. All rights reserved.
+ *
+ *  Use of this source code is governed by a BSD-style license
+ *  that can be found in the LICENSE file in the root of the source
+ *  tree. An additional intellectual property rights grant can be found
+ *  in the file PATENTS.  All contributing project authors may
+ *  be found in the AUTHORS file in the root of the source tree.
+ */
+
+#ifndef API_TASK_QUEUE_TASK_QUEUE_IMPL_H_
+#define API_TASK_QUEUE_TASK_QUEUE_IMPL_H_
+
+#include <memory>
+
+#include "api/task_queue/queued_task.h"
+#include "rtc_base/task_queue.h"
+
+// TODO(danilchap): Remove Impl and dependency on rtc::TaskQueue when custom
+// implementations switch to use global factories that creates TaskQueue
+// instead of using link-time injection.
+class rtc::TaskQueue::Impl {
+ public:
+  virtual void Delete() = 0;
+  virtual void PostTask(std::unique_ptr<QueuedTask> task) = 0;
+  virtual void PostDelayedTask(std::unique_ptr<QueuedTask> task,
+                               uint32_t milliseconds) = 0;
+
+  void AddRef();
+  void Release();
+
+ protected:
+  virtual ~Impl() = default;
+
+ private:
+  friend class rtc::TaskQueue;
+  rtc::TaskQueue* task_queue_ = nullptr;
+};
+
+#endif  // API_TASK_QUEUE_TASK_QUEUE_IMPL_H_
diff --git a/rtc_base/task_queue.h b/rtc_base/task_queue.h
index 43497de..e2b5348 100644
--- a/rtc_base/task_queue.h
+++ b/rtc_base/task_queue.h
@@ -144,6 +144,7 @@
   // TaskQueue priority levels. On some platforms these will map to thread
   // priorities, on others such as Mac and iOS, GCD queue priorities.
   using Priority = ::webrtc::TaskQueuePriority;
+  class Impl;
 
   explicit TaskQueue(const char* queue_name,
                      Priority priority = Priority::NORMAL);
@@ -187,7 +188,6 @@
   }
 
  private:
-  class Impl;
   // TODO(danilchap): Remove when external implementaions of TaskQueue remove
   // these two functions.
   void PostTaskAndReply(std::unique_ptr<QueuedTask> task,