1 /*
2  * Copyright (C) 2016 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 namespace android {
18 
19 // T is FastMixer or FastCapture
20 template<typename T> class AutoPark {
21 public:
22 
23     // Park the specific FastThread, which can be nullptr, in hot idle if not currently idling
AutoPark(const sp<T> & fastThread)24     explicit AutoPark(const sp<T>& fastThread) : mFastThread(fastThread)
25     {
26         mPreviousCommand = FastThreadState::HOT_IDLE;
27         if (fastThread != nullptr) {
28             auto sq = mFastThread->sq();
29             FastThreadState *state = sq->begin();
30             if (!(state->mCommand & FastThreadState::IDLE)) {
31                 mPreviousCommand = state->mCommand;
32                 state->mCommand = FastThreadState::HOT_IDLE;
33                 sq->end();
34                 sq->push(sq->BLOCK_UNTIL_ACKED);
35             } else {
36                 sq->end(false /*didModify*/);
37             }
38         }
39     }
40 
41     // Remove the FastThread from hot idle if necessary
~AutoPark()42     ~AutoPark()
43     {
44         if (!(mPreviousCommand & FastThreadState::IDLE)) {
45             ALOG_ASSERT(mFastThread != nullptr);
46             auto sq = mFastThread->sq();
47             FastThreadState *state = sq->begin();
48             ALOG_ASSERT(state->mCommand == FastThreadState::HOT_IDLE);
49             state->mCommand = mPreviousCommand;
50             sq->end();
51             sq->push(sq->BLOCK_UNTIL_PUSHED);
52         }
53     }
54 
55 private:
56     const sp<T>                 mFastThread;
57     // if !&IDLE, holds the FastThread state to restore after new parameters processed
58     FastThreadState::Command    mPreviousCommand;
59 };  // class AutoPark
60 
61 }   // namespace
62