1 /* 2 * Copyright (C) 2025 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 MEDIA_AVCODEC_ADAPTIVE_FRAMERATE_CONTROLLER_H 17 #define MEDIA_AVCODEC_ADAPTIVE_FRAMERATE_CONTROLLER_H 18 19 #include <chrono> 20 #include <functional> 21 #include <atomic> 22 #include <thread> 23 #include <condition_variable> 24 #include <mutex> 25 #include <memory> 26 #include "avcodec_dfx_component.h" 27 28 namespace OHOS { 29 namespace MediaAVCodec { 30 class FramerateCalculator : public std::enable_shared_from_this<FramerateCalculator>, 31 public AVCodecDfxComponent { 32 public: 33 FramerateCalculator(int32_t instanceId, bool isDecoder, 34 std::function<void(double)> &&resetFramerateHandler); 35 void OnFrameConsumed(); 36 void OnStopped(); 37 bool CheckAndResetFramerate(); 38 void SetConfiguredFramerate(double framerate); 39 bool SetFramerate2ConfiguredFramerate(); 40 41 private: 42 enum class Status { 43 INITIALIZED, 44 RUNNING, 45 STOPPED, 46 }; 47 void Register2AFC(); 48 void UnregisterFromAFC(); 49 50 int32_t instanceId_; 51 bool isDecoder_ = true; 52 std::atomic<Status> status_ = Status::INITIALIZED; 53 std::atomic<uint32_t> frameCount_{0}; 54 double configuredFramerate_{60.0}; 55 std::atomic<double> lastFramerate_{1.0}; 56 uint8_t increseCheckTimes_{0}; 57 uint8_t decreseCheckTimes_{0}; 58 std::chrono::steady_clock::time_point lastAdjustmentTime_{}; 59 std::function<void(double)> resetFramerateHandler_; 60 }; 61 62 class AdaptiveFramerateController { 63 public: 64 static AdaptiveFramerateController &GetInstance(); 65 void Add(int32_t intanceId, std::shared_ptr<FramerateCalculator> calculator); 66 void Remove(int32_t instanceId); 67 68 private: 69 void Loop(); 70 71 std::unordered_map<int32_t, std::weak_ptr<FramerateCalculator>> calculators_; 72 std::mutex calculatorsMutex_; 73 std::unique_ptr<std::thread> looper_; 74 std::mutex looperMutex_; 75 std::condition_variable condition_; 76 std::atomic<bool> isRunning_ = false; 77 }; 78 } // namespace MediaAVCodec 79 } // namespace OHOS 80 #endif // MEDIA_AVCODEC_ADAPTIVE_FRAMERATE_CONTROLLER_H