1/*
2 * Copyright (C) 2023 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16#ifndef AV_CODEC_TASK_THREAD_H
17#define AV_CODEC_TASK_THREAD_H
18
19#include <atomic>
20#include <condition_variable>
21#include <functional>
22#include <memory>
23#include <mutex>
24#include <string_view>
25#include <thread>
26
27namespace OHOS {
28namespace MediaAVCodec {
29class __attribute__((visibility("default"))) TaskThread {
30public:
31    explicit TaskThread(std::string_view name);
32
33    TaskThread(std::string_view name, std::function<void()> handler);
34
35    ~TaskThread();
36
37    void Start();
38
39    void Stop();
40
41    void StopAsync();
42
43    void Pause();
44
45    void PauseAsync();
46
47    void RegisterHandler(std::function<void()> handler);
48
49private:
50    void doTask();
51    void Run();
52
53private:
54    enum class RunningState {
55        STARTED,
56        PAUSING,
57        PAUSED,
58        STOPPING,
59        STOPPED,
60    };
61    const std::string_view name_;
62    std::atomic<RunningState> runningState_;
63    std::unique_ptr<std::thread> loop_;
64    std::function<void()> handler_ = [this] { doTask(); };
65    std::mutex stateMutex_;
66    std::condition_variable syncCond_;
67};
68} // namespace MediaAVCodec
69} // namespace OHOS
70#endif