1 /*
2 **
3 ** Copyright 2014, The Android Open Source Project
4 **
5 ** Licensed under the Apache License, Version 2.0 (the "License");
6 ** you may not use this file except in compliance with the License.
7 ** You may obtain a copy of the License at
8 **
9 ** http://www.apache.org/licenses/LICENSE-2.0
10 **
11 ** Unless required by applicable law or agreed to in writing, software
12 ** distributed under the License is distributed on an "AS IS" BASIS,
13 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 ** See the License for the specific language governing permissions and
15 ** limitations under the License.
16 */
17
18
19 #define LOG_TAG "AudioFlinger::PatchPanel"
20 //#define LOG_NDEBUG 0
21
22 #include "Configuration.h"
23 #include <utils/Log.h>
24 #include <audio_utils/primitives.h>
25
26 #include "AudioFlinger.h"
27 #include <media/AudioParameter.h>
28 #include <media/DeviceDescriptorBase.h>
29 #include <media/PatchBuilder.h>
30 #include <mediautils/ServiceUtilities.h>
31
32 // ----------------------------------------------------------------------------
33
34 // Note: the following macro is used for extremely verbose logging message. In
35 // order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
36 // 0; but one side effect of this is to turn all LOGV's as well. Some messages
37 // are so verbose that we want to suppress them even when we have ALOG_ASSERT
38 // turned on. Do not uncomment the #def below unless you really know what you
39 // are doing and want to see all of the extremely verbose messages.
40 //#define VERY_VERY_VERBOSE_LOGGING
41 #ifdef VERY_VERY_VERBOSE_LOGGING
42 #define ALOGVV ALOGV
43 #else
44 #define ALOGVV(a...) do { } while(0)
45 #endif
46
47 namespace android {
48
49 /* List connected audio ports and their attributes */
listAudioPorts(unsigned int * num_ports,struct audio_port * ports)50 status_t AudioFlinger::listAudioPorts(unsigned int *num_ports,
51 struct audio_port *ports)
52 {
53 Mutex::Autolock _l(mLock);
54 return mPatchPanel.listAudioPorts(num_ports, ports);
55 }
56
57 /* Get supported attributes for a given audio port */
getAudioPort(struct audio_port * port)58 status_t AudioFlinger::getAudioPort(struct audio_port *port)
59 {
60 Mutex::Autolock _l(mLock);
61 return mPatchPanel.getAudioPort(port);
62 }
63
64 /* Connect a patch between several source and sink ports */
createAudioPatch(const struct audio_patch * patch,audio_patch_handle_t * handle)65 status_t AudioFlinger::createAudioPatch(const struct audio_patch *patch,
66 audio_patch_handle_t *handle)
67 {
68 Mutex::Autolock _l(mLock);
69 return mPatchPanel.createAudioPatch(patch, handle);
70 }
71
72 /* Disconnect a patch */
releaseAudioPatch(audio_patch_handle_t handle)73 status_t AudioFlinger::releaseAudioPatch(audio_patch_handle_t handle)
74 {
75 Mutex::Autolock _l(mLock);
76 return mPatchPanel.releaseAudioPatch(handle);
77 }
78
79 /* List connected audio ports and they attributes */
listAudioPatches(unsigned int * num_patches,struct audio_patch * patches)80 status_t AudioFlinger::listAudioPatches(unsigned int *num_patches,
81 struct audio_patch *patches)
82 {
83 Mutex::Autolock _l(mLock);
84 return mPatchPanel.listAudioPatches(num_patches, patches);
85 }
86
getLatencyMs_l(double * latencyMs) const87 status_t AudioFlinger::PatchPanel::SoftwarePatch::getLatencyMs_l(double *latencyMs) const
88 {
89 const auto& iter = mPatchPanel.mPatches.find(mPatchHandle);
90 if (iter != mPatchPanel.mPatches.end()) {
91 return iter->second.getLatencyMs(latencyMs);
92 } else {
93 return BAD_VALUE;
94 }
95 }
96
97 /* List connected audio ports and their attributes */
listAudioPorts(unsigned int * num_ports __unused,struct audio_port * ports __unused)98 status_t AudioFlinger::PatchPanel::listAudioPorts(unsigned int *num_ports __unused,
99 struct audio_port *ports __unused)
100 {
101 ALOGV(__func__);
102 return NO_ERROR;
103 }
104
105 /* Get supported attributes for a given audio port */
getAudioPort(struct audio_port * port __unused)106 status_t AudioFlinger::PatchPanel::getAudioPort(struct audio_port *port __unused)
107 {
108 ALOGV(__func__);
109 return NO_ERROR;
110 }
111
112 /* Connect a patch between several source and sink ports */
createAudioPatch(const struct audio_patch * patch,audio_patch_handle_t * handle)113 status_t AudioFlinger::PatchPanel::createAudioPatch(const struct audio_patch *patch,
114 audio_patch_handle_t *handle)
115 {
116 if (handle == NULL || patch == NULL) {
117 return BAD_VALUE;
118 }
119 ALOGV("%s() num_sources %d num_sinks %d handle %d",
120 __func__, patch->num_sources, patch->num_sinks, *handle);
121 status_t status = NO_ERROR;
122 audio_patch_handle_t halHandle = AUDIO_PATCH_HANDLE_NONE;
123
124 if (!audio_patch_is_valid(patch) || (patch->num_sinks == 0 && patch->num_sources != 2)) {
125 return BAD_VALUE;
126 }
127 // limit number of sources to 1 for now or 2 sources for special cross hw module case.
128 // only the audio policy manager can request a patch creation with 2 sources.
129 if (patch->num_sources > 2) {
130 return INVALID_OPERATION;
131 }
132
133 if (*handle != AUDIO_PATCH_HANDLE_NONE) {
134 auto iter = mPatches.find(*handle);
135 if (iter != mPatches.end()) {
136 ALOGV("%s() removing patch handle %d", __func__, *handle);
137 Patch &removedPatch = iter->second;
138 // free resources owned by the removed patch if applicable
139 // 1) if a software patch is present, release the playback and capture threads and
140 // tracks created. This will also release the corresponding audio HAL patches
141 if (removedPatch.isSoftware()) {
142 removedPatch.clearConnections(this);
143 }
144 // 2) if the new patch and old patch source or sink are devices from different
145 // hw modules, clear the audio HAL patches now because they will not be updated
146 // by call to create_audio_patch() below which will happen on a different HW module
147 if (removedPatch.mHalHandle != AUDIO_PATCH_HANDLE_NONE) {
148 audio_module_handle_t hwModule = AUDIO_MODULE_HANDLE_NONE;
149 const struct audio_patch &oldPatch = removedPatch.mAudioPatch;
150 if (oldPatch.sources[0].type == AUDIO_PORT_TYPE_DEVICE &&
151 (patch->sources[0].type != AUDIO_PORT_TYPE_DEVICE ||
152 oldPatch.sources[0].ext.device.hw_module !=
153 patch->sources[0].ext.device.hw_module)) {
154 hwModule = oldPatch.sources[0].ext.device.hw_module;
155 } else if (patch->num_sinks == 0 ||
156 (oldPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE &&
157 (patch->sinks[0].type != AUDIO_PORT_TYPE_DEVICE ||
158 oldPatch.sinks[0].ext.device.hw_module !=
159 patch->sinks[0].ext.device.hw_module))) {
160 // Note on (patch->num_sinks == 0): this situation should not happen as
161 // these special patches are only created by the policy manager but just
162 // in case, systematically clear the HAL patch.
163 // Note that removedPatch.mAudioPatch.num_sinks cannot be 0 here because
164 // removedPatch.mHalHandle would be AUDIO_PATCH_HANDLE_NONE in this case.
165 hwModule = oldPatch.sinks[0].ext.device.hw_module;
166 }
167 sp<DeviceHalInterface> hwDevice = findHwDeviceByModule(hwModule);
168 if (hwDevice != 0) {
169 hwDevice->releaseAudioPatch(removedPatch.mHalHandle);
170 }
171 halHandle = removedPatch.mHalHandle;
172 }
173 erasePatch(*handle);
174 }
175 }
176
177 Patch newPatch{*patch};
178 audio_module_handle_t insertedModule = AUDIO_MODULE_HANDLE_NONE;
179
180 switch (patch->sources[0].type) {
181 case AUDIO_PORT_TYPE_DEVICE: {
182 audio_module_handle_t srcModule = patch->sources[0].ext.device.hw_module;
183 AudioHwDevice *audioHwDevice = findAudioHwDeviceByModule(srcModule);
184 if (!audioHwDevice) {
185 status = BAD_VALUE;
186 goto exit;
187 }
188 for (unsigned int i = 0; i < patch->num_sinks; i++) {
189 // support only one sink if connection to a mix or across HW modules
190 if ((patch->sinks[i].type == AUDIO_PORT_TYPE_MIX ||
191 (patch->sinks[i].type == AUDIO_PORT_TYPE_DEVICE &&
192 patch->sinks[i].ext.device.hw_module != srcModule)) &&
193 patch->num_sinks > 1) {
194 ALOGW("%s() multiple sinks for mix or across modules not supported", __func__);
195 status = INVALID_OPERATION;
196 goto exit;
197 }
198 // reject connection to different sink types
199 if (patch->sinks[i].type != patch->sinks[0].type) {
200 ALOGW("%s() different sink types in same patch not supported", __func__);
201 status = BAD_VALUE;
202 goto exit;
203 }
204 }
205
206 // manage patches requiring a software bridge
207 // - special patch request with 2 sources (reuse one existing output mix) OR
208 // - Device to device AND
209 // - source HW module != destination HW module OR
210 // - audio HAL does not support audio patches creation
211 if ((patch->num_sources == 2) ||
212 ((patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) &&
213 ((patch->sinks[0].ext.device.hw_module != srcModule) ||
214 !audioHwDevice->supportsAudioPatches()))) {
215 audio_devices_t outputDevice = patch->sinks[0].ext.device.type;
216 String8 outputDeviceAddress = String8(patch->sinks[0].ext.device.address);
217 if (patch->num_sources == 2) {
218 if (patch->sources[1].type != AUDIO_PORT_TYPE_MIX ||
219 (patch->num_sinks != 0 && patch->sinks[0].ext.device.hw_module !=
220 patch->sources[1].ext.mix.hw_module)) {
221 ALOGW("%s() invalid source combination", __func__);
222 status = INVALID_OPERATION;
223 goto exit;
224 }
225
226 sp<ThreadBase> thread =
227 mAudioFlinger.checkPlaybackThread_l(patch->sources[1].ext.mix.handle);
228 if (thread == 0) {
229 ALOGW("%s() cannot get playback thread", __func__);
230 status = INVALID_OPERATION;
231 goto exit;
232 }
233 // existing playback thread is reused, so it is not closed when patch is cleared
234 newPatch.mPlayback.setThread(
235 reinterpret_cast<PlaybackThread*>(thread.get()), false /*closeThread*/);
236 } else {
237 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
238 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
239 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
240 if (patch->sinks[0].config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
241 config.sample_rate = patch->sinks[0].sample_rate;
242 }
243 if (patch->sinks[0].config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
244 config.channel_mask = patch->sinks[0].channel_mask;
245 }
246 if (patch->sinks[0].config_mask & AUDIO_PORT_CONFIG_FORMAT) {
247 config.format = patch->sinks[0].format;
248 }
249 if (patch->sinks[0].config_mask & AUDIO_PORT_CONFIG_FLAGS) {
250 flags = patch->sinks[0].flags.output;
251 }
252 sp<ThreadBase> thread = mAudioFlinger.openOutput_l(
253 patch->sinks[0].ext.device.hw_module,
254 &output,
255 &config,
256 outputDevice,
257 outputDeviceAddress,
258 flags);
259 ALOGV("mAudioFlinger.openOutput_l() returned %p", thread.get());
260 if (thread == 0) {
261 status = NO_MEMORY;
262 goto exit;
263 }
264 newPatch.mPlayback.setThread(reinterpret_cast<PlaybackThread*>(thread.get()));
265 }
266 audio_devices_t device = patch->sources[0].ext.device.type;
267 String8 address = String8(patch->sources[0].ext.device.address);
268 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
269 // open input stream with source device audio properties if provided or
270 // default to peer output stream properties otherwise.
271 if (patch->sources[0].config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
272 config.sample_rate = patch->sources[0].sample_rate;
273 } else {
274 config.sample_rate = newPatch.mPlayback.thread()->sampleRate();
275 }
276 if (patch->sources[0].config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
277 config.channel_mask = patch->sources[0].channel_mask;
278 } else {
279 config.channel_mask = audio_channel_in_mask_from_count(
280 newPatch.mPlayback.thread()->channelCount());
281 }
282 if (patch->sources[0].config_mask & AUDIO_PORT_CONFIG_FORMAT) {
283 config.format = patch->sources[0].format;
284 } else {
285 config.format = newPatch.mPlayback.thread()->format();
286 }
287 audio_input_flags_t flags =
288 patch->sources[0].config_mask & AUDIO_PORT_CONFIG_FLAGS ?
289 patch->sources[0].flags.input : AUDIO_INPUT_FLAG_NONE;
290 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
291 sp<ThreadBase> thread = mAudioFlinger.openInput_l(srcModule,
292 &input,
293 &config,
294 device,
295 address,
296 AUDIO_SOURCE_MIC,
297 flags,
298 outputDevice,
299 outputDeviceAddress);
300 ALOGV("mAudioFlinger.openInput_l() returned %p inChannelMask %08x",
301 thread.get(), config.channel_mask);
302 if (thread == 0) {
303 status = NO_MEMORY;
304 goto exit;
305 }
306 newPatch.mRecord.setThread(reinterpret_cast<RecordThread*>(thread.get()));
307 status = newPatch.createConnections(this);
308 if (status != NO_ERROR) {
309 goto exit;
310 }
311 if (audioHwDevice->isInsert()) {
312 insertedModule = audioHwDevice->handle();
313 }
314 } else {
315 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
316 sp<ThreadBase> thread = mAudioFlinger.checkRecordThread_l(
317 patch->sinks[0].ext.mix.handle);
318 if (thread == 0) {
319 thread = mAudioFlinger.checkMmapThread_l(patch->sinks[0].ext.mix.handle);
320 if (thread == 0) {
321 ALOGW("%s() bad capture I/O handle %d",
322 __func__, patch->sinks[0].ext.mix.handle);
323 status = BAD_VALUE;
324 goto exit;
325 }
326 }
327 status = thread->sendCreateAudioPatchConfigEvent(patch, &halHandle);
328 if (status == NO_ERROR) {
329 newPatch.setThread(thread);
330 }
331
332 // remove stale audio patch with same input as sink if any
333 for (auto& iter : mPatches) {
334 if (iter.second.mAudioPatch.sinks[0].ext.mix.handle == thread->id()) {
335 erasePatch(iter.first);
336 break;
337 }
338 }
339 } else {
340 sp<DeviceHalInterface> hwDevice = audioHwDevice->hwDevice();
341 status = hwDevice->createAudioPatch(patch->num_sources,
342 patch->sources,
343 patch->num_sinks,
344 patch->sinks,
345 &halHandle);
346 if (status == INVALID_OPERATION) goto exit;
347 }
348 }
349 } break;
350 case AUDIO_PORT_TYPE_MIX: {
351 audio_module_handle_t srcModule = patch->sources[0].ext.mix.hw_module;
352 ssize_t index = mAudioFlinger.mAudioHwDevs.indexOfKey(srcModule);
353 if (index < 0) {
354 ALOGW("%s() bad src hw module %d", __func__, srcModule);
355 status = BAD_VALUE;
356 goto exit;
357 }
358 // limit to connections between devices and output streams
359 DeviceDescriptorBaseVector devices;
360 for (unsigned int i = 0; i < patch->num_sinks; i++) {
361 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
362 ALOGW("%s() invalid sink type %d for mix source",
363 __func__, patch->sinks[i].type);
364 status = BAD_VALUE;
365 goto exit;
366 }
367 // limit to connections between sinks and sources on same HW module
368 if (patch->sinks[i].ext.device.hw_module != srcModule) {
369 status = BAD_VALUE;
370 goto exit;
371 }
372 sp<DeviceDescriptorBase> device = new DeviceDescriptorBase(
373 patch->sinks[i].ext.device.type);
374 device->setAddress(patch->sinks[i].ext.device.address);
375 device->applyAudioPortConfig(&patch->sinks[i]);
376 devices.push_back(device);
377 }
378 sp<ThreadBase> thread =
379 mAudioFlinger.checkPlaybackThread_l(patch->sources[0].ext.mix.handle);
380 if (thread == 0) {
381 thread = mAudioFlinger.checkMmapThread_l(patch->sources[0].ext.mix.handle);
382 if (thread == 0) {
383 ALOGW("%s() bad playback I/O handle %d",
384 __func__, patch->sources[0].ext.mix.handle);
385 status = BAD_VALUE;
386 goto exit;
387 }
388 }
389 if (thread == mAudioFlinger.primaryPlaybackThread_l()) {
390 mAudioFlinger.updateOutDevicesForRecordThreads_l(devices);
391 }
392
393 status = thread->sendCreateAudioPatchConfigEvent(patch, &halHandle);
394 if (status == NO_ERROR) {
395 newPatch.setThread(thread);
396 }
397
398 // remove stale audio patch with same output as source if any
399 for (auto& iter : mPatches) {
400 if (iter.second.mAudioPatch.sources[0].ext.mix.handle == thread->id()) {
401 erasePatch(iter.first);
402 break;
403 }
404 }
405 } break;
406 default:
407 status = BAD_VALUE;
408 goto exit;
409 }
410 exit:
411 ALOGV("%s() status %d", __func__, status);
412 if (status == NO_ERROR) {
413 *handle = (audio_patch_handle_t) mAudioFlinger.nextUniqueId(AUDIO_UNIQUE_ID_USE_PATCH);
414 newPatch.mHalHandle = halHandle;
415 mAudioFlinger.mDeviceEffectManager.createAudioPatch(*handle, newPatch);
416 mPatches.insert(std::make_pair(*handle, std::move(newPatch)));
417 if (insertedModule != AUDIO_MODULE_HANDLE_NONE) {
418 addSoftwarePatchToInsertedModules(insertedModule, *handle);
419 }
420 } else {
421 newPatch.clearConnections(this);
422 }
423 return status;
424 }
425
~Patch()426 AudioFlinger::PatchPanel::Patch::~Patch()
427 {
428 ALOGE_IF(isSoftware(), "Software patch connections leaked %d %d",
429 mRecord.handle(), mPlayback.handle());
430 }
431
createConnections(PatchPanel * panel)432 status_t AudioFlinger::PatchPanel::Patch::createConnections(PatchPanel *panel)
433 {
434 // create patch from source device to record thread input
435 status_t status = panel->createAudioPatch(
436 PatchBuilder().addSource(mAudioPatch.sources[0]).
437 addSink(mRecord.thread(), { .source = AUDIO_SOURCE_MIC }).patch(),
438 mRecord.handlePtr());
439 if (status != NO_ERROR) {
440 *mRecord.handlePtr() = AUDIO_PATCH_HANDLE_NONE;
441 return status;
442 }
443
444 // create patch from playback thread output to sink device
445 if (mAudioPatch.num_sinks != 0) {
446 status = panel->createAudioPatch(
447 PatchBuilder().addSource(mPlayback.thread()).addSink(mAudioPatch.sinks[0]).patch(),
448 mPlayback.handlePtr());
449 if (status != NO_ERROR) {
450 *mPlayback.handlePtr() = AUDIO_PATCH_HANDLE_NONE;
451 return status;
452 }
453 } else {
454 *mPlayback.handlePtr() = AUDIO_PATCH_HANDLE_NONE;
455 }
456
457 // create a special record track to capture from record thread
458 uint32_t channelCount = mPlayback.thread()->channelCount();
459 audio_channel_mask_t inChannelMask = audio_channel_in_mask_from_count(channelCount);
460 audio_channel_mask_t outChannelMask = mPlayback.thread()->channelMask();
461 uint32_t sampleRate = mPlayback.thread()->sampleRate();
462 audio_format_t format = mPlayback.thread()->format();
463
464 audio_format_t inputFormat = mRecord.thread()->format();
465 if (!audio_is_linear_pcm(inputFormat)) {
466 // The playbackThread format will say PCM for IEC61937 packetized stream.
467 // Use recordThread format.
468 format = inputFormat;
469 }
470 audio_input_flags_t inputFlags = mAudioPatch.sources[0].config_mask & AUDIO_PORT_CONFIG_FLAGS ?
471 mAudioPatch.sources[0].flags.input : AUDIO_INPUT_FLAG_NONE;
472 if (sampleRate == mRecord.thread()->sampleRate() &&
473 inChannelMask == mRecord.thread()->channelMask() &&
474 mRecord.thread()->fastTrackAvailable() &&
475 mRecord.thread()->hasFastCapture()) {
476 // Create a fast track if the record thread has fast capture to get better performance.
477 // Only enable fast mode when there is no resample needed.
478 inputFlags = (audio_input_flags_t) (inputFlags | AUDIO_INPUT_FLAG_FAST);
479 } else {
480 // Fast mode is not available in this case.
481 inputFlags = (audio_input_flags_t) (inputFlags & ~AUDIO_INPUT_FLAG_FAST);
482 }
483
484 audio_output_flags_t outputFlags = mAudioPatch.sinks[0].config_mask & AUDIO_PORT_CONFIG_FLAGS ?
485 mAudioPatch.sinks[0].flags.output : AUDIO_OUTPUT_FLAG_NONE;
486 audio_stream_type_t streamType = AUDIO_STREAM_PATCH;
487 if (mAudioPatch.num_sources == 2 && mAudioPatch.sources[1].type == AUDIO_PORT_TYPE_MIX) {
488 // "reuse one existing output mix" case
489 streamType = mAudioPatch.sources[1].ext.mix.usecase.stream;
490 }
491 if (mPlayback.thread()->hasFastMixer()) {
492 // Create a fast track if the playback thread has fast mixer to get better performance.
493 // Note: we should have matching channel mask, sample rate, and format by the logic above.
494 outputFlags = (audio_output_flags_t) (outputFlags | AUDIO_OUTPUT_FLAG_FAST);
495 } else {
496 outputFlags = (audio_output_flags_t) (outputFlags & ~AUDIO_OUTPUT_FLAG_FAST);
497 }
498
499 sp<RecordThread::PatchRecord> tempRecordTrack;
500 const bool usePassthruPatchRecord =
501 (inputFlags & AUDIO_INPUT_FLAG_DIRECT) && (outputFlags & AUDIO_OUTPUT_FLAG_DIRECT);
502 const size_t playbackFrameCount = mPlayback.thread()->frameCount();
503 const size_t recordFrameCount = mRecord.thread()->frameCount();
504 size_t frameCount = 0;
505 if (usePassthruPatchRecord) {
506 // PassthruPatchRecord producesBufferOnDemand, so use
507 // maximum of playback and record thread framecounts
508 frameCount = std::max(playbackFrameCount, recordFrameCount);
509 ALOGV("%s() playframeCount %zu recordFrameCount %zu frameCount %zu",
510 __func__, playbackFrameCount, recordFrameCount, frameCount);
511 tempRecordTrack = new RecordThread::PassthruPatchRecord(
512 mRecord.thread().get(),
513 sampleRate,
514 inChannelMask,
515 format,
516 frameCount,
517 inputFlags);
518 } else {
519 // use a pseudo LCM between input and output framecount
520 int playbackShift = __builtin_ctz(playbackFrameCount);
521 int shift = __builtin_ctz(recordFrameCount);
522 if (playbackShift < shift) {
523 shift = playbackShift;
524 }
525 frameCount = (playbackFrameCount * recordFrameCount) >> shift;
526 ALOGV("%s() playframeCount %zu recordFrameCount %zu frameCount %zu",
527 __func__, playbackFrameCount, recordFrameCount, frameCount);
528
529 tempRecordTrack = new RecordThread::PatchRecord(
530 mRecord.thread().get(),
531 sampleRate,
532 inChannelMask,
533 format,
534 frameCount,
535 nullptr,
536 (size_t)0 /* bufferSize */,
537 inputFlags);
538 }
539 status = mRecord.checkTrack(tempRecordTrack.get());
540 if (status != NO_ERROR) {
541 return status;
542 }
543
544 // create a special playback track to render to playback thread.
545 // this track is given the same buffer as the PatchRecord buffer
546 sp<PlaybackThread::PatchTrack> tempPatchTrack = new PlaybackThread::PatchTrack(
547 mPlayback.thread().get(),
548 streamType,
549 sampleRate,
550 outChannelMask,
551 format,
552 frameCount,
553 tempRecordTrack->buffer(),
554 tempRecordTrack->bufferSize(),
555 outputFlags);
556 status = mPlayback.checkTrack(tempPatchTrack.get());
557 if (status != NO_ERROR) {
558 return status;
559 }
560
561 // tie playback and record tracks together
562 // In the case of PassthruPatchRecord no I/O activity happens on RecordThread,
563 // everything is driven from PlaybackThread. Thus AudioBufferProvider methods
564 // of PassthruPatchRecord can only be called if the corresponding PatchTrack
565 // is alive. There is no need to hold a reference, and there is no need
566 // to clear it. In fact, since playback stopping is asynchronous, there is
567 // no proper time when clearing could be done.
568 mRecord.setTrackAndPeer(tempRecordTrack, tempPatchTrack, !usePassthruPatchRecord);
569 mPlayback.setTrackAndPeer(tempPatchTrack, tempRecordTrack, true /*holdReference*/);
570
571 // start capture and playback
572 mRecord.track()->start(AudioSystem::SYNC_EVENT_NONE, AUDIO_SESSION_NONE);
573 mPlayback.track()->start();
574
575 return status;
576 }
577
clearConnections(PatchPanel * panel)578 void AudioFlinger::PatchPanel::Patch::clearConnections(PatchPanel *panel)
579 {
580 ALOGV("%s() mRecord.handle %d mPlayback.handle %d",
581 __func__, mRecord.handle(), mPlayback.handle());
582 mRecord.stopTrack();
583 mPlayback.stopTrack();
584 mRecord.clearTrackPeer(); // mRecord stop is synchronous. Break PeerProxy sp<> cycle.
585 mRecord.closeConnections(panel);
586 mPlayback.closeConnections(panel);
587 }
588
getLatencyMs(double * latencyMs) const589 status_t AudioFlinger::PatchPanel::Patch::getLatencyMs(double *latencyMs) const
590 {
591 if (!isSoftware()) return INVALID_OPERATION;
592
593 auto recordTrack = mRecord.const_track();
594 if (recordTrack.get() == nullptr) return INVALID_OPERATION;
595
596 auto playbackTrack = mPlayback.const_track();
597 if (playbackTrack.get() == nullptr) return INVALID_OPERATION;
598
599 // Latency information for tracks may be called without obtaining
600 // the underlying thread lock.
601 //
602 // We use record server latency + playback track latency (generally smaller than the
603 // reverse due to internal biases).
604 //
605 // TODO: is this stable enough? Consider a PatchTrack synchronized version of this.
606
607 // For PCM tracks get server latency.
608 if (audio_is_linear_pcm(recordTrack->format())) {
609 double recordServerLatencyMs, playbackTrackLatencyMs;
610 if (recordTrack->getServerLatencyMs(&recordServerLatencyMs) == OK
611 && playbackTrack->getTrackLatencyMs(&playbackTrackLatencyMs) == OK) {
612 *latencyMs = recordServerLatencyMs + playbackTrackLatencyMs;
613 return OK;
614 }
615 }
616
617 // See if kernel latencies are available.
618 // If so, do a frame diff and time difference computation to estimate
619 // the total patch latency. This requires that frame counts are reported by the
620 // HAL are matched properly in the case of record overruns and playback underruns.
621 ThreadBase::TrackBase::FrameTime recordFT{}, playFT{};
622 recordTrack->getKernelFrameTime(&recordFT);
623 playbackTrack->getKernelFrameTime(&playFT);
624 if (recordFT.timeNs > 0 && playFT.timeNs > 0) {
625 const int64_t frameDiff = recordFT.frames - playFT.frames;
626 const int64_t timeDiffNs = recordFT.timeNs - playFT.timeNs;
627
628 // It is possible that the patch track and patch record have a large time disparity because
629 // one thread runs but another is stopped. We arbitrarily choose the maximum timestamp
630 // time difference based on how often we expect the timestamps to update in normal operation
631 // (typical should be no more than 50 ms).
632 //
633 // If the timestamps aren't sampled close enough, the patch latency is not
634 // considered valid.
635 //
636 // TODO: change this based on more experiments.
637 constexpr int64_t maxValidTimeDiffNs = 200 * NANOS_PER_MILLISECOND;
638 if (std::abs(timeDiffNs) < maxValidTimeDiffNs) {
639 *latencyMs = frameDiff * 1e3 / recordTrack->sampleRate()
640 - timeDiffNs * 1e-6;
641 return OK;
642 }
643 }
644
645 return INVALID_OPERATION;
646 }
647
dump(audio_patch_handle_t myHandle) const648 String8 AudioFlinger::PatchPanel::Patch::dump(audio_patch_handle_t myHandle) const
649 {
650 // TODO: Consider table dump form for patches, just like tracks.
651 String8 result = String8::format("Patch %d: %s (thread %p => thread %p)",
652 myHandle, isSoftware() ? "Software bridge between" : "No software bridge",
653 mRecord.const_thread().get(), mPlayback.const_thread().get());
654
655 bool hasSinkDevice =
656 mAudioPatch.num_sinks > 0 && mAudioPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE;
657 bool hasSourceDevice =
658 mAudioPatch.num_sources > 0 && mAudioPatch.sources[0].type == AUDIO_PORT_TYPE_DEVICE;
659 result.appendFormat(" thread %p %s (%d) first device type %08x", mThread.unsafe_get(),
660 hasSinkDevice ? "num sinks" :
661 (hasSourceDevice ? "num sources" : "no devices"),
662 hasSinkDevice ? mAudioPatch.num_sinks :
663 (hasSourceDevice ? mAudioPatch.num_sources : 0),
664 hasSinkDevice ? mAudioPatch.sinks[0].ext.device.type :
665 (hasSourceDevice ? mAudioPatch.sources[0].ext.device.type : 0));
666
667 // add latency if it exists
668 double latencyMs;
669 if (getLatencyMs(&latencyMs) == OK) {
670 result.appendFormat(" latency: %.2lf ms", latencyMs);
671 }
672 return result;
673 }
674
675 /* Disconnect a patch */
releaseAudioPatch(audio_patch_handle_t handle)676 status_t AudioFlinger::PatchPanel::releaseAudioPatch(audio_patch_handle_t handle)
677 {
678 ALOGV("%s handle %d", __func__, handle);
679 status_t status = NO_ERROR;
680
681 auto iter = mPatches.find(handle);
682 if (iter == mPatches.end()) {
683 return BAD_VALUE;
684 }
685 Patch &removedPatch = iter->second;
686 const struct audio_patch &patch = removedPatch.mAudioPatch;
687
688 const struct audio_port_config &src = patch.sources[0];
689 switch (src.type) {
690 case AUDIO_PORT_TYPE_DEVICE: {
691 sp<DeviceHalInterface> hwDevice = findHwDeviceByModule(src.ext.device.hw_module);
692 if (hwDevice == 0) {
693 ALOGW("%s() bad src hw module %d", __func__, src.ext.device.hw_module);
694 status = BAD_VALUE;
695 break;
696 }
697
698 if (removedPatch.isSoftware()) {
699 removedPatch.clearConnections(this);
700 break;
701 }
702
703 if (patch.sinks[0].type == AUDIO_PORT_TYPE_MIX) {
704 audio_io_handle_t ioHandle = patch.sinks[0].ext.mix.handle;
705 sp<ThreadBase> thread = mAudioFlinger.checkRecordThread_l(ioHandle);
706 if (thread == 0) {
707 thread = mAudioFlinger.checkMmapThread_l(ioHandle);
708 if (thread == 0) {
709 ALOGW("%s() bad capture I/O handle %d", __func__, ioHandle);
710 status = BAD_VALUE;
711 break;
712 }
713 }
714 status = thread->sendReleaseAudioPatchConfigEvent(removedPatch.mHalHandle);
715 } else {
716 status = hwDevice->releaseAudioPatch(removedPatch.mHalHandle);
717 }
718 } break;
719 case AUDIO_PORT_TYPE_MIX: {
720 if (findHwDeviceByModule(src.ext.mix.hw_module) == 0) {
721 ALOGW("%s() bad src hw module %d", __func__, src.ext.mix.hw_module);
722 status = BAD_VALUE;
723 break;
724 }
725 audio_io_handle_t ioHandle = src.ext.mix.handle;
726 sp<ThreadBase> thread = mAudioFlinger.checkPlaybackThread_l(ioHandle);
727 if (thread == 0) {
728 thread = mAudioFlinger.checkMmapThread_l(ioHandle);
729 if (thread == 0) {
730 ALOGW("%s() bad playback I/O handle %d", __func__, ioHandle);
731 status = BAD_VALUE;
732 break;
733 }
734 }
735 status = thread->sendReleaseAudioPatchConfigEvent(removedPatch.mHalHandle);
736 } break;
737 default:
738 status = BAD_VALUE;
739 }
740
741 erasePatch(handle);
742 return status;
743 }
744
erasePatch(audio_patch_handle_t handle)745 void AudioFlinger::PatchPanel::erasePatch(audio_patch_handle_t handle) {
746 mPatches.erase(handle);
747 removeSoftwarePatchFromInsertedModules(handle);
748 mAudioFlinger.mDeviceEffectManager.releaseAudioPatch(handle);
749 }
750
751 /* List connected audio ports and they attributes */
listAudioPatches(unsigned int * num_patches __unused,struct audio_patch * patches __unused)752 status_t AudioFlinger::PatchPanel::listAudioPatches(unsigned int *num_patches __unused,
753 struct audio_patch *patches __unused)
754 {
755 ALOGV(__func__);
756 return NO_ERROR;
757 }
758
getDownstreamSoftwarePatches(audio_io_handle_t stream,std::vector<AudioFlinger::PatchPanel::SoftwarePatch> * patches) const759 status_t AudioFlinger::PatchPanel::getDownstreamSoftwarePatches(
760 audio_io_handle_t stream,
761 std::vector<AudioFlinger::PatchPanel::SoftwarePatch> *patches) const
762 {
763 for (const auto& module : mInsertedModules) {
764 if (module.second.streams.count(stream)) {
765 for (const auto& patchHandle : module.second.sw_patches) {
766 const auto& patch_iter = mPatches.find(patchHandle);
767 if (patch_iter != mPatches.end()) {
768 const Patch &patch = patch_iter->second;
769 patches->emplace_back(*this, patchHandle,
770 patch.mPlayback.const_thread()->id(),
771 patch.mRecord.const_thread()->id());
772 } else {
773 ALOGE("Stale patch handle in the cache: %d", patchHandle);
774 }
775 }
776 return OK;
777 }
778 }
779 // The stream is not associated with any of inserted modules.
780 return BAD_VALUE;
781 }
782
notifyStreamOpened(AudioHwDevice * audioHwDevice,audio_io_handle_t stream)783 void AudioFlinger::PatchPanel::notifyStreamOpened(
784 AudioHwDevice *audioHwDevice, audio_io_handle_t stream)
785 {
786 if (audioHwDevice->isInsert()) {
787 mInsertedModules[audioHwDevice->handle()].streams.insert(stream);
788 }
789 }
790
notifyStreamClosed(audio_io_handle_t stream)791 void AudioFlinger::PatchPanel::notifyStreamClosed(audio_io_handle_t stream)
792 {
793 for (auto& module : mInsertedModules) {
794 module.second.streams.erase(stream);
795 }
796 }
797
findAudioHwDeviceByModule(audio_module_handle_t module)798 AudioHwDevice* AudioFlinger::PatchPanel::findAudioHwDeviceByModule(audio_module_handle_t module)
799 {
800 if (module == AUDIO_MODULE_HANDLE_NONE) return nullptr;
801 ssize_t index = mAudioFlinger.mAudioHwDevs.indexOfKey(module);
802 if (index < 0) {
803 ALOGW("%s() bad hw module %d", __func__, module);
804 return nullptr;
805 }
806 return mAudioFlinger.mAudioHwDevs.valueAt(index);
807 }
808
findHwDeviceByModule(audio_module_handle_t module)809 sp<DeviceHalInterface> AudioFlinger::PatchPanel::findHwDeviceByModule(audio_module_handle_t module)
810 {
811 AudioHwDevice *audioHwDevice = findAudioHwDeviceByModule(module);
812 return audioHwDevice ? audioHwDevice->hwDevice() : nullptr;
813 }
814
addSoftwarePatchToInsertedModules(audio_module_handle_t module,audio_patch_handle_t handle)815 void AudioFlinger::PatchPanel::addSoftwarePatchToInsertedModules(
816 audio_module_handle_t module, audio_patch_handle_t handle)
817 {
818 mInsertedModules[module].sw_patches.insert(handle);
819 }
820
removeSoftwarePatchFromInsertedModules(audio_patch_handle_t handle)821 void AudioFlinger::PatchPanel::removeSoftwarePatchFromInsertedModules(
822 audio_patch_handle_t handle)
823 {
824 for (auto& module : mInsertedModules) {
825 module.second.sw_patches.erase(handle);
826 }
827 }
828
dump(int fd) const829 void AudioFlinger::PatchPanel::dump(int fd) const
830 {
831 String8 patchPanelDump;
832 const char *indent = " ";
833
834 bool headerPrinted = false;
835 for (const auto& iter : mPatches) {
836 if (!headerPrinted) {
837 patchPanelDump += "\nPatches:\n";
838 headerPrinted = true;
839 }
840 patchPanelDump.appendFormat("%s%s\n", indent, iter.second.dump(iter.first).string());
841 }
842
843 headerPrinted = false;
844 for (const auto& module : mInsertedModules) {
845 if (!module.second.streams.empty() || !module.second.sw_patches.empty()) {
846 if (!headerPrinted) {
847 patchPanelDump += "\nTracked inserted modules:\n";
848 headerPrinted = true;
849 }
850 String8 moduleDump = String8::format("Module %d: I/O handles: ", module.first);
851 for (const auto& stream : module.second.streams) {
852 moduleDump.appendFormat("%d ", stream);
853 }
854 moduleDump.append("; SW Patches: ");
855 for (const auto& patch : module.second.sw_patches) {
856 moduleDump.appendFormat("%d ", patch);
857 }
858 patchPanelDump.appendFormat("%s%s\n", indent, moduleDump.string());
859 }
860 }
861
862 if (!patchPanelDump.isEmpty()) {
863 write(fd, patchPanelDump.string(), patchPanelDump.size());
864 }
865 }
866
867 } // namespace android
868