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