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_RECORD_AUDIO
23 class OpRecordAudioMonitor : public RefBase {
24 public:
25     ~OpRecordAudioMonitor() override;
26     bool hasOpRecordAudio() const;
27 
28     static sp<OpRecordAudioMonitor> createIfNeeded(uid_t uid, const String16& opPackageName);
29 
30 private:
31     OpRecordAudioMonitor(uid_t uid, const String16& opPackageName);
32     void onFirstRef() override;
33 
34     AppOpsManager mAppOpsManager;
35 
36     class RecordAudioOpCallback : public BnAppOpsCallback {
37     public:
38         explicit RecordAudioOpCallback(const wp<OpRecordAudioMonitor>& monitor);
39         void opChanged(int32_t op, const String16& packageName) override;
40 
41     private:
42         const wp<OpRecordAudioMonitor> mMonitor;
43     };
44 
45     sp<RecordAudioOpCallback> mOpCallback;
46     // called by RecordAudioOpCallback when OP_RECORD_AUDIO is updated in AppOp callback
47     // and in onFirstRef()
48     void checkRecordAudio();
49 
50     std::atomic_bool mHasOpRecordAudio;
51     const uid_t mUid;
52     const String16 mPackage;
53 };
54 
55 // record track
56 class RecordTrack : public TrackBase {
57 public:
58                         RecordTrack(RecordThread *thread,
59                                 const sp<Client>& client,
60                                 const audio_attributes_t& attr,
61                                 uint32_t sampleRate,
62                                 audio_format_t format,
63                                 audio_channel_mask_t channelMask,
64                                 size_t frameCount,
65                                 void *buffer,
66                                 size_t bufferSize,
67                                 audio_session_t sessionId,
68                                 pid_t creatorPid,
69                                 uid_t uid,
70                                 audio_input_flags_t flags,
71                                 track_type type,
72                                 const String16& opPackageName,
73                                 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE);
74     virtual             ~RecordTrack();
75     virtual status_t    initCheck() const;
76 
77     virtual status_t    start(AudioSystem::sync_event_t event, audio_session_t triggerSession);
78     virtual void        stop();
79 
80             void        destroy();
81 
82     virtual void        invalidate();
83             // clear the buffer overflow flag
clearOverflow()84             void        clearOverflow() { mOverflow = false; }
85             // set the buffer overflow flag and return previous value
setOverflow()86             bool        setOverflow() { bool tmp = mOverflow; mOverflow = true;
87                                                 return tmp; }
88 
89             void        appendDumpHeader(String8& result);
90             void        appendDump(String8& result, bool active);
91 
92             void        handleSyncStartEvent(const sp<SyncEvent>& event);
93             void        clearSyncStartEvent();
94 
95             void        updateTrackFrameInfo(int64_t trackFramesReleased,
96                                              int64_t sourceFramesRead,
97                                              uint32_t halSampleRate,
98                                              const ExtendedTimestamp &timestamp);
99 
isFastTrack()100     virtual bool        isFastTrack() const { return (mFlags & AUDIO_INPUT_FLAG_FAST) != 0; }
isDirect()101             bool        isDirect() const override
102                                 { return (mFlags & AUDIO_INPUT_FLAG_DIRECT) != 0; }
103 
setSilenced(bool silenced)104             void        setSilenced(bool silenced) { if (!isPatchTrack()) mSilenced = silenced; }
105             bool        isSilenced() const;
106 
107             status_t    getActiveMicrophones(std::vector<media::MicrophoneInfo>* activeMicrophones);
108 
109             status_t    setPreferredMicrophoneDirection(audio_microphone_direction_t direction);
110             status_t    setPreferredMicrophoneFieldDimension(float zoom);
111 
checkServerLatencySupported(audio_format_t format,audio_input_flags_t flags)112     static  bool        checkServerLatencySupported(
113                                 audio_format_t format, audio_input_flags_t flags) {
114                             return audio_is_linear_pcm(format)
115                                     && (flags & AUDIO_INPUT_FLAG_HW_AV_SYNC) == 0;
116                         }
117 
118 private:
119     friend class AudioFlinger;  // for mState
120 
121     DISALLOW_COPY_AND_ASSIGN(RecordTrack);
122 
123     // AudioBufferProvider interface
124     virtual status_t getNextBuffer(AudioBufferProvider::Buffer* buffer);
125     // releaseBuffer() not overridden
126 
127     bool                mOverflow;  // overflow on most recent attempt to fill client buffer
128 
129             AudioBufferProvider::Buffer mSink;  // references client's buffer sink in shared memory
130 
131             // sync event triggering actual audio capture. Frames read before this event will
132             // be dropped and therefore not read by the application.
133             sp<SyncEvent>                       mSyncStartEvent;
134 
135             // number of captured frames to drop after the start sync event has been received.
136             // when < 0, maximum frames to drop before starting capture even if sync event is
137             // not received
138             ssize_t                             mFramesToDrop;
139 
140             // used by resampler to find source frames
141             ResamplerBufferProvider            *mResamplerBufferProvider;
142 
143             // used by the record thread to convert frames to proper destination format
144             RecordBufferConverter              *mRecordBufferConverter;
145             audio_input_flags_t                mFlags;
146 
147             bool                               mSilenced;
148 
149             // used to enforce OP_RECORD_AUDIO
150             uid_t                              mUid;
151             String16                           mOpPackageName;
152             sp<OpRecordAudioMonitor>           mOpRecordAudioMonitor;
153 };
154 
155 // playback track, used by PatchPanel
156 class PatchRecord : public RecordTrack, public PatchTrackBase {
157 public:
158 
159     PatchRecord(RecordThread *recordThread,
160                 uint32_t sampleRate,
161                 audio_channel_mask_t channelMask,
162                 audio_format_t format,
163                 size_t frameCount,
164                 void *buffer,
165                 size_t bufferSize,
166                 audio_input_flags_t flags,
167                 const Timeout& timeout = {});
168     virtual             ~PatchRecord();
169 
getSource()170     virtual Source* getSource() { return nullptr; }
171 
172     // AudioBufferProvider interface
173     virtual status_t getNextBuffer(AudioBufferProvider::Buffer* buffer);
174     virtual void releaseBuffer(AudioBufferProvider::Buffer* buffer);
175 
176     // PatchProxyBufferProvider interface
177     virtual status_t    obtainBuffer(Proxy::Buffer *buffer,
178                                      const struct timespec *timeOut = NULL);
179     virtual void        releaseBuffer(Proxy::Buffer *buffer);
180 
writeFrames(const void * src,size_t frameCount,size_t frameSize)181     size_t writeFrames(const void* src, size_t frameCount, size_t frameSize) {
182         return writeFrames(this, src, frameCount, frameSize);
183     }
184 
185 protected:
186     /** Write the source data into the buffer provider. @return written frame count. */
187     static size_t writeFrames(AudioBufferProvider* dest, const void* src,
188             size_t frameCount, size_t frameSize);
189 
190 };  // end of PatchRecord
191 
192 class PassthruPatchRecord : public PatchRecord, public Source {
193 public:
194     PassthruPatchRecord(RecordThread *recordThread,
195                         uint32_t sampleRate,
196                         audio_channel_mask_t channelMask,
197                         audio_format_t format,
198                         size_t frameCount,
199                         audio_input_flags_t flags);
200 
getSource()201     Source* getSource() override { return static_cast<Source*>(this); }
202 
203     // Source interface
204     status_t read(void *buffer, size_t bytes, size_t *read) override;
205     status_t getCapturePosition(int64_t *frames, int64_t *time) override;
206     status_t standby() override;
207 
208     // AudioBufferProvider interface
209     // This interface is used by RecordThread to pass the data obtained
210     // from HAL or other source to the client. PassthruPatchRecord receives
211     // the data in 'obtainBuffer' so these calls are stubbed out.
212     status_t getNextBuffer(AudioBufferProvider::Buffer* buffer) override;
213     void releaseBuffer(AudioBufferProvider::Buffer* buffer) override;
214 
215     // PatchProxyBufferProvider interface
216     // This interface is used from DirectOutputThread to acquire data from HAL.
producesBufferOnDemand()217     bool producesBufferOnDemand() const override { return true; }
218     status_t obtainBuffer(Proxy::Buffer *buffer, const struct timespec *timeOut = nullptr) override;
219     void releaseBuffer(Proxy::Buffer *buffer) override;
220 
221 private:
222     // This is to use with PatchRecord::writeFrames
223     struct PatchRecordAudioBufferProvider : public AudioBufferProvider {
PatchRecordAudioBufferProviderPatchRecordAudioBufferProvider224         explicit PatchRecordAudioBufferProvider(PassthruPatchRecord& passthru) :
225                 mPassthru(passthru) {}
getNextBufferPatchRecordAudioBufferProvider226         status_t getNextBuffer(AudioBufferProvider::Buffer* buffer) override {
227             return mPassthru.PatchRecord::getNextBuffer(buffer);
228         }
releaseBufferPatchRecordAudioBufferProvider229         void releaseBuffer(AudioBufferProvider::Buffer* buffer) override {
230             return mPassthru.PatchRecord::releaseBuffer(buffer);
231         }
232     private:
233         PassthruPatchRecord& mPassthru;
234     };
235 
236     sp<StreamInHalInterface> obtainStream(sp<ThreadBase>* thread);
237 
238     PatchRecordAudioBufferProvider mPatchRecordAudioBufferProvider;
239     std::unique_ptr<void, decltype(free)*> mSinkBuffer;  // frame size aligned continuous buffer
240     std::unique_ptr<void, decltype(free)*> mStubBuffer;  // buffer used for AudioBufferProvider
241     size_t mUnconsumedFrames = 0;
242     std::mutex mReadLock;
243     std::condition_variable mReadCV;
244     size_t mReadBytes = 0; // GUARDED_BY(mReadLock)
245     status_t mReadError = NO_ERROR; // GUARDED_BY(mReadLock)
246     int64_t mLastReadFrames = 0;  // accessed on RecordThread only
247 };
248