1 /*
2 * Copyright (C) 2017 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 #define LOG_TAG "AAudioServiceEndpointPlay"
18 //#define LOG_NDEBUG 0
19 #include <utils/Log.h>
20
21 #include <assert.h>
22 #include <map>
23 #include <mutex>
24 #include <media/AudioSystem.h>
25 #include <utils/Singleton.h>
26
27 #include "AAudioEndpointManager.h"
28 #include "AAudioServiceEndpoint.h"
29 #include <algorithm>
30 #include <mutex>
31 #include <vector>
32
33 #include "core/AudioStreamBuilder.h"
34 #include "AAudioServiceEndpoint.h"
35 #include "AAudioServiceStreamShared.h"
36 #include "AAudioServiceEndpointPlay.h"
37 #include "AAudioServiceEndpointShared.h"
38 #include "AAudioServiceStreamBase.h"
39
40 using namespace android; // TODO just import names needed
41 using namespace aaudio; // TODO just import names needed
42
43 #define BURSTS_PER_BUFFER_DEFAULT 2
44
AAudioServiceEndpointPlay(AAudioService & audioService)45 AAudioServiceEndpointPlay::AAudioServiceEndpointPlay(AAudioService& audioService)
46 : AAudioServiceEndpointShared(
47 new AudioStreamInternalPlay(audioService.asAAudioServiceInterface(), true)) {}
48
open(const aaudio::AAudioStreamRequest & request)49 aaudio_result_t AAudioServiceEndpointPlay::open(const aaudio::AAudioStreamRequest &request) {
50 aaudio_result_t result = AAudioServiceEndpointShared::open(request);
51 if (result == AAUDIO_OK) {
52 mMixer.allocate(getStreamInternal()->getSamplesPerFrame(),
53 getStreamInternal()->getFramesPerBurst());
54
55 int32_t burstsPerBuffer = AudioSystem::getAAudioMixerBurstCount();
56 if (burstsPerBuffer == 0) {
57 mLatencyTuningEnabled = true;
58 burstsPerBuffer = BURSTS_PER_BUFFER_DEFAULT;
59 }
60 int32_t desiredBufferSize = burstsPerBuffer * getStreamInternal()->getFramesPerBurst();
61 getStreamInternal()->setBufferSize(desiredBufferSize);
62 }
63 return result;
64 }
65
66 // Mix data from each application stream and write result to the shared MMAP stream.
callbackLoop()67 void *AAudioServiceEndpointPlay::callbackLoop() {
68 ALOGD("%s() entering >>>>>>>>>>>>>>> MIXER", __func__);
69 aaudio_result_t result = AAUDIO_OK;
70 int64_t timeoutNanos = getStreamInternal()->calculateReasonableTimeout();
71
72 // result might be a frame count
73 while (mCallbackEnabled.load() && getStreamInternal()->isActive() && (result >= 0)) {
74 // Mix data from each active stream.
75 mMixer.clear();
76
77 { // brackets are for lock_guard
78 int index = 0;
79 int64_t mmapFramesWritten = getStreamInternal()->getFramesWritten();
80
81 std::lock_guard <std::mutex> lock(mLockStreams);
82 for (const auto& clientStream : mRegisteredStreams) {
83 int64_t clientFramesRead = 0;
84 bool allowUnderflow = true;
85
86 if (clientStream->isSuspended()) {
87 continue; // dead stream
88 }
89
90 aaudio_stream_state_t state = clientStream->getState();
91 if (state == AAUDIO_STREAM_STATE_STOPPING) {
92 allowUnderflow = false; // just read what is already in the FIFO
93 } else if (state != AAUDIO_STREAM_STATE_STARTED) {
94 continue; // this stream is not running so skip it.
95 }
96
97 sp<AAudioServiceStreamShared> streamShared =
98 static_cast<AAudioServiceStreamShared *>(clientStream.get());
99
100 {
101 // Lock the AudioFifo to protect against close.
102 std::lock_guard <std::mutex> lock(streamShared->audioDataQueueLock);
103 std::shared_ptr<SharedRingBuffer> audioDataQueue
104 = streamShared->getAudioDataQueue_l();
105 std::shared_ptr<FifoBuffer> fifo;
106 if (audioDataQueue && (fifo = audioDataQueue->getFifoBuffer())) {
107
108 // Determine offset between framePosition in client's stream
109 // vs the underlying MMAP stream.
110 clientFramesRead = fifo->getReadCounter();
111 // These two indices refer to the same frame.
112 int64_t positionOffset = mmapFramesWritten - clientFramesRead;
113 streamShared->setTimestampPositionOffset(positionOffset);
114
115 int32_t framesMixed = mMixer.mix(index, fifo, allowUnderflow);
116
117 if (streamShared->isFlowing()) {
118 // Consider it an underflow if we got less than a burst
119 // after the data started flowing.
120 bool underflowed = allowUnderflow
121 && framesMixed < mMixer.getFramesPerBurst();
122 if (underflowed) {
123 streamShared->incrementXRunCount();
124 }
125 } else if (framesMixed > 0) {
126 // Mark beginning of data flow after a start.
127 streamShared->setFlowing(true);
128 }
129 clientFramesRead = fifo->getReadCounter();
130 }
131 }
132
133 if (clientFramesRead > 0) {
134 // This timestamp represents the completion of data being read out of the
135 // client buffer. It is sent to the client and used in the timing model
136 // to decide when the client has room to write more data.
137 Timestamp timestamp(clientFramesRead, AudioClock::getNanoseconds());
138 streamShared->markTransferTime(timestamp);
139 }
140
141 index++; // just used for labelling tracks in systrace
142 }
143 }
144
145 // Write mixer output to stream using a blocking write.
146 result = getStreamInternal()->write(mMixer.getOutputBuffer(),
147 getFramesPerBurst(), timeoutNanos);
148 if (result == AAUDIO_ERROR_DISCONNECTED) {
149 ALOGD("%s() write() returned AAUDIO_ERROR_DISCONNECTED", __func__);
150 AAudioServiceEndpointShared::handleDisconnectRegisteredStreamsAsync();
151 break;
152 } else if (result != getFramesPerBurst()) {
153 ALOGW("callbackLoop() wrote %d / %d",
154 result, getFramesPerBurst());
155 break;
156 }
157 }
158
159 ALOGD("%s() exiting, enabled = %d, state = %d, result = %d <<<<<<<<<<<<< MIXER",
160 __func__, mCallbackEnabled.load(), getStreamInternal()->getState(), result);
161 return NULL; // TODO review
162 }
163