1 /*
2  * Copyright (C) 2010 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 #ifndef ANDROID_MEDIA_VISUALIZER_H
18 #define ANDROID_MEDIA_VISUALIZER_H
19 
20 #include <media/AudioEffect.h>
21 #include <system/audio_effects/effect_visualizer.h>
22 #include <utils/Thread.h>
23 #include <cstdint>
24 #include <cutils/bitops.h>
25 #include "android/content/AttributionSourceState.h"
26 
27 /**
28  * The Visualizer class enables application to retrieve part of the currently playing audio for
29  * visualization purpose. It is not an audio recording interface and only returns partial and low
30  * quality audio content. However, to protect privacy of certain audio data (e.g voice mail) the use
31  * of the visualizer requires the permission android.permission.RECORD_AUDIO.
32  * The audio session ID passed to the constructor indicates which audio content should be
33  * visualized:
34  * - If the session is 0, the audio output mix is visualized
35  * - If the session is not 0, the audio from a particular MediaPlayer or AudioTrack
36  *   using this audio session is visualized
37  * Two types of representation of audio content can be captured:
38  * - Waveform data: consecutive 8-bit (unsigned) mono samples by using the getWaveForm() method
39  * - Frequency data: 8-bit magnitude FFT by using the getFft() method
40  *
41  * The length of the capture can be retrieved or specified by calling respectively
42  * getCaptureSize() and setCaptureSize() methods. Note that the size of the FFT
43  * is half of the specified capture size but both sides of the spectrum are returned yielding in a
44  * number of bytes equal to the capture size. The capture size must be a power of 2 in the range
45  * returned by getMinCaptureSize() and getMaxCaptureSize().
46  * In addition to the polling capture mode, a callback mode is also available by installing a
47  * callback function by use of the setCaptureCallBack() method. The rate at which the callback
48  * is called as well as the type of data returned is specified.
49  * Before capturing data, the Visualizer must be enabled by calling the setEnabled() method.
50  * When data capture is not needed any more, the Visualizer should be disabled.
51  */
52 
53 
54 namespace android {
55 
56 // ----------------------------------------------------------------------------
57 
58 class Visualizer: public AudioEffect {
59 public:
60 
61     enum callback_flags {
62         CAPTURE_WAVEFORM = 0x00000001,  // capture callback returns a PCM wave form
63         CAPTURE_FFT = 0x00000002,       // apture callback returns a frequency representation
64         CAPTURE_CALL_JAVA = 0x00000004  // the callback thread can call java
65     };
66 
67 
68     /* Constructor.
69      * See AudioEffect constructor for details on parameters.
70      */
71      explicit Visualizer(const android::content::AttributionSourceState& attributionSource);
72 
73      ~Visualizer();
74 
75     /**
76      * Initialize an uninitialized Visualizer.
77      * See AudioEffect 'set' function for details on parameters.
78      */
79     status_t    set(int32_t priority = 0,
80                     legacy_callback_t cbf = nullptr,
81                     void* user = nullptr,
82                     audio_session_t sessionId = AUDIO_SESSION_OUTPUT_MIX,
83                     audio_io_handle_t io = AUDIO_IO_HANDLE_NONE,
84                     const AudioDeviceTypeAddr& device = {},
85                     bool probe = false);
86 
87     // Declared 'final' because we call this in ~Visualizer().
88     status_t    setEnabled(bool enabled) final;
89 
90     // maximum capture size in samples
getMaxCaptureSize()91     static uint32_t getMaxCaptureSize() { return VISUALIZER_CAPTURE_SIZE_MAX; }
92     // minimum capture size in samples
getMinCaptureSize()93     static uint32_t getMinCaptureSize() { return VISUALIZER_CAPTURE_SIZE_MIN; }
94     // maximum capture rate in millihertz
getMaxCaptureRate()95     static uint32_t getMaxCaptureRate() { return CAPTURE_RATE_MAX; }
96 
97     // callback used to return periodic PCM or FFT captures to the application. Either one or both
98     // types of data are returned (PCM and FFT) according to flags indicated when installing the
99     // callback. When a type of data is not present, the corresponding size (waveformSize or
100     // fftSize) is 0.
101     typedef void (*capture_cbk_t)(void* user,
102                                     uint32_t waveformSize,
103                                     uint8_t *waveform,
104                                     uint32_t fftSize,
105                                     uint8_t *fft,
106                                     uint32_t samplingrate);
107 
108     // install a callback to receive periodic captures. The capture rate is specified in milliHertz
109     // and the capture format is according to flags  (see callback_flags).
110     status_t setCaptureCallBack(capture_cbk_t cbk, void* user, uint32_t flags, uint32_t rate);
111 
112     // set the capture size capture size must be a power of two in the range
113     // [VISUALIZER_CAPTURE_SIZE_MAX. VISUALIZER_CAPTURE_SIZE_MIN]
114     // must be called when the visualizer is not enabled
115     status_t setCaptureSize(uint32_t size);
getCaptureSize()116     uint32_t getCaptureSize() { return mCaptureSize; }
117 
118     // returns the capture rate indicated when installing the callback
getCaptureRate()119     uint32_t getCaptureRate() { return mCaptureRate; }
120 
121     // returns the sampling rate of the audio being captured
getSamplingRate()122     uint32_t getSamplingRate() { return mSampleRate; }
123 
124     // set the way volume affects the captured data
125     // mode must one of VISUALIZER_SCALING_MODE_NORMALIZED,
126     //  VISUALIZER_SCALING_MODE_AS_PLAYED
127     status_t setScalingMode(uint32_t mode);
getScalingMode()128     uint32_t getScalingMode() { return mScalingMode; }
129 
130     // set which measurements are done on the audio buffers processed by the effect.
131     // valid measurements (mask): MEASUREMENT_MODE_PEAK_RMS
132     status_t setMeasurementMode(uint32_t mode);
getMeasurementMode()133     uint32_t getMeasurementMode() { return mMeasurementMode; }
134 
135     // return a set of int32_t measurements
136     status_t getIntMeasurements(uint32_t type, uint32_t number, int32_t *measurements);
137 
138     // return a capture in PCM 8 bit unsigned format. The size of the capture is equal to
139     // getCaptureSize()
140     status_t getWaveForm(uint8_t *waveform);
141 
142     // return a capture in FFT 8 bit signed format. The size of the capture is equal to
143     // getCaptureSize() but the length of the FFT is half of the size (both parts of the spectrum
144     // are returned
145     status_t getFft(uint8_t *fft);
146     void release();
147 
148 protected:
149     // from IEffectClient
150     virtual void controlStatusChanged(bool controlGranted);
151 
152 private:
153 
154     static const uint32_t CAPTURE_RATE_MAX = 20000;
155     static const uint32_t CAPTURE_RATE_DEF = 10000;
156     static const uint32_t CAPTURE_SIZE_DEF = VISUALIZER_CAPTURE_SIZE_MAX;
157 
158     /* internal class to handle the callback */
159     class CaptureThread : public Thread
160     {
161     public:
162         CaptureThread(const sp<Visualizer>& visualizer,
163                 uint32_t captureRate, bool bCanCallJava = false);
164 
165     private:
166         friend class Visualizer;
167         virtual bool        threadLoop();
168         wp<Visualizer> mReceiver;
169         Mutex       mLock;
170         uint32_t mSleepTimeUs;
171     };
172 
173     status_t doFft(uint8_t *fft, uint8_t *waveform);
174     void periodicCapture();
175     status_t initCaptureSize();
176     void initSampleRate();
isCaptureSizeValid(uint32_t size)177     static constexpr bool isCaptureSizeValid(uint32_t size) {
178         return size <= VISUALIZER_CAPTURE_SIZE_MAX && size >= VISUALIZER_CAPTURE_SIZE_MIN &&
179                 popcount(size) == 1;
180     }
181 
182     Mutex mCaptureLock;
183     uint32_t mCaptureRate = CAPTURE_RATE_DEF;
184     uint32_t mCaptureSize = CAPTURE_SIZE_DEF;
185     uint32_t mSampleRate = 44100000;
186     uint32_t mScalingMode = VISUALIZER_SCALING_MODE_NORMALIZED;
187     uint32_t mMeasurementMode = MEASUREMENT_MODE_NONE;
188     capture_cbk_t mCaptureCallBack = nullptr;
189     void *mCaptureCbkUser = nullptr;
190     sp<CaptureThread> mCaptureThread;
191     uint32_t mCaptureFlags = 0;
192 };
193 
194 
195 }; // namespace android
196 
197 #endif // ANDROID_MEDIA_VISUALIZER_H
198