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