1 /*
2  * Copyright (C) 2015 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #pragma once
18 
19 #define __STDC_LIMIT_MACROS
20 #include <inttypes.h>
21 
22 #include <sys/types.h>
23 
24 #include <media/AudioContainers.h>
25 #include <utils/Errors.h>
26 #include <utils/Timers.h>
27 #include <utils/KeyedVector.h>
28 #include <system/audio.h>
29 #include "AudioIODescriptorInterface.h"
30 #include "ClientDescriptor.h"
31 #include "DeviceDescriptor.h"
32 #include "PolicyAudioPort.h"
33 #include <vector>
34 
35 namespace android {
36 
37 class IOProfile;
38 class AudioPolicyMix;
39 class AudioPolicyClientInterface;
40 
41 class ActivityTracking
42 {
43 public:
44     virtual ~ActivityTracking() = default;
45     bool isActive(uint32_t inPastMs = 0, nsecs_t sysTime = 0) const
46     {
47         if (mActivityCount > 0) {
48             return true;
49         }
50         if (inPastMs == 0) {
51             return false;
52         }
53         if (sysTime == 0) {
54             sysTime = systemTime();
55         }
56         if (ns2ms(sysTime - mStopTime) < inPastMs) {
57             return true;
58         }
59         return false;
60     }
changeActivityCount(int delta)61     void changeActivityCount(int delta)
62     {
63         if ((delta + (int)mActivityCount) < 0) {
64             LOG_ALWAYS_FATAL("%s: invalid delta %d, refCount %d", __func__, delta, mActivityCount);
65         }
66         mActivityCount += delta;
67         if (!mActivityCount) {
68             setStopTime(systemTime());
69         }
70     }
getActivityCount()71     uint32_t getActivityCount() const { return mActivityCount; }
getStopTime()72     nsecs_t getStopTime() const { return mStopTime; }
setStopTime(nsecs_t stopTime)73     void setStopTime(nsecs_t stopTime) { mStopTime = stopTime; }
74 
dump(String8 * dst,int spaces)75     virtual void dump(String8 *dst, int spaces) const
76     {
77         dst->appendFormat("%*s- ActivityCount: %d, StopTime: %" PRId64 ", ", spaces, "",
78                           getActivityCount(), getStopTime());
79     }
80 private:
81     uint32_t mActivityCount = 0;
82     nsecs_t mStopTime = 0;
83 };
84 
85 /**
86  * @brief VolumeActivity: it tracks the activity for volume policy (volume index, mute,
87  * memorize previous stop, and store mute if incompatible device with another strategy.
88  */
89 class VolumeActivity : public ActivityTracking
90 {
91 public:
isMuted()92     bool isMuted() const { return mMuteCount > 0; }
getMuteCount()93     int getMuteCount() const { return mMuteCount; }
incMuteCount()94     int incMuteCount() { return ++mMuteCount; }
decMuteCount()95     int decMuteCount() { return mMuteCount > 0 ? --mMuteCount : -1; }
96 
dump(String8 * dst,int spaces)97     void dump(String8 *dst, int spaces) const override
98     {
99         ActivityTracking::dump(dst, spaces);
100         dst->appendFormat(", Volume: %.03f, MuteCount: %02d\n", mCurVolumeDb, mMuteCount);
101     }
setVolume(float volumeDb)102     void setVolume(float volumeDb) { mCurVolumeDb = volumeDb; }
getVolume()103     float getVolume() const { return mCurVolumeDb; }
104 
105 private:
106     int mMuteCount = 0; /**< mute request counter */
107     float mCurVolumeDb = NAN; /**< current volume in dB. */
108 };
109 /**
110  * Note: volume activities shall be indexed by CurvesId if we want to allow multiple
111  * curves per volume source, inferring a mute management or volume balancing between HW and SW is
112  * done
113  */
114 using VolumeActivities = std::map<VolumeSource, VolumeActivity>;
115 
116 /**
117  * @brief The Activity class: it tracks the activity for volume policy (volume index, mute,
118  * memorize previous stop, and store mute if incompatible device with another strategy.
119  * Having this class prevents from looping on all attributes (legacy streams) of the strategy
120  */
121 class RoutingActivity : public ActivityTracking
122 {
123 public:
setMutedByDevice(bool isMuted)124     void setMutedByDevice( bool isMuted) { mIsMutedByDevice = isMuted; }
isMutedByDevice()125     bool isMutedByDevice() const { return mIsMutedByDevice; }
126 
dump(String8 * dst,int spaces)127     void dump(String8 *dst, int spaces) const override {
128         ActivityTracking::dump(dst, spaces);
129         dst->appendFormat("\n");
130     }
131 private:
132     /**
133      * strategies muted because of incompatible device selection.
134      * See AudioPolicyManager::checkDeviceMuteStrategies()
135      */
136     bool mIsMutedByDevice = false;
137 };
138 using RoutingActivities = std::map<product_strategy_t, RoutingActivity>;
139 
140 // descriptor for audio outputs. Used to maintain current configuration of each opened audio output
141 // and keep track of the usage of this output by each audio stream type.
142 class AudioOutputDescriptor: public AudioPortConfig,
143         public PolicyAudioPortConfig,
144         public AudioIODescriptorInterface,
145         public ClientMapHandler<TrackClientDescriptor>
146 {
147 public:
148     AudioOutputDescriptor(const sp<PolicyAudioPort>& policyAudioPort,
149                           AudioPolicyClientInterface *clientInterface);
~AudioOutputDescriptor()150     virtual ~AudioOutputDescriptor() {}
151 
152     void dump(String8 *dst) const override;
153     void        log(const char* indent);
154 
devices()155     virtual DeviceVector devices() const { return mDevices; }
156     bool sharesHwModuleWith(const sp<AudioOutputDescriptor>& outputDesc);
supportedDevices()157     virtual DeviceVector supportedDevices() const  { return mDevices; }
isDuplicated()158     virtual bool isDuplicated() const { return false; }
latency()159     virtual uint32_t latency() { return 0; }
160     virtual bool isFixedVolume(const DeviceTypeSet& deviceTypes);
161     virtual bool setVolume(float volumeDb,
162                            VolumeSource volumeSource, const StreamTypeVector &streams,
163                            const DeviceTypeSet& deviceTypes,
164                            uint32_t delayMs,
165                            bool force);
166 
167     /**
168      * @brief setStopTime set the stop time due to the client stoppage or a re routing of this
169      * client
170      * @param client to be considered
171      * @param sysTime when the client stopped/was rerouted
172      */
173     void setStopTime(const sp<TrackClientDescriptor>& client, nsecs_t sysTime);
174 
175     /**
176      * Changes the client->active() state and the output descriptor's global active count,
177      * along with the stream active count and mActiveClients.
178      * The client must be previously added by the base class addClient().
179      * In case of duplicating thread, client shall be added on the duplicated thread, not on the
180      * involved outputs but setClientActive will be called on all output to track strategy and
181      * active client for a given output.
182      * Active ref count of the client will be incremented/decremented through setActive API
183      */
184     virtual void setClientActive(const sp<TrackClientDescriptor>& client, bool active);
185 
186     bool isActive(uint32_t inPastMs) const;
187     bool isActive(VolumeSource volumeSource = VOLUME_SOURCE_NONE,
188                   uint32_t inPastMs = 0,
189                   nsecs_t sysTime = 0) const;
190     bool isAnyActive(VolumeSource volumeSourceToIgnore) const;
191 
getActiveVolumeSources()192     std::vector<VolumeSource> getActiveVolumeSources() const {
193         std::vector<VolumeSource> activeList;
194         for (const auto &iter : mVolumeActivities) {
195             if (iter.second.isActive()) {
196                 activeList.push_back(iter.first);
197             }
198         }
199         return activeList;
200     }
getActivityCount(VolumeSource vs)201     uint32_t getActivityCount(VolumeSource vs) const
202     {
203         return mVolumeActivities.find(vs) != std::end(mVolumeActivities)?
204                     mVolumeActivities.at(vs).getActivityCount() : 0;
205     }
isMuted(VolumeSource vs)206     bool isMuted(VolumeSource vs) const
207     {
208         return mVolumeActivities.find(vs) != std::end(mVolumeActivities)?
209                     mVolumeActivities.at(vs).isMuted() : false;
210     }
getMuteCount(VolumeSource vs)211     int getMuteCount(VolumeSource vs) const
212     {
213         return mVolumeActivities.find(vs) != std::end(mVolumeActivities)?
214                     mVolumeActivities.at(vs).getMuteCount() : 0;
215     }
incMuteCount(VolumeSource vs)216     int incMuteCount(VolumeSource vs)
217     {
218         return mVolumeActivities[vs].incMuteCount();
219     }
decMuteCount(VolumeSource vs)220     int decMuteCount(VolumeSource vs)
221     {
222         return mVolumeActivities[vs].decMuteCount();
223     }
setCurVolume(VolumeSource vs,float volumeDb)224     void setCurVolume(VolumeSource vs, float volumeDb)
225     {
226         // Even if not activity for this source registered, need to create anyway
227         mVolumeActivities[vs].setVolume(volumeDb);
228     }
getCurVolume(VolumeSource vs)229     float getCurVolume(VolumeSource vs) const
230     {
231         return mVolumeActivities.find(vs) != std::end(mVolumeActivities) ?
232                     mVolumeActivities.at(vs).getVolume() : NAN;
233     }
234 
235     bool isStrategyActive(product_strategy_t ps, uint32_t inPastMs = 0, nsecs_t sysTime = 0) const
236     {
237         return mRoutingActivities.find(ps) != std::end(mRoutingActivities)?
238                     mRoutingActivities.at(ps).isActive(inPastMs, sysTime) : false;
239     }
isStrategyMutedByDevice(product_strategy_t ps)240     bool isStrategyMutedByDevice(product_strategy_t ps) const
241     {
242         return mRoutingActivities.find(ps) != std::end(mRoutingActivities)?
243                     mRoutingActivities.at(ps).isMutedByDevice() : false;
244     }
setStrategyMutedByDevice(product_strategy_t ps,bool isMuted)245     void setStrategyMutedByDevice(product_strategy_t ps, bool isMuted)
246     {
247         mRoutingActivities[ps].setMutedByDevice(isMuted);
248     }
249 
250     // PolicyAudioPortConfig
getPolicyAudioPort()251     virtual sp<PolicyAudioPort> getPolicyAudioPort() const
252     {
253         return mPolicyAudioPort;
254     }
255 
256     // AudioPortConfig
257     virtual status_t applyAudioPortConfig(const struct audio_port_config *config,
258                                           struct audio_port_config *backupConfig = NULL);
259     virtual void toAudioPortConfig(struct audio_port_config *dstConfig,
260                            const struct audio_port_config *srcConfig = NULL) const;
getAudioPort()261     virtual sp<AudioPort> getAudioPort() const { return mPolicyAudioPort->asAudioPort(); }
262 
263     virtual void toAudioPort(struct audio_port *port) const;
264 
265     audio_module_handle_t getModuleHandle() const;
266 
267     // implementation of AudioIODescriptorInterface
268     audio_config_base_t getConfig() const override;
269     audio_patch_handle_t getPatchHandle() const override;
270     void setPatchHandle(audio_patch_handle_t handle) override;
isMmap()271     bool isMmap() override {
272         if (getPolicyAudioPort() != nullptr) {
273             return getPolicyAudioPort()->isMmap();
274         }
275         return false;
276     }
277 
278     TrackClientVector clientsList(bool activeOnly = false,
279                                   product_strategy_t strategy = PRODUCT_STRATEGY_NONE,
280                                   bool preferredDeviceOnly = false) const;
281 
282     // override ClientMapHandler to abort when removing a client when active.
removeClient(audio_port_handle_t portId)283     void removeClient(audio_port_handle_t portId) override {
284         auto client = getClient(portId);
285         LOG_ALWAYS_FATAL_IF(client.get() == nullptr,
286                 "%s(%d): nonexistent client portId %d", __func__, mId, portId);
287         // it is possible that when a client is removed, we could remove its
288         // associated active count by calling changeStreamActiveCount(),
289         // but that would be hiding a problem, so we log fatal instead.
290         auto clientIter = std::find(begin(mActiveClients), end(mActiveClients), client);
291         LOG_ALWAYS_FATAL_IF(clientIter != mActiveClients.end(),
292                             "%s(%d) removing client portId %d which is active (count %d)",
293                             __func__, mId, portId, client->getActivityCount());
294         ClientMapHandler<TrackClientDescriptor>::removeClient(portId);
295     }
296 
getActiveClients()297     const TrackClientVector& getActiveClients() const {
298         return mActiveClients;
299     }
300 
useHwGain()301     bool useHwGain() const
302     {
303         return !devices().isEmpty() ? devices().itemAt(0)->hasGainController() : false;
304     }
305 
306     DeviceVector mDevices; /**< current devices this output is routed to */
307     wp<AudioPolicyMix> mPolicyMix;  // non NULL when used by a dynamic policy
308 
309 protected:
310     const sp<PolicyAudioPort> mPolicyAudioPort;
311     AudioPolicyClientInterface * const mClientInterface;
312     uint32_t mGlobalActiveCount = 0;  // non-client-specific active count
313     audio_patch_handle_t mPatchHandle = AUDIO_PATCH_HANDLE_NONE;
314 
315     // The ActiveClients shows the clients that contribute to the @VolumeSource counts
316     // and may include upstream clients from a duplicating thread.
317     // Compare with the ClientMap (mClients) which are external AudioTrack clients of the
318     // output descriptor (and do not count internal PatchTracks).
319     TrackClientVector mActiveClients;
320 
321     RoutingActivities mRoutingActivities; /**< track routing activity on this ouput.*/
322 
323     VolumeActivities mVolumeActivities; /**< track volume activity on this ouput.*/
324 };
325 
326 // Audio output driven by a software mixer in audio flinger.
327 class SwAudioOutputDescriptor: public AudioOutputDescriptor
328 {
329 public:
330     SwAudioOutputDescriptor(const sp<IOProfile>& profile,
331                             AudioPolicyClientInterface *clientInterface);
~SwAudioOutputDescriptor()332     virtual ~SwAudioOutputDescriptor() {}
333 
334             void dump(String8 *dst) const override;
335     virtual DeviceVector devices() const;
setDevices(const DeviceVector & devices)336     void setDevices(const DeviceVector &devices) { mDevices = devices; }
337     bool sharesHwModuleWith(const sp<SwAudioOutputDescriptor>& outputDesc);
338     virtual DeviceVector supportedDevices() const;
339     virtual bool devicesSupportEncodedFormats(const DeviceTypeSet& deviceTypes);
340     virtual uint32_t latency();
isDuplicated()341     virtual bool isDuplicated() const { return (mOutput1 != NULL && mOutput2 != NULL); }
342     virtual bool isFixedVolume(const DeviceTypeSet& deviceTypes);
subOutput1()343     sp<SwAudioOutputDescriptor> subOutput1() { return mOutput1; }
subOutput2()344     sp<SwAudioOutputDescriptor> subOutput2() { return mOutput2; }
345     void setClientActive(const sp<TrackClientDescriptor>& client, bool active) override;
setAllClientsInactive()346     void setAllClientsInactive()
347     {
348         for (const auto &client : clientsList(true)) {
349             setClientActive(client, false);
350         }
351     }
352     virtual bool setVolume(float volumeDb,
353                            VolumeSource volumeSource, const StreamTypeVector &streams,
354                            const DeviceTypeSet& device,
355                            uint32_t delayMs,
356                            bool force);
357 
358     virtual void toAudioPortConfig(struct audio_port_config *dstConfig,
359                            const struct audio_port_config *srcConfig = NULL) const;
360     virtual void toAudioPort(struct audio_port *port) const;
361 
362         status_t open(const audio_config_t *config,
363                       const DeviceVector &devices,
364                       audio_stream_type_t stream,
365                       audio_output_flags_t flags,
366                       audio_io_handle_t *output);
367 
368         // Called when a stream is about to be started
369         // Note: called before setClientActive(true);
370         status_t start();
371         // Called after a stream is stopped.
372         // Note: called after setClientActive(false);
373         void stop();
374         void close();
375         status_t openDuplicating(const sp<SwAudioOutputDescriptor>& output1,
376                                  const sp<SwAudioOutputDescriptor>& output2,
377                                  audio_io_handle_t *ioHandle);
378 
379     /**
380      * @brief supportsDevice
381      * @param device to be checked against
382      * @return true if the device is supported by type (for non bus / remote submix devices),
383      *         true if the device is supported (both type and address) for bus / remote submix
384      *         false otherwise
385      */
386     bool supportsDevice(const sp<DeviceDescriptor> &device) const;
387 
388     /**
389      * @brief supportsAllDevices
390      * @param devices to be checked against
391      * @return true if the device is weakly supported by type (e.g. for non bus / rsubmix devices),
392      *         true if the device is supported (both type and address) for bus / remote submix
393      *         false otherwise
394      */
395     bool supportsAllDevices(const DeviceVector &devices) const;
396 
397     /**
398      * @brief filterSupportedDevices takes a vector of devices and filters them according to the
399      * device supported by this output (the profile from which this output derives from)
400      * @param devices reference device vector to be filtered
401      * @return vector of devices filtered from the supported devices of this output (weakly or not
402      * depending on the device type)
403      */
404     DeviceVector filterSupportedDevices(const DeviceVector &devices) const;
405 
406     const sp<IOProfile> mProfile;          // I/O profile this output derives from
407     audio_io_handle_t mIoHandle;           // output handle
408     uint32_t mLatency;                  //
409     audio_output_flags_t mFlags;   //
410     sp<SwAudioOutputDescriptor> mOutput1;    // used by duplicated outputs: first output
411     sp<SwAudioOutputDescriptor> mOutput2;    // used by duplicated outputs: second output
412     uint32_t mDirectOpenCount; // number of clients using this output (direct outputs only)
413     audio_session_t mDirectClientSession; // session id of the direct output client
414 };
415 
416 // Audio output driven by an input device directly.
417 class HwAudioOutputDescriptor: public AudioOutputDescriptor
418 {
419 public:
420     HwAudioOutputDescriptor(const sp<SourceClientDescriptor>& source,
421                             AudioPolicyClientInterface *clientInterface);
~HwAudioOutputDescriptor()422     virtual ~HwAudioOutputDescriptor() {}
423 
424             void dump(String8 *dst) const override;
425 
426     virtual bool setVolume(float volumeDb,
427                            VolumeSource volumeSource, const StreamTypeVector &streams,
428                            const DeviceTypeSet& deviceTypes,
429                            uint32_t delayMs,
430                            bool force);
431 
432     virtual void toAudioPortConfig(struct audio_port_config *dstConfig,
433                            const struct audio_port_config *srcConfig = NULL) const;
434     virtual void toAudioPort(struct audio_port *port) const;
435 
436     const sp<SourceClientDescriptor> mSource;
437 
438 };
439 
440 class SwAudioOutputCollection :
441         public DefaultKeyedVector< audio_io_handle_t, sp<SwAudioOutputDescriptor> >
442 {
443 public:
444     bool isActive(VolumeSource volumeSource, uint32_t inPastMs = 0) const;
445 
446     /**
447      * return whether any source contributing to VolumeSource is playing remotely, override
448      * to change the definition of
449      * local/remote playback, used for instance by notification manager to not make
450      * media players lose audio focus when not playing locally
451      * For the base implementation, "remotely" means playing during screen mirroring which
452      * uses an output for playback with a non-empty, non "0" address.
453      */
454     bool isActiveRemotely(VolumeSource volumeSource, uint32_t inPastMs = 0) const;
455 
456     /**
457      * return whether any source contributing to VolumeSource is playing, but not on a "remote"
458      * device.
459      * Override to change the definition of a local/remote playback.
460      * Used for instance by policy manager to alter the speaker playback ("speaker safe" behavior)
461      * when media plays or not locally.
462      * For the base implementation, "remotely" means playing during screen mirroring.
463      */
464     bool isActiveLocally(VolumeSource volumeSource, uint32_t inPastMs = 0) const;
465 
466     /**
467      * @brief isStrategyActiveOnSameModule checks if the given strategy is active (or was active
468      * in the past) on the given output and all the outputs belonging to the same HW Module
469      * the same module than the given output
470      * @param outputDesc to be considered
471      * @param ps product strategy to be checked upon activity status
472      * @param inPastMs if 0, check currently, otherwise, check in the past
473      * @param sysTime shall be set if request is done for the past activity.
474      * @return true if an output following the strategy is active on the same module than desc,
475      * false otherwise
476      */
477     bool isStrategyActiveOnSameModule(product_strategy_t ps,
478                                       const sp<SwAudioOutputDescriptor>& desc,
479                                       uint32_t inPastMs = 0, nsecs_t sysTime = 0) const;
480 
481     /**
482      * @brief clearSessionRoutesForDevice: when a device is disconnected, and if this device has
483      * been chosen as the preferred device by any client, the policy manager shall
484      * prevent from using this device any more by clearing all the session routes involving this
485      * device.
486      * In other words, the preferred device port id of these clients will be resetted to NONE.
487      * @param disconnectedDevice device to be disconnected
488      */
489     void clearSessionRoutesForDevice(const sp<DeviceDescriptor> &disconnectedDevice);
490 
491     /**
492      * returns the A2DP output handle if it is open or 0 otherwise
493      */
494     audio_io_handle_t getA2dpOutput() const;
495 
496     /**
497      * returns true if primary HAL supports A2DP Offload
498      */
499     bool isA2dpOffloadedOnPrimary() const;
500 
501     /**
502      * returns true if A2DP is supported (either via hardware offload or software encoding)
503      */
504     bool isA2dpSupported() const;
505 
506     sp<SwAudioOutputDescriptor> getOutputFromId(audio_port_handle_t id) const;
507 
508     sp<SwAudioOutputDescriptor> getPrimaryOutput() const;
509 
510     /**
511      * @brief isAnyOutputActive checks if any output is active (aka playing) except the one(s) that
512      * hold the volume source to be ignored
513      * @param volumeSourceToIgnore source not to be considered in the activity detection
514      * @return true if any output is active for any volume source except the one to be ignored
515      */
isAnyOutputActive(VolumeSource volumeSourceToIgnore)516     bool isAnyOutputActive(VolumeSource volumeSourceToIgnore) const
517     {
518         for (size_t i = 0; i < size(); i++) {
519             const sp<AudioOutputDescriptor> &outputDesc = valueAt(i);
520             if (outputDesc->isAnyActive(volumeSourceToIgnore)) {
521                 return true;
522             }
523         }
524         return false;
525     }
526 
527     audio_devices_t getSupportedDevices(audio_io_handle_t handle) const;
528 
529     sp<SwAudioOutputDescriptor> getOutputForClient(audio_port_handle_t portId);
530 
531     void dump(String8 *dst) const;
532 };
533 
534 class HwAudioOutputCollection :
535         public DefaultKeyedVector< audio_io_handle_t, sp<HwAudioOutputDescriptor> >
536 {
537 public:
538     bool isActive(VolumeSource volumeSource, uint32_t inPastMs = 0) const;
539 
540     /**
541      * @brief isAnyOutputActive checks if any output is active (aka playing) except the one(s) that
542      * hold the volume source to be ignored
543      * @param volumeSourceToIgnore source not to be considered in the activity detection
544      * @return true if any output is active for any volume source except the one to be ignored
545      */
isAnyOutputActive(VolumeSource volumeSourceToIgnore)546     bool isAnyOutputActive(VolumeSource volumeSourceToIgnore) const
547     {
548         for (size_t i = 0; i < size(); i++) {
549             const sp<AudioOutputDescriptor> &outputDesc = valueAt(i);
550             if (outputDesc->isAnyActive(volumeSourceToIgnore)) {
551                 return true;
552             }
553         }
554         return false;
555     }
556 
557     void dump(String8 *dst) const;
558 };
559 
560 
561 } // namespace android
562