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