1 /* 2 * Copyright (c) 2021-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 HISTREAMER_FOUNDATION_OSAL_TASK_H 17 #define HISTREAMER_FOUNDATION_OSAL_TASK_H 18 19 #include <atomic> 20 #include <functional> 21 #include <string> 22 23 #include "osal/task/condition_variable.h" 24 #include "osal/task/mutex.h" 25 26 #ifndef MEDIA_FOUNDATION_FFRT 27 #include "osal/task/thread.h" 28 #endif 29 30 namespace OHOS { 31 namespace Media { 32 33 enum class TaskPriority : int { 34 LOW, 35 NORMAL, 36 MIDDLE, 37 HIGH, 38 HIGHEST, 39 }; 40 41 class TaskNative; 42 43 class Task { 44 public: 45 explicit Task(std::string name, TaskPriority priority = TaskPriority::HIGH); 46 47 explicit Task(std::string name, std::function<void()> job, TaskPriority priority = TaskPriority::HIGH); 48 49 virtual ~Task(); 50 51 virtual void Start(); 52 53 virtual void Stop(); 54 55 virtual void StopAsync(); 56 57 virtual void Pause(); 58 59 virtual void PauseAsync(); 60 61 virtual void DoTask(); 62 63 void RegisterJob(std::function<void()> job); 64 IsTaskRunning()65 bool IsTaskRunning() { return runningState_ == RunningState::STARTED; } 66 67 private: 68 enum class RunningState { 69 STARTED, 70 PAUSING, 71 PAUSED, 72 STOPPING, 73 STOPPED, 74 }; 75 76 void Run(); 77 78 Mutex stateMutex_{}; 79 ConditionVariable syncCond_{}; 80 const std::string name_; 81 const TaskPriority priority_; 82 std::atomic<RunningState> runningState_{RunningState::STOPPED}; 83 std::function<void()> job_ = [this] { DoTask(); }; 84 #ifdef MEDIA_FOUNDATION_FFRT 85 std::unique_ptr<ffrt::thread> loop_; 86 #else 87 std::unique_ptr<Thread> loop_; 88 #endif 89 }; 90 } // namespace Media 91 } // namespace OHOS 92 #endif // HISTREAMER_FOUNDATION_OSAL_TASK_H 93