1 /*
2 **
3 ** Copyright 2012, 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 #ifndef INCLUDING_FROM_AUDIOFLINGER_H
19     #error This header file should only be included from AudioFlinger.h
20 #endif
21 
22 // Checks and monitors OP_PLAY_AUDIO
23 class OpPlayAudioMonitor : public RefBase {
24 public:
25     ~OpPlayAudioMonitor() override;
26     bool hasOpPlayAudio() const;
27 
28     static sp<OpPlayAudioMonitor> createIfNeeded(
29             uid_t uid, const audio_attributes_t& attr, int id, audio_stream_type_t streamType);
30 
31 private:
32     OpPlayAudioMonitor(uid_t uid, audio_usage_t usage, int id);
33     void onFirstRef() override;
34     static void getPackagesForUid(uid_t uid, Vector<String16>& packages);
35 
36     AppOpsManager mAppOpsManager;
37 
38     class PlayAudioOpCallback : public BnAppOpsCallback {
39     public:
40         explicit PlayAudioOpCallback(const wp<OpPlayAudioMonitor>& monitor);
41         void opChanged(int32_t op, const String16& packageName) override;
42 
43     private:
44         const wp<OpPlayAudioMonitor> mMonitor;
45     };
46 
47     sp<PlayAudioOpCallback> mOpCallback;
48     // called by PlayAudioOpCallback when OP_PLAY_AUDIO is updated in AppOp callback
49     void checkPlayAudioForUsage();
50 
51     std::atomic_bool mHasOpPlayAudio;
52     Vector<String16> mPackages;
53     const uid_t mUid;
54     const int32_t mUsage; // on purpose not audio_usage_t because always checked in appOps as int32_t
55     const int mId; // for logging purposes only
56 };
57 
58 // playback track
59 class Track : public TrackBase, public VolumeProvider {
60 public:
61                         Track(  PlaybackThread *thread,
62                                 const sp<Client>& client,
63                                 audio_stream_type_t streamType,
64                                 const audio_attributes_t& attr,
65                                 uint32_t sampleRate,
66                                 audio_format_t format,
67                                 audio_channel_mask_t channelMask,
68                                 size_t frameCount,
69                                 void *buffer,
70                                 size_t bufferSize,
71                                 const sp<IMemory>& sharedBuffer,
72                                 audio_session_t sessionId,
73                                 pid_t creatorPid,
74                                 uid_t uid,
75                                 audio_output_flags_t flags,
76                                 track_type type,
77                                 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE,
78                                 /** default behaviour is to start when there are as many frames
79                                   * ready as possible (aka. Buffer is full). */
80                                 size_t frameCountToBeReady = SIZE_MAX);
81     virtual             ~Track();
82     virtual status_t    initCheck() const;
83 
84             void        appendDumpHeader(String8& result);
85             void        appendDump(String8& result, bool active);
86     virtual status_t    start(AudioSystem::sync_event_t event = AudioSystem::SYNC_EVENT_NONE,
87                               audio_session_t triggerSession = AUDIO_SESSION_NONE);
88     virtual void        stop();
89             void        pause();
90 
91             void        flush();
92             void        destroy();
93 
94     virtual uint32_t    sampleRate() const;
95 
streamType()96             audio_stream_type_t streamType() const {
97                 return mStreamType;
98             }
isOffloaded()99             bool        isOffloaded() const
100                                 { return (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0; }
isDirect()101             bool        isDirect() const override
102                                 { return (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0; }
isOffloadedOrDirect()103             bool        isOffloadedOrDirect() const { return (mFlags
104                             & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD
105                                     | AUDIO_OUTPUT_FLAG_DIRECT)) != 0; }
isStatic()106             bool        isStatic() const { return  mSharedBuffer.get() != nullptr; }
107 
108             status_t    setParameters(const String8& keyValuePairs);
109             status_t    selectPresentation(int presentationId, int programId);
110             status_t    attachAuxEffect(int EffectId);
111             void        setAuxBuffer(int EffectId, int32_t *buffer);
auxBuffer()112             int32_t     *auxBuffer() const { return mAuxBuffer; }
setMainBuffer(effect_buffer_t * buffer)113             void        setMainBuffer(effect_buffer_t *buffer) { mMainBuffer = buffer; }
mainBuffer()114             effect_buffer_t *mainBuffer() const { return mMainBuffer; }
auxEffectId()115             int         auxEffectId() const { return mAuxEffectId; }
116     virtual status_t    getTimestamp(AudioTimestamp& timestamp);
117             void        signal();
118 
119 // implement FastMixerState::VolumeProvider interface
120     virtual gain_minifloat_packed_t getVolumeLR();
121 
122     virtual status_t    setSyncEvent(const sp<SyncEvent>& event);
123 
isFastTrack()124     virtual bool        isFastTrack() const { return (mFlags & AUDIO_OUTPUT_FLAG_FAST) != 0; }
125 
bufferLatencyMs()126             double      bufferLatencyMs() const override {
127                             return isStatic() ? 0. : TrackBase::bufferLatencyMs();
128                         }
129 
130 // implement volume handling.
131     media::VolumeShaper::Status applyVolumeShaper(
132                                 const sp<media::VolumeShaper::Configuration>& configuration,
133                                 const sp<media::VolumeShaper::Operation>& operation);
134     sp<media::VolumeShaper::State> getVolumeShaperState(int id);
getVolumeHandler()135     sp<media::VolumeHandler>   getVolumeHandler() { return mVolumeHandler; }
136     /** Set the computed normalized final volume of the track.
137      * !masterMute * masterVolume * streamVolume * averageLRVolume */
138     void                setFinalVolume(float volume);
getFinalVolume()139     float               getFinalVolume() const { return mFinalVolume; }
140 
141     /** @return true if the track has changed (metadata or volume) since
142      *          the last time this function was called,
143      *          true if this function was never called since the track creation,
144      *          false otherwise.
145      *  Thread safe.
146      */
readAndClearHasChanged()147     bool            readAndClearHasChanged() { return !mChangeNotified.test_and_set(); }
148 
149     using SourceMetadatas = std::vector<playback_track_metadata_t>;
150     using MetadataInserter = std::back_insert_iterator<SourceMetadatas>;
151     /** Copy the track metadata in the provided iterator. Thread safe. */
152     virtual void    copyMetadataTo(MetadataInserter& backInserter) const;
153 
154             /** Return haptic playback of the track is enabled or not, used in mixer. */
getHapticPlaybackEnabled()155             bool    getHapticPlaybackEnabled() const { return mHapticPlaybackEnabled; }
156             /** Set haptic playback of the track is enabled or not, should be
157              *  set after query or get callback from vibrator service */
setHapticPlaybackEnabled(bool hapticPlaybackEnabled)158             void    setHapticPlaybackEnabled(bool hapticPlaybackEnabled) {
159                 mHapticPlaybackEnabled = hapticPlaybackEnabled;
160             }
161             /** Return at what intensity to play haptics, used in mixer. */
getHapticIntensity()162             AudioMixer::haptic_intensity_t getHapticIntensity() const { return mHapticIntensity; }
163             /** Set intensity of haptic playback, should be set after querying vibrator service. */
setHapticIntensity(AudioMixer::haptic_intensity_t hapticIntensity)164             void    setHapticIntensity(AudioMixer::haptic_intensity_t hapticIntensity) {
165                 if (AudioMixer::isValidHapticIntensity(hapticIntensity)) {
166                     mHapticIntensity = hapticIntensity;
167                     setHapticPlaybackEnabled(mHapticIntensity != AudioMixer::HAPTIC_SCALE_MUTE);
168                 }
169             }
getExternalVibration()170             sp<os::ExternalVibration> getExternalVibration() const { return mExternalVibration; }
171 
172             void    setTeePatches(TeePatches teePatches);
173 
174 protected:
175     // for numerous
176     friend class PlaybackThread;
177     friend class MixerThread;
178     friend class DirectOutputThread;
179     friend class OffloadThread;
180 
181     DISALLOW_COPY_AND_ASSIGN(Track);
182 
183     // AudioBufferProvider interface
184     status_t getNextBuffer(AudioBufferProvider::Buffer* buffer) override;
185     void releaseBuffer(AudioBufferProvider::Buffer* buffer) override;
186 
187     // ExtendedAudioBufferProvider interface
188     virtual size_t framesReady() const;
189     virtual int64_t framesReleased() const;
190     virtual void onTimestamp(const ExtendedTimestamp &timestamp);
191 
isPausing()192     bool isPausing() const { return mState == PAUSING; }
isPaused()193     bool isPaused() const { return mState == PAUSED; }
isResuming()194     bool isResuming() const { return mState == RESUMING; }
195     bool isReady() const;
setPaused()196     void setPaused() { mState = PAUSED; }
197     void reset();
isFlushPending()198     bool isFlushPending() const { return mFlushHwPending; }
199     void flushAck();
200     bool isResumePending();
201     void resumeAck();
202     void updateTrackFrameInfo(int64_t trackFramesReleased, int64_t sinkFramesWritten,
203             uint32_t halSampleRate, const ExtendedTimestamp &timeStamp);
204 
sharedBuffer()205     sp<IMemory> sharedBuffer() const { return mSharedBuffer; }
206 
207     // framesWritten is cumulative, never reset, and is shared all tracks
208     // audioHalFrames is derived from output latency
209     // FIXME parameters not needed, could get them from the thread
210     bool presentationComplete(int64_t framesWritten, size_t audioHalFrames);
211     void signalClientFlag(int32_t flag);
212 
213     /** Set that a metadata has changed and needs to be notified to backend. Thread safe. */
setMetadataHasChanged()214     void setMetadataHasChanged() { mChangeNotified.clear(); }
215 public:
216     void triggerEvents(AudioSystem::sync_event_t type);
217     virtual void invalidate();
218     void disable();
219 
fastIndex()220     int fastIndex() const { return mFastIndex; }
221 
isPlaybackRestricted()222     bool isPlaybackRestricted() const {
223         // The monitor is only created for tracks that can be silenced.
224         return mOpPlayAudioMonitor ? !mOpPlayAudioMonitor->hasOpPlayAudio() : false; }
225 
226 protected:
227 
228     // FILLED state is used for suppressing volume ramp at begin of playing
229     enum {FS_INVALID, FS_FILLING, FS_FILLED, FS_ACTIVE};
230     mutable uint8_t     mFillingUpStatus;
231     int8_t              mRetryCount;
232 
233     // see comment at AudioFlinger::PlaybackThread::Track::~Track for why this can't be const
234     sp<IMemory>         mSharedBuffer;
235 
236     bool                mResetDone;
237     const audio_stream_type_t mStreamType;
238     effect_buffer_t     *mMainBuffer;
239 
240     int32_t             *mAuxBuffer;
241     int                 mAuxEffectId;
242     bool                mHasVolumeController;
243     size_t              mPresentationCompleteFrames; // number of frames written to the
244                                     // audio HAL when this track will be fully rendered
245                                     // zero means not monitoring
246 
247     // access these three variables only when holding thread lock.
248     LinearMap<int64_t> mFrameMap;           // track frame to server frame mapping
249 
250     ExtendedTimestamp  mSinkTimestamp;
251 
252     sp<media::VolumeHandler>  mVolumeHandler; // handles multiple VolumeShaper configs and operations
253 
254     sp<OpPlayAudioMonitor>  mOpPlayAudioMonitor;
255 
256     bool                mHapticPlaybackEnabled = false; // indicates haptic playback enabled or not
257     // intensity to play haptic data
258     AudioMixer::haptic_intensity_t mHapticIntensity = AudioMixer::HAPTIC_SCALE_MUTE;
259     class AudioVibrationController : public os::BnExternalVibrationController {
260     public:
AudioVibrationController(Track * track)261         explicit AudioVibrationController(Track* track) : mTrack(track) {}
262         binder::Status mute(/*out*/ bool *ret) override;
263         binder::Status unmute(/*out*/ bool *ret) override;
264     private:
265         Track* const mTrack;
266     };
267     sp<AudioVibrationController> mAudioVibrationController;
268     sp<os::ExternalVibration>    mExternalVibration;
269     /** How many frames should be in the buffer before the track is considered ready */
270     const size_t        mFrameCountToBeReady;
271 
272 private:
273     void                interceptBuffer(const AudioBufferProvider::Buffer& buffer);
274     template <class F>
forEachTeePatchTrack(F f)275     void                forEachTeePatchTrack(F f) {
276         for (auto& tp : mTeePatches) { f(tp.patchTrack); }
277     };
278 
279     // The following fields are only for fast tracks, and should be in a subclass
280     int                 mFastIndex; // index within FastMixerState::mFastTracks[];
281                                     // either mFastIndex == -1 if not isFastTrack()
282                                     // or 0 < mFastIndex < FastMixerState::kMaxFast because
283                                     // index 0 is reserved for normal mixer's submix;
284                                     // index is allocated statically at track creation time
285                                     // but the slot is only used if track is active
286     FastTrackUnderruns  mObservedUnderruns; // Most recently observed value of
287                                     // mFastMixerDumpState.mTracks[mFastIndex].mUnderruns
288     volatile float      mCachedVolume;  // combined master volume and stream type volume;
289                                         // 'volatile' means accessed without lock or
290                                         // barrier, but is read/written atomically
291     float               mFinalVolume; // combine master volume, stream type volume and track volume
292     sp<AudioTrackServerProxy>  mAudioTrackServerProxy;
293     bool                mResumeToStopping; // track was paused in stopping state.
294     bool                mFlushHwPending; // track requests for thread flush
295     audio_output_flags_t mFlags;
296     // If the last track change was notified to the client with readAndClearHasChanged
297     std::atomic_flag     mChangeNotified = ATOMIC_FLAG_INIT;
298     TeePatches  mTeePatches;
299 };  // end of Track
300 
301 
302 // playback track, used by DuplicatingThread
303 class OutputTrack : public Track {
304 public:
305 
306     class Buffer : public AudioBufferProvider::Buffer {
307     public:
308         void *mBuffer;
309     };
310 
311                         OutputTrack(PlaybackThread *thread,
312                                 DuplicatingThread *sourceThread,
313                                 uint32_t sampleRate,
314                                 audio_format_t format,
315                                 audio_channel_mask_t channelMask,
316                                 size_t frameCount,
317                                 uid_t uid);
318     virtual             ~OutputTrack();
319 
320     virtual status_t    start(AudioSystem::sync_event_t event =
321                                     AudioSystem::SYNC_EVENT_NONE,
322                              audio_session_t triggerSession = AUDIO_SESSION_NONE);
323     virtual void        stop();
324             ssize_t     write(void* data, uint32_t frames);
bufferQueueEmpty()325             bool        bufferQueueEmpty() const { return mBufferQueue.size() == 0; }
isActive()326             bool        isActive() const { return mActive; }
thread()327     const wp<ThreadBase>& thread() const { return mThread; }
328 
329             void        copyMetadataTo(MetadataInserter& backInserter) const override;
330     /** Set the metadatas of the upstream tracks. Thread safe. */
331             void        setMetadatas(const SourceMetadatas& metadatas);
332     /** returns client timestamp to the upstream duplicating thread. */
getClientProxyTimestamp()333     ExtendedTimestamp   getClientProxyTimestamp() const {
334                             // server - kernel difference is not true latency when drained
335                             // i.e. mServerProxy->isDrained().
336                             ExtendedTimestamp timestamp;
337                             (void) mClientProxy->getTimestamp(&timestamp);
338                             // On success, the timestamp LOCATION_SERVER and LOCATION_KERNEL
339                             // entries will be properly filled. If getTimestamp()
340                             // is unsuccessful, then a default initialized timestamp
341                             // (with mTimeNs[] filled with -1's) is returned.
342                             return timestamp;
343                         }
344 
345 private:
346     status_t            obtainBuffer(AudioBufferProvider::Buffer* buffer,
347                                      uint32_t waitTimeMs);
348     void                clearBufferQueue();
349 
350     void                restartIfDisabled();
351 
352     // Maximum number of pending buffers allocated by OutputTrack::write()
353     static const uint8_t kMaxOverFlowBuffers = 10;
354 
355     Vector < Buffer* >          mBufferQueue;
356     AudioBufferProvider::Buffer mOutBuffer;
357     bool                        mActive;
358     DuplicatingThread* const    mSourceThread; // for waitTimeMs() in write()
359     sp<AudioTrackClientProxy>   mClientProxy;
360 
361     /** Attributes of the source tracks.
362      *
363      * This member must be accessed with mTrackMetadatasMutex taken.
364      * There is one writer (duplicating thread) and one reader (downstream mixer).
365      *
366      * That means that the duplicating thread can block the downstream mixer
367      * thread and vice versa for the time of the copy.
368      * If this becomes an issue, the metadata could be stored in an atomic raw pointer,
369      * and a exchange with nullptr and delete can be used.
370      * Alternatively a read-copy-update might be implemented.
371      */
372     SourceMetadatas mTrackMetadatas;
373     /** Protects mTrackMetadatas against concurrent access. */
374     mutable std::mutex mTrackMetadatasMutex;
375 };  // end of OutputTrack
376 
377 // playback track, used by PatchPanel
378 class PatchTrack : public Track, public PatchTrackBase {
379 public:
380 
381                         PatchTrack(PlaybackThread *playbackThread,
382                                    audio_stream_type_t streamType,
383                                    uint32_t sampleRate,
384                                    audio_channel_mask_t channelMask,
385                                    audio_format_t format,
386                                    size_t frameCount,
387                                    void *buffer,
388                                    size_t bufferSize,
389                                    audio_output_flags_t flags,
390                                    const Timeout& timeout = {},
391                                    size_t frameCountToBeReady = 1 /** Default behaviour is to start
392                                                                     *  as soon as possible to have
393                                                                     *  the lowest possible latency
394                                                                     *  even if it might glitch. */);
395     virtual             ~PatchTrack();
396 
397             size_t      framesReady() const override;
398 
399     virtual status_t    start(AudioSystem::sync_event_t event =
400                                     AudioSystem::SYNC_EVENT_NONE,
401                              audio_session_t triggerSession = AUDIO_SESSION_NONE);
402 
403     // AudioBufferProvider interface
404     virtual status_t getNextBuffer(AudioBufferProvider::Buffer* buffer);
405     virtual void releaseBuffer(AudioBufferProvider::Buffer* buffer);
406 
407     // PatchProxyBufferProvider interface
408     virtual status_t    obtainBuffer(Proxy::Buffer* buffer,
409                                      const struct timespec *timeOut = NULL);
410     virtual void        releaseBuffer(Proxy::Buffer* buffer);
411 
412 private:
413             void restartIfDisabled();
414 };  // end of PatchTrack
415