1 /*
2  * Copyright (C) 2012 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5  * use this file except in compliance with the License. You may obtain a copy of
6  * 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, WITHOUT
12  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13  * License for the specific language governing permissions and limitations under
14  * the License.
15  */
16 
17 
18 #ifndef CTSAUDIO_AUDIOLOCAL_H
19 #define CTSAUDIO_AUDIOLOCAL_H
20 
21 #include <utils/StrongPointer.h>
22 #include <utils/threads.h>
23 
24 #include <Semaphore.h>
25 
26 #include "AudioHardware.h"
27 
28 class Buffer;
29 
30 /**
31  * Basic API for playback and record
32  */
33 class AudioLocal: public android::Thread, public AudioHardware {
34 public:
35 
36     virtual bool prepare(AudioHardware::SamplingRate samplingRate, int gain,
37             int mode = AudioHardware::EModeVoice);
38     virtual bool startPlaybackOrRecord(android::sp<Buffer>& buffer, int numberRepetition = 1);
39     virtual bool waitForCompletion();
40     virtual void stopPlaybackOrRecord();
41 
42     virtual ~AudioLocal();
43 protected:
44     AudioLocal();
45 
46     virtual bool doPrepare(AudioHardware::SamplingRate, int samplesInOneGo) = 0;
47     virtual bool doPlaybackOrRecord(android::sp<Buffer>& buffer) = 0;
48     virtual void doStop() = 0;
releaseHw()49     virtual void releaseHw() {};
50 
51 private:
52 
53 
54     bool threadLoop();
55 
56     enum AudioCommand{
57         ECmNone = 0,
58         ECmInitialize,
59         ECmRun,
60         ECmStop,
61         ECmThreadStop // terminate the thread
62     };
63 
64     bool issueCommandAndWaitForCompletion(AudioCommand command);
65 
66 protected:
67 
68 private:
69     // only one command at a time.
70     // Thus, all parameters can be stored here.
71     AudioHardware::SamplingRate mSamplingRate;
72 
73     android::sp<Buffer> mBuffer;
74     int mNumberRepetition;
75     int mCurrentRepeat;
76 
77     enum AudioState{
78         EStNone,
79         EStCreated,
80         EStInitialized,
81         EStRunning  // playing or recording
82     };
83     volatile AudioState mState;
84     volatile AudioCommand mCurrentCommand;
85 
86 
87     static const int COMMAND_WAIT_TIME_MSEC = 4000;
88 
89     Semaphore mClientCommandWait;
90     Semaphore mClientCompletionWait;
91     Semaphore mAudioThreadWait;
92 
93     bool mCommandResult;
94     bool mCompletionResult;
95 };
96 
97 #endif // CTSAUDIO_AUDIOLOCAL_H
98