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 #ifndef ANDROID_AAUDIO_AUDIO_STREAM_INTERNAL_H
18 #define ANDROID_AAUDIO_AUDIO_STREAM_INTERNAL_H
19 
20 #include <stdint.h>
21 #include <aaudio/AAudio.h>
22 
23 #include "binding/IAAudioService.h"
24 #include "binding/AudioEndpointParcelable.h"
25 #include "binding/AAudioServiceInterface.h"
26 #include "client/IsochronousClockModel.h"
27 #include "client/AudioEndpoint.h"
28 #include "core/AudioStream.h"
29 #include "utility/AudioClock.h"
30 #include "utility/LinearRamp.h"
31 
32 using android::sp;
33 using android::IAAudioService;
34 
35 namespace aaudio {
36 
37     // These are intended to be outside the range of what is normally encountered.
38     // TODO MAXes should probably be much bigger.
39     constexpr int32_t MIN_FRAMES_PER_BURST = 16; // arbitrary
40     constexpr int32_t MAX_FRAMES_PER_BURST = 16 * 1024;  // arbitrary
41     constexpr int32_t MAX_BUFFER_CAPACITY_IN_FRAMES = 32 * 1024;  // arbitrary
42 
43 // A stream that talks to the AAudioService or directly to a HAL.
44 class AudioStreamInternal : public AudioStream {
45 
46 public:
47     AudioStreamInternal(AAudioServiceInterface  &serviceInterface, bool inService);
48     virtual ~AudioStreamInternal();
49 
50     aaudio_result_t requestStart() override;
51 
52     aaudio_result_t requestStop() override;
53 
54     aaudio_result_t getTimestamp(clockid_t clockId,
55                                        int64_t *framePosition,
56                                        int64_t *timeNanoseconds) override;
57 
58     virtual aaudio_result_t updateStateMachine() override;
59 
60     aaudio_result_t open(const AudioStreamBuilder &builder) override;
61 
62     aaudio_result_t close() override;
63 
64     aaudio_result_t setBufferSize(int32_t requestedFrames) override;
65 
66     int32_t getBufferSize() const override;
67 
68     int32_t getBufferCapacity() const override;
69 
70     int32_t getFramesPerBurst() const override;
71 
getXRunCount()72     int32_t getXRunCount() const override {
73         return mXRunCount;
74     }
75 
76     aaudio_result_t registerThread() override;
77 
78     aaudio_result_t unregisterThread() override;
79 
80     aaudio_result_t joinThread(void** returnArg);
81 
82     // Called internally from 'C'
83     virtual void *callbackLoop() = 0;
84 
85 
isMMap()86     bool isMMap() override {
87         return true;
88     }
89 
90     // Calculate timeout based on framesPerBurst
91     int64_t calculateReasonableTimeout();
92 
93     aaudio_result_t startClient(const android::AudioClient& client,
94                                 audio_port_handle_t *clientHandle);
95 
96     aaudio_result_t stopClient(audio_port_handle_t clientHandle);
97 
getServiceHandle()98     aaudio_handle_t getServiceHandle() const {
99         return mServiceStreamHandle;
100     }
101 
102 protected:
103 
104     aaudio_result_t processData(void *buffer,
105                          int32_t numFrames,
106                          int64_t timeoutNanoseconds);
107 
108 /**
109  * Low level data processing that will not block. It will just read or write as much as it can.
110  *
111  * It passed back a recommended time to wake up if wakeTimePtr is not NULL.
112  *
113  * @return the number of frames processed or a negative error code.
114  */
115     virtual aaudio_result_t processDataNow(void *buffer,
116                             int32_t numFrames,
117                             int64_t currentTimeNanos,
118                             int64_t *wakeTimePtr) = 0;
119 
120     aaudio_result_t drainTimestampsFromService();
121 
122     aaudio_result_t processCommands();
123 
124     aaudio_result_t stopCallback();
125 
126     virtual void advanceClientToMatchServerPosition() = 0;
127 
onFlushFromServer()128     virtual void onFlushFromServer() {}
129 
130     aaudio_result_t onEventFromServer(AAudioServiceMessage *message);
131 
132     aaudio_result_t onTimestampService(AAudioServiceMessage *message);
133 
134     aaudio_result_t onTimestampHardware(AAudioServiceMessage *message);
135 
136     void logTimestamp(AAudioServiceMessage &message);
137 
138     // Calculate timeout for an operation involving framesPerOperation.
139     int64_t calculateReasonableTimeout(int32_t framesPerOperation);
140 
getDeviceChannelCount()141     int32_t getDeviceChannelCount() const { return mDeviceChannelCount; }
142 
143     /**
144      * @return true if running in audio service, versus in app process
145      */
isInService()146     bool isInService() const { return mInService; }
147 
148     IsochronousClockModel    mClockModel;      // timing model for chasing the HAL
149 
150     AudioEndpoint            mAudioEndpoint;   // source for reads or sink for writes
151     aaudio_handle_t          mServiceStreamHandle; // opaque handle returned from service
152 
153     int32_t                  mFramesPerBurst = MIN_FRAMES_PER_BURST; // frames per HAL transfer
154     int32_t                  mXRunCount = 0;      // how many underrun events?
155 
156     // Offset from underlying frame position.
157     int64_t                  mFramesOffsetFromService = 0; // offset for timestamps
158 
159     uint8_t                 *mCallbackBuffer = nullptr;
160     int32_t                  mCallbackFrames = 0;
161 
162     // The service uses this for SHARED mode.
163     bool                     mInService = false;  // Is this running in the client or the service?
164 
165     AAudioServiceInterface  &mServiceInterface;   // abstract interface to the service
166 
167     SimpleDoubleBuffer<Timestamp>  mAtomicTimestamp;
168 
169     AtomicRequestor          mNeedCatchUp;   // Ask read() or write() to sync on first timestamp.
170 
171     float                    mStreamVolume = 1.0f;
172 
173 private:
174     /*
175      * Asynchronous write with data conversion.
176      * @param buffer
177      * @param numFrames
178      * @return fdrames written or negative error
179      */
180     aaudio_result_t writeNowWithConversion(const void *buffer,
181                                      int32_t numFrames);
182 
183     // Adjust timing model based on timestamp from service.
184     void processTimestamp(uint64_t position, int64_t time);
185 
186     // Thread on other side of FIFO will have wakeup jitter.
187     // By delaying slightly we can avoid waking up before other side is ready.
188     const int32_t            mWakeupDelayNanos; // delay past typical wakeup jitter
189     const int32_t            mMinimumSleepNanos; // minimum sleep while polling
190 
191     AudioEndpointParcelable  mEndPointParcelable; // description of the buffers filled by service
192     EndpointDescriptor       mEndpointDescriptor; // buffer description with resolved addresses
193 
194     int64_t                  mServiceLatencyNanos = 0;
195 
196     int32_t                  mDeviceChannelCount = 0;
197 };
198 
199 } /* namespace aaudio */
200 
201 #endif //ANDROID_AAUDIO_AUDIO_STREAM_INTERNAL_H
202