blob: 0d169e18bf87f113496e1c0b51b5b5d89c7af069 [file] [log] [blame]
Phil Burk204a1632017-01-03 17:23:43 -08001/*
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#define LOG_TAG "OboeAudio"
18//#define LOG_NDEBUG 0
19#include <utils/Log.h>
20
21#include <stdint.h>
22#include <assert.h>
23
24#include <binder/IServiceManager.h>
25
26#include <oboe/OboeAudio.h>
27
28#include "AudioClock.h"
29#include "AudioEndpointParcelable.h"
30#include "binding/OboeStreamRequest.h"
31#include "binding/OboeStreamConfiguration.h"
32#include "binding/IOboeAudioService.h"
33#include "binding/OboeServiceMessage.h"
34
35#include "AudioStreamInternal.h"
36
37#define LOG_TIMESTAMPS 0
38
39using android::String16;
40using android::IServiceManager;
41using android::defaultServiceManager;
42using android::interface_cast;
43
44using namespace oboe;
45
46// Helper function to get access to the "OboeAudioService" service.
47static sp<IOboeAudioService> getOboeAudioService() {
48 sp<IServiceManager> sm = defaultServiceManager();
49 sp<IBinder> binder = sm->getService(String16("OboeAudioService"));
50 // TODO: If the "OboeHack" service is not running, getService times out and binder == 0.
51 sp<IOboeAudioService> service = interface_cast<IOboeAudioService>(binder);
52 return service;
53}
54
55AudioStreamInternal::AudioStreamInternal()
56 : AudioStream()
57 , mClockModel()
58 , mAudioEndpoint()
59 , mServiceStreamHandle(OBOE_HANDLE_INVALID)
60 , mFramesPerBurst(16)
61{
62 // TODO protect against mService being NULL;
63 // TODO Model access to the service on frameworks/av/media/libaudioclient/AudioSystem.cpp
64 mService = getOboeAudioService();
65}
66
67AudioStreamInternal::~AudioStreamInternal() {
68}
69
70oboe_result_t AudioStreamInternal::open(const AudioStreamBuilder &builder) {
71
72 oboe_result_t result = OBOE_OK;
73 OboeStreamRequest request;
74 OboeStreamConfiguration configuration;
75
76 result = AudioStream::open(builder);
77 if (result < 0) {
78 return result;
79 }
80
81 // Build the request.
82 request.setUserId(getuid());
83 request.setProcessId(getpid());
84 request.getConfiguration().setDeviceId(getDeviceId());
85 request.getConfiguration().setSampleRate(getSampleRate());
86 request.getConfiguration().setSamplesPerFrame(getSamplesPerFrame());
87 request.getConfiguration().setAudioFormat(getFormat());
88 request.dump();
89
90 mServiceStreamHandle = mService->openStream(request, configuration);
91 ALOGD("AudioStreamInternal.open(): openStream returned mServiceStreamHandle = 0x%08X",
92 (unsigned int)mServiceStreamHandle);
93 if (mServiceStreamHandle < 0) {
94 result = mServiceStreamHandle;
95 ALOGE("AudioStreamInternal.open(): acquireRealtimeStream oboe_result_t = 0x%08X", result);
96 } else {
97 result = configuration.validate();
98 if (result != OBOE_OK) {
99 close();
100 return result;
101 }
102 // Save results of the open.
103 setSampleRate(configuration.getSampleRate());
104 setSamplesPerFrame(configuration.getSamplesPerFrame());
105 setFormat(configuration.getAudioFormat());
106
107 oboe::AudioEndpointParcelable parcelable;
108 result = mService->getStreamDescription(mServiceStreamHandle, parcelable);
109 if (result != OBOE_OK) {
110 ALOGE("AudioStreamInternal.open(): getStreamDescriptor returns %d", result);
111 mService->closeStream(mServiceStreamHandle);
112 return result;
113 }
114 // resolve parcelable into a descriptor
115 parcelable.resolve(&mEndpointDescriptor);
116
117 // Configure endpoint based on descriptor.
118 mAudioEndpoint.configure(&mEndpointDescriptor);
119
120
121 mFramesPerBurst = mEndpointDescriptor.downDataQueueDescriptor.framesPerBurst;
122 assert(mFramesPerBurst >= 16);
123 assert(mEndpointDescriptor.downDataQueueDescriptor.capacityInFrames < 10 * 1024);
124
125 mClockModel.setSampleRate(getSampleRate());
126 mClockModel.setFramesPerBurst(mFramesPerBurst);
127
128 setState(OBOE_STREAM_STATE_OPEN);
129 }
130 return result;
131}
132
133oboe_result_t AudioStreamInternal::close() {
134 ALOGD("AudioStreamInternal.close(): mServiceStreamHandle = 0x%08X", mServiceStreamHandle);
135 if (mServiceStreamHandle != OBOE_HANDLE_INVALID) {
136 mService->closeStream(mServiceStreamHandle);
137 mServiceStreamHandle = OBOE_HANDLE_INVALID;
138 return OBOE_OK;
139 } else {
140 return OBOE_ERROR_INVALID_STATE;
141 }
142}
143
144oboe_result_t AudioStreamInternal::requestStart()
145{
146 oboe_nanoseconds_t startTime;
147 ALOGD("AudioStreamInternal(): start()");
148 if (mServiceStreamHandle == OBOE_HANDLE_INVALID) {
149 return OBOE_ERROR_INVALID_STATE;
150 }
151 startTime = Oboe_getNanoseconds(OBOE_CLOCK_MONOTONIC);
152 mClockModel.start(startTime);
153 processTimestamp(0, startTime);
154 setState(OBOE_STREAM_STATE_STARTING);
155 return mService->startStream(mServiceStreamHandle);
156}
157
158oboe_result_t AudioStreamInternal::requestPause()
159{
160 ALOGD("AudioStreamInternal(): pause()");
161 if (mServiceStreamHandle == OBOE_HANDLE_INVALID) {
162 return OBOE_ERROR_INVALID_STATE;
163 }
164 mClockModel.stop(Oboe_getNanoseconds(OBOE_CLOCK_MONOTONIC));
165 setState(OBOE_STREAM_STATE_PAUSING);
166 return mService->pauseStream(mServiceStreamHandle);
167}
168
169oboe_result_t AudioStreamInternal::requestFlush() {
170 ALOGD("AudioStreamInternal(): flush()");
171 if (mServiceStreamHandle == OBOE_HANDLE_INVALID) {
172 return OBOE_ERROR_INVALID_STATE;
173 }
174 setState(OBOE_STREAM_STATE_FLUSHING);
175 return mService->flushStream(mServiceStreamHandle);
176}
177
178void AudioStreamInternal::onFlushFromServer() {
179 ALOGD("AudioStreamInternal(): onFlushFromServer()");
180 oboe_position_frames_t readCounter = mAudioEndpoint.getDownDataReadCounter();
181 oboe_position_frames_t writeCounter = mAudioEndpoint.getDownDataWriteCounter();
182 // Bump offset so caller does not see the retrograde motion in getFramesRead().
183 oboe_position_frames_t framesFlushed = writeCounter - readCounter;
184 mFramesOffsetFromService += framesFlushed;
185 // Flush written frames by forcing writeCounter to readCounter.
186 // This is because we cannot move the read counter in the hardware.
187 mAudioEndpoint.setDownDataWriteCounter(readCounter);
188}
189
190oboe_result_t AudioStreamInternal::requestStop()
191{
192 // TODO better implementation of requestStop()
193 oboe_result_t result = requestPause();
194 if (result == OBOE_OK) {
195 oboe_stream_state_t state;
196 result = waitForStateChange(OBOE_STREAM_STATE_PAUSING,
197 &state,
198 500 * OBOE_NANOS_PER_MILLISECOND);// TODO temporary code
199 if (result == OBOE_OK) {
200 result = requestFlush();
201 }
202 }
203 return result;
204}
205
206oboe_result_t AudioStreamInternal::registerThread() {
207 ALOGD("AudioStreamInternal(): registerThread()");
208 if (mServiceStreamHandle == OBOE_HANDLE_INVALID) {
209 return OBOE_ERROR_INVALID_STATE;
210 }
211 return mService->registerAudioThread(mServiceStreamHandle,
212 gettid(),
213 getPeriodNanoseconds());
214}
215
216oboe_result_t AudioStreamInternal::unregisterThread() {
217 ALOGD("AudioStreamInternal(): unregisterThread()");
218 if (mServiceStreamHandle == OBOE_HANDLE_INVALID) {
219 return OBOE_ERROR_INVALID_STATE;
220 }
221 return mService->unregisterAudioThread(mServiceStreamHandle, gettid());
222}
223
224// TODO use oboe_clockid_t all the way down to AudioClock
225oboe_result_t AudioStreamInternal::getTimestamp(clockid_t clockId,
226 oboe_position_frames_t *framePosition,
227 oboe_nanoseconds_t *timeNanoseconds) {
228// TODO implement using real HAL
229 oboe_nanoseconds_t time = AudioClock::getNanoseconds();
230 *framePosition = mClockModel.convertTimeToPosition(time);
231 *timeNanoseconds = time + (10 * OBOE_NANOS_PER_MILLISECOND); // Fake hardware delay
232 return OBOE_OK;
233}
234
235oboe_result_t AudioStreamInternal::updateState() {
236 return processCommands();
237}
238
239#if LOG_TIMESTAMPS
240static void AudioStreamInternal_LogTimestamp(OboeServiceMessage &command) {
241 static int64_t oldPosition = 0;
242 static oboe_nanoseconds_t oldTime = 0;
243 int64_t framePosition = command.timestamp.position;
244 oboe_nanoseconds_t nanoTime = command.timestamp.timestamp;
245 ALOGD("AudioStreamInternal() timestamp says framePosition = %08lld at nanoTime %llu",
246 (long long) framePosition,
247 (long long) nanoTime);
248 int64_t nanosDelta = nanoTime - oldTime;
249 if (nanosDelta > 0 && oldTime > 0) {
250 int64_t framesDelta = framePosition - oldPosition;
251 int64_t rate = (framesDelta * OBOE_NANOS_PER_SECOND) / nanosDelta;
252 ALOGD("AudioStreamInternal() - framesDelta = %08lld", (long long) framesDelta);
253 ALOGD("AudioStreamInternal() - nanosDelta = %08lld", (long long) nanosDelta);
254 ALOGD("AudioStreamInternal() - measured rate = %llu", (unsigned long long) rate);
255 }
256 oldPosition = framePosition;
257 oldTime = nanoTime;
258}
259#endif
260
261oboe_result_t AudioStreamInternal::onTimestampFromServer(OboeServiceMessage *message) {
262 oboe_position_frames_t framePosition = 0;
263#if LOG_TIMESTAMPS
264 AudioStreamInternal_LogTimestamp(command);
265#endif
266 framePosition = message->timestamp.position;
267 processTimestamp(framePosition, message->timestamp.timestamp);
268 return OBOE_OK;
269}
270
271oboe_result_t AudioStreamInternal::onEventFromServer(OboeServiceMessage *message) {
272 oboe_result_t result = OBOE_OK;
273 ALOGD("processCommands() got event %d", message->event.event);
274 switch (message->event.event) {
275 case OBOE_SERVICE_EVENT_STARTED:
276 ALOGD("processCommands() got OBOE_SERVICE_EVENT_STARTED");
277 setState(OBOE_STREAM_STATE_STARTED);
278 break;
279 case OBOE_SERVICE_EVENT_PAUSED:
280 ALOGD("processCommands() got OBOE_SERVICE_EVENT_PAUSED");
281 setState(OBOE_STREAM_STATE_PAUSED);
282 break;
283 case OBOE_SERVICE_EVENT_FLUSHED:
284 ALOGD("processCommands() got OBOE_SERVICE_EVENT_FLUSHED");
285 setState(OBOE_STREAM_STATE_FLUSHED);
286 onFlushFromServer();
287 break;
288 case OBOE_SERVICE_EVENT_CLOSED:
289 ALOGD("processCommands() got OBOE_SERVICE_EVENT_CLOSED");
290 setState(OBOE_STREAM_STATE_CLOSED);
291 break;
292 case OBOE_SERVICE_EVENT_DISCONNECTED:
293 result = OBOE_ERROR_DISCONNECTED;
294 ALOGW("WARNING - processCommands() OBOE_SERVICE_EVENT_DISCONNECTED");
295 break;
296 default:
297 ALOGW("WARNING - processCommands() Unrecognized event = %d",
298 (int) message->event.event);
299 break;
300 }
301 return result;
302}
303
304// Process all the commands coming from the server.
305oboe_result_t AudioStreamInternal::processCommands() {
306 oboe_result_t result = OBOE_OK;
307
308 // Let the service run in case it is a fake service simulator.
309 mService->tickle(); // TODO use real service thread
310
311 while (result == OBOE_OK) {
312 OboeServiceMessage message;
313 if (mAudioEndpoint.readUpCommand(&message) != 1) {
314 break; // no command this time, no problem
315 }
316 switch (message.what) {
317 case OboeServiceMessage::code::TIMESTAMP:
318 result = onTimestampFromServer(&message);
319 break;
320
321 case OboeServiceMessage::code::EVENT:
322 result = onEventFromServer(&message);
323 break;
324
325 default:
326 ALOGW("WARNING - AudioStreamInternal::processCommands() Unrecognized what = %d",
327 (int) message.what);
328 result = OBOE_ERROR_UNEXPECTED_VALUE;
329 break;
330 }
331 }
332 return result;
333}
334
335// Write the data, block if needed and timeoutMillis > 0
336oboe_result_t AudioStreamInternal::write(const void *buffer, int32_t numFrames,
337 oboe_nanoseconds_t timeoutNanoseconds)
338{
339 oboe_result_t result = OBOE_OK;
340 uint8_t* source = (uint8_t*)buffer;
341 oboe_nanoseconds_t currentTimeNanos = AudioClock::getNanoseconds();
342 oboe_nanoseconds_t deadlineNanos = currentTimeNanos + timeoutNanoseconds;
343 int32_t framesLeft = numFrames;
344// ALOGD("AudioStreamInternal::write(%p, %d) at time %08llu , mState = %d ------------------",
345// buffer, numFrames, (unsigned long long) currentTimeNanos, mState);
346
347 // Write until all the data has been written or until a timeout occurs.
348 while (framesLeft > 0) {
349 // The call to writeNow() will not block. It will just write as much as it can.
350 oboe_nanoseconds_t wakeTimeNanos = 0;
351 oboe_result_t framesWritten = writeNow(source, framesLeft,
352 currentTimeNanos, &wakeTimeNanos);
353// ALOGD("AudioStreamInternal::write() writeNow() framesLeft = %d --> framesWritten = %d", framesLeft, framesWritten);
354 if (framesWritten < 0) {
355 result = framesWritten;
356 break;
357 }
358 framesLeft -= (int32_t) framesWritten;
359 source += framesWritten * getBytesPerFrame();
360
361 // Should we block?
362 if (timeoutNanoseconds == 0) {
363 break; // don't block
364 } else if (framesLeft > 0) {
365 //ALOGD("AudioStreamInternal:: original wakeTimeNanos %lld", (long long) wakeTimeNanos);
366 // clip the wake time to something reasonable
367 if (wakeTimeNanos < currentTimeNanos) {
368 wakeTimeNanos = currentTimeNanos;
369 }
370 if (wakeTimeNanos > deadlineNanos) {
371 // If we time out, just return the framesWritten so far.
372 ALOGE("AudioStreamInternal::write(): timed out after %lld nanos", (long long) timeoutNanoseconds);
373 break;
374 }
375
376 //ALOGD("AudioStreamInternal:: sleep until %lld, dur = %lld", (long long) wakeTimeNanos,
377 // (long long) (wakeTimeNanos - currentTimeNanos));
378 AudioClock::sleepForNanos(wakeTimeNanos - currentTimeNanos);
379 currentTimeNanos = AudioClock::getNanoseconds();
380 }
381 }
382
383 // return error or framesWritten
384 return (result < 0) ? result : numFrames - framesLeft;
385}
386
387// Write as much data as we can without blocking.
388oboe_result_t AudioStreamInternal::writeNow(const void *buffer, int32_t numFrames,
389 oboe_nanoseconds_t currentNanoTime, oboe_nanoseconds_t *wakeTimePtr) {
390 {
391 oboe_result_t result = processCommands();
392 if (result != OBOE_OK) {
393 return result;
394 }
395 }
396
397 if (mAudioEndpoint.isOutputFreeRunning()) {
398 // Update data queue based on the timing model.
399 int64_t estimatedReadCounter = mClockModel.convertTimeToPosition(currentNanoTime);
400 mAudioEndpoint.setDownDataReadCounter(estimatedReadCounter);
401 // If the read index passed the write index then consider it an underrun.
402 if (mAudioEndpoint.getFullFramesAvailable() < 0) {
403 mXRunCount++;
404 }
405 }
406 // TODO else query from endpoint cuz set by actual reader, maybe
407
408 // Write some data to the buffer.
409 int32_t framesWritten = mAudioEndpoint.writeDataNow(buffer, numFrames);
410 if (framesWritten > 0) {
411 incrementFramesWritten(framesWritten);
412 }
413 //ALOGD("AudioStreamInternal::writeNow() - tried to write %d frames, wrote %d",
414 // numFrames, framesWritten);
415
416 // Calculate an ideal time to wake up.
417 if (wakeTimePtr != nullptr && framesWritten >= 0) {
418 // By default wake up a few milliseconds from now. // TODO review
419 oboe_nanoseconds_t wakeTime = currentNanoTime + (2 * OBOE_NANOS_PER_MILLISECOND);
420 switch (getState()) {
421 case OBOE_STREAM_STATE_OPEN:
422 case OBOE_STREAM_STATE_STARTING:
423 if (framesWritten != 0) {
424 // Don't wait to write more data. Just prime the buffer.
425 wakeTime = currentNanoTime;
426 }
427 break;
428 case OBOE_STREAM_STATE_STARTED: // When do we expect the next read burst to occur?
429 {
430 uint32_t burstSize = mFramesPerBurst;
431 if (burstSize < 32) {
432 burstSize = 32; // TODO review
433 }
434
435 uint64_t nextReadPosition = mAudioEndpoint.getDownDataReadCounter() + burstSize;
436 wakeTime = mClockModel.convertPositionToTime(nextReadPosition);
437 }
438 break;
439 default:
440 break;
441 }
442 *wakeTimePtr = wakeTime;
443
444 }
445// ALOGD("AudioStreamInternal::writeNow finished: now = %llu, read# = %llu, wrote# = %llu",
446// (unsigned long long)currentNanoTime,
447// (unsigned long long)mAudioEndpoint.getDownDataReadCounter(),
448// (unsigned long long)mAudioEndpoint.getDownDataWriteCounter());
449 return framesWritten;
450}
451
452oboe_result_t AudioStreamInternal::waitForStateChange(oboe_stream_state_t currentState,
453 oboe_stream_state_t *nextState,
454 oboe_nanoseconds_t timeoutNanoseconds)
455
456{
457 oboe_result_t result = processCommands();
458// ALOGD("AudioStreamInternal::waitForStateChange() - processCommands() returned %d", result);
459 if (result != OBOE_OK) {
460 return result;
461 }
462 // TODO replace this polling with a timed sleep on a futex on the message queue
463 int32_t durationNanos = 5 * OBOE_NANOS_PER_MILLISECOND;
464 oboe_stream_state_t state = getState();
465// ALOGD("AudioStreamInternal::waitForStateChange() - state = %d", state);
466 while (state == currentState && timeoutNanoseconds > 0) {
467 // TODO use futex from service message queue
468 if (durationNanos > timeoutNanoseconds) {
469 durationNanos = timeoutNanoseconds;
470 }
471 AudioClock::sleepForNanos(durationNanos);
472 timeoutNanoseconds -= durationNanos;
473
474 result = processCommands();
475 if (result != OBOE_OK) {
476 return result;
477 }
478
479 state = getState();
480// ALOGD("AudioStreamInternal::waitForStateChange() - state = %d", state);
481 }
482 if (nextState != nullptr) {
483 *nextState = state;
484 }
485 return (state == currentState) ? OBOE_ERROR_TIMEOUT : OBOE_OK;
486}
487
488
489void AudioStreamInternal::processTimestamp(uint64_t position, oboe_nanoseconds_t time) {
490 mClockModel.processTimestamp( position, time);
491}
492
493oboe_result_t AudioStreamInternal::setBufferSize(oboe_size_frames_t requestedFrames,
494 oboe_size_frames_t *actualFrames) {
495 return mAudioEndpoint.setBufferSizeInFrames(requestedFrames, actualFrames);
496}
497
498oboe_size_frames_t AudioStreamInternal::getBufferSize() const
499{
500 return mAudioEndpoint.getBufferSizeInFrames();
501}
502
503oboe_size_frames_t AudioStreamInternal::getBufferCapacity() const
504{
505 return mAudioEndpoint.getBufferCapacityInFrames();
506}
507
508oboe_size_frames_t AudioStreamInternal::getFramesPerBurst() const
509{
510 return mEndpointDescriptor.downDataQueueDescriptor.framesPerBurst;
511}
512
513oboe_position_frames_t AudioStreamInternal::getFramesRead()
514{
515 oboe_position_frames_t framesRead =
516 mClockModel.convertTimeToPosition(AudioClock::getNanoseconds())
517 + mFramesOffsetFromService;
518 // Prevent retrograde motion.
519 if (framesRead < mLastFramesRead) {
520 framesRead = mLastFramesRead;
521 } else {
522 mLastFramesRead = framesRead;
523 }
524 ALOGD("AudioStreamInternal::getFramesRead() returns %lld", (long long)framesRead);
525 return framesRead;
526}
527
528// TODO implement getTimestamp