xref: /aosp_15_r20/external/webrtc/api/metronome/test/fake_metronome.h (revision d9f758449e529ab9291ac668be2861e7a55c2422)
1 /*
2  *  Copyright (c) 2022 The WebRTC project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10 
11 #ifndef API_METRONOME_TEST_FAKE_METRONOME_H_
12 #define API_METRONOME_TEST_FAKE_METRONOME_H_
13 
14 #include <memory>
15 #include <set>
16 #include <vector>
17 
18 #include "api/metronome/metronome.h"
19 #include "api/task_queue/task_queue_base.h"
20 #include "api/task_queue/task_queue_factory.h"
21 #include "api/units/time_delta.h"
22 #include "rtc_base/synchronization/mutex.h"
23 #include "rtc_base/task_queue.h"
24 #include "rtc_base/task_utils/repeating_task.h"
25 #include "rtc_base/thread_annotations.h"
26 
27 namespace webrtc::test {
28 
29 // ForcedTickMetronome is a Metronome that ticks when `Tick()` is invoked.
30 // The constructor argument `tick_period` returned in `TickPeriod()`.
31 class ForcedTickMetronome : public Metronome {
32  public:
33   explicit ForcedTickMetronome(TimeDelta tick_period);
34 
35   // Forces all TickListeners to run `OnTick`.
36   void Tick();
37   size_t NumListeners();
38 
39   // Metronome implementation.
40   void RequestCallOnNextTick(absl::AnyInvocable<void() &&> callback) override;
41   TimeDelta TickPeriod() const override;
42 
43  private:
44   const TimeDelta tick_period_;
45   std::vector<absl::AnyInvocable<void() &&>> callbacks_;
46 };
47 
48 // FakeMetronome is a metronome that ticks based on a repeating task at the
49 // `tick_period` provided in the constructor. It is designed for use with
50 // simulated task queues for unit tests.
51 //
52 // `Stop()` must be called before destruction, as it cancels the metronome tick
53 // on the proper task queue.
54 class FakeMetronome : public Metronome {
55  public:
56   explicit FakeMetronome(TimeDelta tick_period);
57 
58   // Metronome implementation.
59   void RequestCallOnNextTick(absl::AnyInvocable<void() &&> callback) override;
60   TimeDelta TickPeriod() const override;
61 
62  private:
63   const TimeDelta tick_period_;
64   std::vector<absl::AnyInvocable<void() &&>> callbacks_;
65 };
66 
67 }  // namespace webrtc::test
68 
69 #endif  // API_METRONOME_TEST_FAKE_METRONOME_H_
70