| Glenn Kasten | dc998c8 | 2012-03-23 18:53:59 -0700 | [diff] [blame] | 1 | /* | 
 | 2 |  * Copyright (C) 2012 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 | #ifndef ANDROID_AUDIO_STATE_QUEUE_H | 
 | 18 | #define ANDROID_AUDIO_STATE_QUEUE_H | 
 | 19 |  | 
| Glenn Kasten | 2188bc9 | 2012-10-26 16:10:30 -0700 | [diff] [blame] | 20 | // The state queue template class was originally driven by this use case / requirements: | 
 | 21 | //  There are two threads: a fast mixer, and a normal mixer, and they share state. | 
 | 22 | //  The interesting part of the shared state is a set of active fast tracks, | 
 | 23 | //  and the output HAL configuration (buffer size in frames, sample rate, etc.). | 
 | 24 | //  Fast mixer thread: | 
 | 25 | //      periodic with typical period < 10 ms | 
 | 26 | //      FIFO/RR scheduling policy and a low fixed priority | 
 | 27 | //      ok to block for bounded time using nanosleep() to achieve desired period | 
 | 28 | //      must not block on condition wait, mutex lock, atomic operation spin, I/O, etc. | 
 | 29 | //        under typical operations of mixing, writing, or adding/removing tracks | 
 | 30 | //      ok to block for unbounded time when the output HAL configuration changes, | 
 | 31 | //        and this may result in an audible artifact | 
 | 32 | //      needs read-only access to a recent stable state, | 
 | 33 | //        but not necessarily the most current one | 
| Glenn Kasten | fb1fdc9 | 2013-07-10 17:03:19 -0700 | [diff] [blame^] | 34 | //      only allocate and free memory when configuration changes | 
 | 35 | //      avoid conventional logging, as this is a form of I/O and could block | 
 | 36 | //      defer computation to other threads when feasible; for example | 
 | 37 | //        cycle times are collected by fast mixer thread but the floating-point | 
 | 38 | //        statistical calculations on these cycle times are computed by normal mixer | 
 | 39 | //      these requirements also apply to callouts such as AudioBufferProvider and VolumeProvider | 
| Glenn Kasten | 2188bc9 | 2012-10-26 16:10:30 -0700 | [diff] [blame] | 40 | //  Normal mixer thread: | 
| Glenn Kasten | fb1fdc9 | 2013-07-10 17:03:19 -0700 | [diff] [blame^] | 41 | //      periodic with typical period ~20 ms | 
| Glenn Kasten | 2188bc9 | 2012-10-26 16:10:30 -0700 | [diff] [blame] | 42 | //      SCHED_OTHER scheduling policy and nice priority == urgent audio | 
 | 43 | //      ok to block, but prefer to avoid as much as possible | 
 | 44 | //      needs read/write access to state | 
 | 45 | //  The normal mixer may need to temporarily suspend the fast mixer thread during mode changes. | 
 | 46 | //  It will do this using the state -- one of the fields tells the fast mixer to idle. | 
 | 47 |  | 
 | 48 | // Additional requirements: | 
 | 49 | //  - observer must always be able to poll for and view the latest pushed state; it must never be | 
 | 50 | //    blocked from seeing that state | 
 | 51 | //  - observer does not need to see every state in sequence; it is OK for it to skip states | 
 | 52 | //    [see below for more on this] | 
 | 53 | //  - mutator must always be able to read/modify a state, it must never be blocked from reading or | 
 | 54 | //    modifying state | 
 | 55 | //  - reduce memcpy where possible | 
 | 56 | //  - work well if the observer runs more frequently than the mutator, | 
 | 57 | //    as is the case with fast mixer/normal mixer. | 
 | 58 | // It is not a requirement to work well if the roles were reversed, | 
 | 59 | // and the mutator were to run more frequently than the observer. | 
 | 60 | // In this case, the mutator could get blocked waiting for a slot to fill up for | 
 | 61 | // it to work with. This could be solved somewhat by increasing the depth of the queue, but it would | 
 | 62 | // still limit the mutator to a finite number of changes before it would block.  A future | 
 | 63 | // possibility, not implemented here, would be to allow the mutator to safely overwrite an already | 
 | 64 | // pushed state. This could be done by the mutator overwriting mNext, but then being prepared to | 
 | 65 | // read an mAck which is actually for the earlier mNext (since there is a race). | 
 | 66 |  | 
 | 67 | // Solution: | 
 | 68 | //  Let's call the fast mixer thread the "observer" and normal mixer thread the "mutator". | 
 | 69 | //  We assume there is only a single observer and a single mutator; this is critical. | 
 | 70 | //  Each state is of type <T>, and should contain only POD (Plain Old Data) and raw pointers, as | 
 | 71 | //  memcpy() may be used to copy state, and the destructors are run in unpredictable order. | 
 | 72 | //  The states in chronological order are: previous, current, next, and mutating: | 
 | 73 | //      previous    read-only, observer can compare vs. current to see the subset that changed | 
 | 74 | //      current     read-only, this is the primary state for observer | 
 | 75 | //      next        read-only, when observer is ready to accept a new state it will shift it in: | 
 | 76 | //                      previous = current | 
 | 77 | //                      current = next | 
 | 78 | //                  and the slot formerly used by previous is now available to the mutator. | 
 | 79 | //      mutating    invisible to observer, read/write to mutator | 
 | 80 | //  Initialization is tricky, especially for the observer.  If the observer starts execution | 
 | 81 | //  before the mutator, there are no previous, current, or next states.  And even if the observer | 
 | 82 | //  starts execution after the mutator, there is a next state but no previous or current states. | 
 | 83 | //  To solve this, we'll have the observer idle until there is a next state, | 
 | 84 | //  and it will have to deal with the case where there is no previous state. | 
 | 85 | //  The states are stored in a shared FIFO queue represented using a circular array. | 
 | 86 | //  The observer polls for mutations, and receives a new state pointer after a | 
 | 87 | //  a mutation is pushed onto the queue.  To the observer, the state pointers are | 
 | 88 | //  effectively in random order, that is the observer should not do address | 
 | 89 | //  arithmetic on the state pointers.  However to the mutator, the state pointers | 
 | 90 | //  are in a definite circular order. | 
 | 91 |  | 
| Glenn Kasten | dc998c8 | 2012-03-23 18:53:59 -0700 | [diff] [blame] | 92 | namespace android { | 
 | 93 |  | 
| Glenn Kasten | 3999308 | 2012-05-31 13:40:27 -0700 | [diff] [blame] | 94 | #ifdef STATE_QUEUE_DUMP | 
 | 95 | // The StateQueueObserverDump and StateQueueMutatorDump keep | 
 | 96 | // a cache of StateQueue statistics that can be logged by dumpsys. | 
 | 97 | // Each individual native word-sized field is accessed atomically.  But the | 
 | 98 | // overall structure is non-atomic, that is there may be an inconsistency between fields. | 
 | 99 | // No barriers or locks are used for either writing or reading. | 
 | 100 | // Only POD types are permitted, and the contents shouldn't be trusted (i.e. do range checks). | 
 | 101 | // It has a different lifetime than the StateQueue, and so it can't be a member of StateQueue. | 
 | 102 |  | 
 | 103 | struct StateQueueObserverDump { | 
 | 104 |     StateQueueObserverDump() : mStateChanges(0) { } | 
 | 105 |     /*virtual*/ ~StateQueueObserverDump() { } | 
 | 106 |     unsigned    mStateChanges;    // incremented each time poll() detects a state change | 
 | 107 |     void        dump(int fd); | 
 | 108 | }; | 
 | 109 |  | 
 | 110 | struct StateQueueMutatorDump { | 
 | 111 |     StateQueueMutatorDump() : mPushDirty(0), mPushAck(0), mBlockedSequence(0) { } | 
 | 112 |     /*virtual*/ ~StateQueueMutatorDump() { } | 
 | 113 |     unsigned    mPushDirty;       // incremented each time push() is called with a dirty state | 
 | 114 |     unsigned    mPushAck;         // incremented each time push(BLOCK_UNTIL_ACKED) is called | 
 | 115 |     unsigned    mBlockedSequence; // incremented before and after each time that push() | 
 | 116 |                                   // blocks for more than one PUSH_BLOCK_ACK_NS; | 
 | 117 |                                   // if odd, then mutator is currently blocked inside push() | 
 | 118 |     void        dump(int fd); | 
 | 119 | }; | 
 | 120 | #endif | 
 | 121 |  | 
| Glenn Kasten | dc998c8 | 2012-03-23 18:53:59 -0700 | [diff] [blame] | 122 | // manages a FIFO queue of states | 
 | 123 | template<typename T> class StateQueue { | 
 | 124 |  | 
 | 125 | public: | 
 | 126 |             StateQueue(); | 
 | 127 |     virtual ~StateQueue(); | 
 | 128 |  | 
 | 129 |     // Observer APIs | 
 | 130 |  | 
 | 131 |     // Poll for a state change.  Returns a pointer to a read-only state, | 
 | 132 |     // or NULL if the state has not been initialized yet. | 
 | 133 |     // If a new state has not pushed by mutator since the previous poll, | 
 | 134 |     // then the returned pointer will be unchanged. | 
 | 135 |     // The previous state pointer is guaranteed to still be valid; | 
 | 136 |     // this allows the observer to diff the previous and new states. | 
 | 137 |     const T* poll(); | 
 | 138 |  | 
 | 139 |     // Mutator APIs | 
 | 140 |  | 
 | 141 |     // Begin a mutation.  Returns a pointer to a read/write state, except the | 
 | 142 |     // first time it is called the state is write-only and _must_ be initialized. | 
 | 143 |     // Mutations cannot be nested. | 
 | 144 |     // If the state is dirty and has not been pushed onto the state queue yet, then | 
 | 145 |     // this new mutation will be squashed together with the previous one. | 
 | 146 |     T*      begin(); | 
 | 147 |  | 
 | 148 |     // End the current mutation and indicate whether caller modified the state. | 
 | 149 |     // If didModify is true, then the state is marked dirty (in need of pushing). | 
 | 150 |     // There is no rollback option because modifications are done in place. | 
 | 151 |     // Does not automatically push the new state onto the state queue. | 
 | 152 |     void    end(bool didModify = true); | 
 | 153 |  | 
 | 154 |     // Push a new state, if any, out to the observer via the state queue. | 
 | 155 |     // For BLOCK_NEVER, returns: | 
 | 156 |     //      true if not dirty, or dirty and pushed successfully | 
 | 157 |     //      false if dirty and not pushed because that would block; remains dirty | 
 | 158 |     // For BLOCK_UNTIL_PUSHED and BLOCK_UNTIL_ACKED, always returns true. | 
 | 159 |     // No-op if there are no pending modifications (not dirty), except | 
 | 160 |     //      for BLOCK_UNTIL_ACKED it will wait until a prior push has been acknowledged. | 
 | 161 |     // Must not be called in the middle of a mutation. | 
 | 162 |     enum block_t { | 
 | 163 |         BLOCK_NEVER,        // do not block | 
 | 164 |         BLOCK_UNTIL_PUSHED, // block until there's a slot available for the push | 
 | 165 |         BLOCK_UNTIL_ACKED,  // also block until the push is acknowledged by the observer | 
 | 166 |     }; | 
 | 167 |     bool    push(block_t block = BLOCK_NEVER); | 
 | 168 |  | 
 | 169 |     // Return whether the current state is dirty (modified and not pushed). | 
 | 170 |     bool    isDirty() const { return mIsDirty; } | 
 | 171 |  | 
| Glenn Kasten | 3999308 | 2012-05-31 13:40:27 -0700 | [diff] [blame] | 172 | #ifdef STATE_QUEUE_DUMP | 
 | 173 |     // Register location of observer dump area | 
 | 174 |     void    setObserverDump(StateQueueObserverDump *dump) | 
 | 175 |             { mObserverDump = dump != NULL ? dump : &mObserverDummyDump; } | 
 | 176 |  | 
 | 177 |     // Register location of mutator dump area | 
 | 178 |     void    setMutatorDump(StateQueueMutatorDump *dump) | 
 | 179 |             { mMutatorDump = dump != NULL ? dump : &mMutatorDummyDump; } | 
 | 180 | #endif | 
 | 181 |  | 
| Glenn Kasten | dc998c8 | 2012-03-23 18:53:59 -0700 | [diff] [blame] | 182 | private: | 
| Glenn Kasten | 7f5d335 | 2013-02-15 23:55:04 +0000 | [diff] [blame] | 183 |     static const unsigned kN = 4;       // values < 4 are not supported by this code | 
| Glenn Kasten | dc998c8 | 2012-03-23 18:53:59 -0700 | [diff] [blame] | 184 |     T                 mStates[kN];      // written by mutator, read by observer | 
 | 185 |  | 
 | 186 |     // "volatile" is meaningless with SMP, but here it indicates that we're using atomic ops | 
 | 187 |     volatile const T* mNext; // written by mutator to advance next, read by observer | 
 | 188 |     volatile const T* mAck;  // written by observer to acknowledge advance of next, read by mutator | 
 | 189 |  | 
 | 190 |     // only used by observer | 
 | 191 |     const T*          mCurrent;         // most recent value returned by poll() | 
 | 192 |  | 
 | 193 |     // only used by mutator | 
 | 194 |     T*                mMutating;        // where updates by mutator are done in place | 
 | 195 |     const T*          mExpecting;       // what the mutator expects mAck to be set to | 
 | 196 |     bool              mInMutation;      // whether we're currently in the middle of a mutation | 
 | 197 |     bool              mIsDirty;         // whether mutating state has been modified since last push | 
 | 198 |     bool              mIsInitialized;   // whether mutating state has been initialized yet | 
 | 199 |  | 
| Glenn Kasten | 3999308 | 2012-05-31 13:40:27 -0700 | [diff] [blame] | 200 | #ifdef STATE_QUEUE_DUMP | 
 | 201 |     StateQueueObserverDump  mObserverDummyDump; // default area for observer dump if not set | 
 | 202 |     StateQueueObserverDump* mObserverDump;      // pointer to active observer dump, always non-NULL | 
 | 203 |     StateQueueMutatorDump   mMutatorDummyDump;  // default area for mutator dump if not set | 
 | 204 |     StateQueueMutatorDump*  mMutatorDump;       // pointer to active mutator dump, always non-NULL | 
 | 205 | #endif | 
 | 206 |  | 
| Glenn Kasten | dc998c8 | 2012-03-23 18:53:59 -0700 | [diff] [blame] | 207 | };  // class StateQueue | 
 | 208 |  | 
 | 209 | }   // namespace android | 
 | 210 |  | 
 | 211 | #endif  // ANDROID_AUDIO_STATE_QUEUE_H |