1 /* 2 * Copyright (c) 2021-2021 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_HIPLAYER_STATE_MACHINE_H 17 #define HISTREAMER_HIPLAYER_STATE_MACHINE_H 18 19 #include <map> 20 #include <memory> 21 #include <queue> 22 #include <tuple> 23 #include "foundation/log.h" 24 #include "foundation/osal/base/synchronizer.h" 25 #include "foundation/osal/thread/mutex.h" 26 #include "foundation/osal/thread/task.h" 27 #include "foundation/utils/blocking_queue.h" 28 #include "pipeline/core/error_code.h" 29 #include "play_executor.h" 30 #include "plugin/common/any.h" 31 #include "state.h" 32 33 namespace OHOS { 34 namespace Media { 35 class StateChangeCallback { 36 public: 37 virtual ~StateChangeCallback() = default; 38 virtual void OnStateChanged(StateId state) = 0; 39 }; 40 41 class StateMachine final : public OSAL::Task { 42 public: 43 explicit StateMachine(PlayExecutor& executor); 44 45 ~StateMachine() override = default; 46 47 void Stop() override; 48 49 void SetStateCallback(StateChangeCallback* callback); 50 51 const std::string& GetCurrentState() const; 52 53 StateId GetCurrentStateId() const; 54 55 ErrorCode SendEvent(Intent intent, const Plugin::Any& param = {}); 56 57 ErrorCode SendEvent(Intent intent, const Plugin::Any& param = {}) const; 58 59 ErrorCode SendEventAsync(Intent intent, const Plugin::Any& param = {}); 60 61 ErrorCode SendEventAsync(Intent intent, const Plugin::Any& param = {}) const; 62 63 void Notify(Intent intent, ErrorCode code); 64 65 private: 66 using Job = std::function<Action()>; 67 68 Action ProcessIntent(Intent intent, const Plugin::Any& param); 69 70 void DoTask() override; 71 72 void AddState(const std::shared_ptr<State>& state); 73 74 ErrorCode ProcAction(Action nextAction); 75 76 ErrorCode TransitionTo(const std::shared_ptr<State>& state); 77 78 void OnIntentExecuted(Intent intent, Action action, ErrorCode result); 79 80 mutable OSAL::Mutex mutex_ {}; 81 mutable OSAL::Synchronizer<Intent, ErrorCode> intentSync_; 82 mutable std::shared_ptr<State> curState_ {nullptr}; 83 mutable Intent lastIntent {Intent::INTENT_BUTT}; 84 std::map<StateId, std::shared_ptr<State>> states_ {}; 85 Media::BlockingQueue<Job> jobs_; 86 std::queue<Job> pendingJobs_ {}; 87 StateChangeCallback* callback_ {nullptr}; 88 }; 89 } // namespace Media 90 } // namespace OHOS 91 #endif 92