xref: /aosp_15_r20/hardware/interfaces/audio/aidl/default/include/effect-impl/EffectThread.h (revision 4d7e907c777eeecc4c5bd7cf640a754fac206ff7)
1 /*
2  * Copyright (C) 2022 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #pragma once
18 #include <atomic>
19 #include <memory>
20 #include <string>
21 #include <thread>
22 
23 #include <android-base/thread_annotations.h>
24 #include <fmq/EventFlag.h>
25 #include <system/thread_defs.h>
26 
27 #include "effect-impl/EffectContext.h"
28 #include "effect-impl/EffectTypes.h"
29 
30 namespace aidl::android::hardware::audio::effect {
31 
32 class EffectThread {
33   public:
34     virtual ~EffectThread();
35 
36     // called by effect implementation
37     RetCode createThread(const std::string& name, int priority = ANDROID_PRIORITY_URGENT_AUDIO);
38     RetCode destroyThread();
39     RetCode startThread();
40     RetCode stopThread();
41     RetCode startDraining();
42     RetCode finishDraining();
43 
44     // Will call process() in a loop if the thread is running.
45     void threadLoop();
46 
47     /**
48      * process() call effectProcessImpl() for effect data processing, it is necessary for the
49      * processing to be called under Effect thread mutex mThreadMutex, to avoid the effect state
50      * change before/during data processing, and keep the thread and effect state consistent.
51      */
52     virtual void process() = 0;
53 
54   protected:
55     bool mDraining GUARDED_BY(mThreadMutex) = false;
56 
57   private:
58     static constexpr int kMaxTaskNameLen = 15;
59 
60     std::mutex mThreadMutex;
61     std::condition_variable mCv;
62     bool mStop GUARDED_BY(mThreadMutex) = true;
63     bool mExit GUARDED_BY(mThreadMutex) = false;
64 
65     std::thread mThread;
66     int mPriority;
67     std::string mName;
68 };
69 }  // namespace aidl::android::hardware::audio::effect
70