1 /*
2  * Copyright (C) 2008 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_TONEGENERATOR_H_
18 #define ANDROID_TONEGENERATOR_H_
19 
20 #include <string>
21 
22 #include <media/AudioSystem.h>
23 #include <media/AudioTrack.h>
24 #include <utils/Compat.h>
25 #include <utils/KeyedVector.h>
26 #include <utils/RefBase.h>
27 #include <utils/threads.h>
28 
29 namespace android {
30 
31 class ToneGenerator : public AudioTrack::IAudioTrackCallback {
32 public:
33 
34     // List of all available tones
35     // This enum must be kept consistant with constants in ToneGenerator JAVA class
36     enum tone_type {
37         // DTMF tones  ITU-T Recommendation Q.23
38         TONE_DTMF_0 = 0,  // 0 key: 1336Hz, 941Hz
39         TONE_DTMF_1,  // 1 key: 1209Hz, 697Hz
40         TONE_DTMF_2,  // 2 key: 1336Hz, 697Hz
41         TONE_DTMF_3,  // 3 key: 1477Hz, 697Hz
42         TONE_DTMF_4,  // 4 key: 1209Hz, 770Hz
43         TONE_DTMF_5,  // 5 key: 1336Hz, 770Hz
44         TONE_DTMF_6,  // 6 key: 1477Hz, 770Hz
45         TONE_DTMF_7,  // 7 key: 1209Hz, 852Hz
46         TONE_DTMF_8,  // 8 key: 1336Hz, 852Hz
47         TONE_DTMF_9,  // 9 key: 1477Hz, 852Hz
48         TONE_DTMF_S,  // * key: 1209Hz, 941Hz
49         TONE_DTMF_P,  // # key: 1477Hz, 941Hz
50         TONE_DTMF_A,  // A key: 1633Hz, 697Hz
51         TONE_DTMF_B,  // B key: 1633Hz, 770Hz
52         TONE_DTMF_C,  // C key: 1633Hz, 852Hz
53         TONE_DTMF_D,  // D key: 1633Hz, 941Hz
54         // Call supervisory tones:  3GPP TS 22.001 (CEPT)
55         TONE_SUP_DIAL,  // Dial tone: CEPT: 425Hz, continuous
56         FIRST_SUP_TONE = TONE_SUP_DIAL,
57         TONE_SUP_BUSY,  // Busy tone, CEPT: 425Hz, 500ms ON, 500ms OFF...
58         TONE_SUP_CONGESTION,  // Congestion tone CEPT, JAPAN: 425Hz, 200ms ON, 200ms OFF...
59         TONE_SUP_RADIO_ACK,  // Radio path acknowlegment, CEPT, ANSI: 425Hz, 200ms ON
60         TONE_SUP_RADIO_NOTAVAIL,  // Radio path not available: 425Hz, 200ms ON, 200 OFF 3 bursts
61         TONE_SUP_ERROR,  // Error/Special info:  950Hz+1400Hz+1800Hz, 330ms ON, 1s OFF...
62         TONE_SUP_CALL_WAITING,  // Call Waiting CEPT,JAPAN:  425Hz, 200ms ON, 600ms OFF, 200ms ON, 3s OFF...
63         TONE_SUP_RINGTONE,  // Ring Tone CEPT, JAPAN:  425Hz, 1s ON, 4s OFF...
64         LAST_SUP_TONE = TONE_SUP_RINGTONE,
65         // Proprietary tones:  3GPP TS 31.111
66         TONE_PROP_BEEP,  // General beep: 400Hz+1200Hz, 35ms ON
67         TONE_PROP_ACK,  // Positive Acknowlgement: 1200Hz, 100ms ON, 100ms OFF 2 bursts
68         TONE_PROP_NACK,  // Negative Acknowlgement: 300Hz+400Hz+500Hz, 400ms ON
69         TONE_PROP_PROMPT,  // Prompt tone: 400Hz+1200Hz, 200ms ON
70         TONE_PROP_BEEP2,  // General double beep: 400Hz+1200Hz, 35ms ON, 200ms OFF, 35ms on
71         // Additional call supervisory tones: specified by IS-95 only
72         TONE_SUP_INTERCEPT, // Intercept tone: alternating 440 Hz and 620 Hz tones, each on for 250 ms.
73         TONE_SUP_INTERCEPT_ABBREV, // Abbreviated intercept: intercept tone limited to 4 seconds
74         TONE_SUP_CONGESTION_ABBREV, // Abbreviated congestion: congestion tone limited to 4 seconds
75         TONE_SUP_CONFIRM, // Confirm tone: a 350 Hz tone added to a 440 Hz tone repeated 3 times in a 100 ms on, 100 ms off cycle.
76         TONE_SUP_PIP, // Pip tone: four bursts of 480 Hz tone (0.1 s on, 0.1 s off).
77 
78         // CDMA Tones
79         TONE_CDMA_DIAL_TONE_LITE,
80         TONE_CDMA_NETWORK_USA_RINGBACK,
81         TONE_CDMA_INTERCEPT,
82         TONE_CDMA_ABBR_INTERCEPT,
83         TONE_CDMA_REORDER,
84         TONE_CDMA_ABBR_REORDER,
85         TONE_CDMA_NETWORK_BUSY,
86         TONE_CDMA_CONFIRM,
87         TONE_CDMA_ANSWER,
88         TONE_CDMA_NETWORK_CALLWAITING,
89         TONE_CDMA_PIP,
90 
91         // ISDN
92         TONE_CDMA_CALL_SIGNAL_ISDN_NORMAL,  // ISDN Alert Normal
93         TONE_CDMA_CALL_SIGNAL_ISDN_INTERGROUP, // ISDN Intergroup
94         TONE_CDMA_CALL_SIGNAL_ISDN_SP_PRI, // ISDN SP PRI
95         TONE_CDMA_CALL_SIGNAL_ISDN_PAT3,  // ISDN Alert PAT3
96         TONE_CDMA_CALL_SIGNAL_ISDN_PING_RING, // ISDN Alert PING RING
97         TONE_CDMA_CALL_SIGNAL_ISDN_PAT5,  // ISDN Alert PAT5
98         TONE_CDMA_CALL_SIGNAL_ISDN_PAT6,  // ISDN Alert PAT6
99         TONE_CDMA_CALL_SIGNAL_ISDN_PAT7,  // ISDN Alert PAT7
100         // ISDN end
101 
102         // IS54
103         TONE_CDMA_HIGH_L,  // IS54 High Pitch Long
104         TONE_CDMA_MED_L, // IS54 Med Pitch Long
105         TONE_CDMA_LOW_L, // IS54 Low Pitch Long
106         TONE_CDMA_HIGH_SS, // IS54 High Pitch Short Short
107         TONE_CDMA_MED_SS, // IS54 Medium Pitch Short Short
108         TONE_CDMA_LOW_SS, // IS54 Low Pitch Short Short
109         TONE_CDMA_HIGH_SSL, // IS54 High Pitch Short Short Long
110         TONE_CDMA_MED_SSL, // IS54 Medium  Pitch Short Short Long
111         TONE_CDMA_LOW_SSL, // IS54 Low  Pitch Short Short Long
112         TONE_CDMA_HIGH_SS_2, // IS54 High Pitch Short Short 2
113         TONE_CDMA_MED_SS_2, // IS54 Med Pitch Short Short 2
114         TONE_CDMA_LOW_SS_2, // IS54 Low  Pitch Short Short 2
115         TONE_CDMA_HIGH_SLS, // IS54 High Pitch Short Long Short
116         TONE_CDMA_MED_SLS, // IS54 Med Pitch Short Long Short
117         TONE_CDMA_LOW_SLS, // IS54 Low Pitch Short Long Short
118         TONE_CDMA_HIGH_S_X4, // IS54 High Pitch Short Short Short Short
119         TONE_CDMA_MED_S_X4, // IS54 Med Pitch Short Short Short Short
120         TONE_CDMA_LOW_S_X4, // IS54 Low Pitch Short Short Short Short
121         TONE_CDMA_HIGH_PBX_L, // PBX High Pitch Long
122         TONE_CDMA_MED_PBX_L, // PBX Med Pitch Long
123         TONE_CDMA_LOW_PBX_L, // PBX Low  Pitch Long
124         TONE_CDMA_HIGH_PBX_SS, // PBX High Short Short
125         TONE_CDMA_MED_PBX_SS, // PBX Med Short Short
126         TONE_CDMA_LOW_PBX_SS, // PBX Low  Short Short
127         TONE_CDMA_HIGH_PBX_SSL, // PBX High Short Short Long
128         TONE_CDMA_MED_PBX_SSL, // PBX Med Short Short Long
129         TONE_CDMA_LOW_PBX_SSL,  // PBX Low Short Short Long
130         TONE_CDMA_HIGH_PBX_SLS, // PBX High  SLS
131         TONE_CDMA_MED_PBX_SLS,  // PBX Med SLS
132         TONE_CDMA_LOW_PBX_SLS, // PBX Low SLS
133         TONE_CDMA_HIGH_PBX_S_X4, // PBX High SSSS
134         TONE_CDMA_MED_PBX_S_X4, // PBX Med SSSS
135         TONE_CDMA_LOW_PBX_S_X4, // PBX LOW SSSS
136         //IS54 end
137         // proprietary
138         TONE_CDMA_ALERT_NETWORK_LITE,
139         TONE_CDMA_ALERT_AUTOREDIAL_LITE,
140         TONE_CDMA_ONE_MIN_BEEP,
141         TONE_CDMA_KEYPAD_VOLUME_KEY_LITE,
142         TONE_CDMA_PRESSHOLDKEY_LITE,
143         TONE_CDMA_ALERT_INCALL_LITE,
144         TONE_CDMA_EMERGENCY_RINGBACK,
145         TONE_CDMA_ALERT_CALL_GUARD,
146         TONE_CDMA_SOFT_ERROR_LITE,
147         TONE_CDMA_CALLDROP_LITE,
148         // proprietary end
149         TONE_CDMA_NETWORK_BUSY_ONE_SHOT,
150         TONE_CDMA_ABBR_ALERT,
151         TONE_CDMA_SIGNAL_OFF,
152         //CDMA end
153         NUM_TONES,
154         NUM_SUP_TONES = LAST_SUP_TONE-FIRST_SUP_TONE+1
155     };
156 
157     ToneGenerator(audio_stream_type_t streamType, float volume, bool threadCanCallJava = false,
158             std::string opPackageName = {});
159 
160     void onFirstRef() override;
161 
162     ~ToneGenerator();
163 
164     bool startTone(tone_type toneType, int durationMs = -1);
165     void stopTone();
166 
isInited()167     bool isInited() { return (mState == TONE_IDLE)?false:true;}
168 
169     // returns the audio session this ToneGenerator belongs to or 0 if an error occured.
getSessionId()170     int getSessionId() { return (mpAudioTrack == 0) ? 0 : mpAudioTrack->getSessionId(); }
171 
172 private:
173 
174     enum tone_state {
175         TONE_IDLE,  // ToneGenerator is being initialized or initialization failed
176         TONE_INIT,  // ToneGenerator has been successfully initialized and is not playing
177         TONE_STARTING,  // ToneGenerator is starting playing
178         TONE_PLAYING,  // ToneGenerator is playing
179         TONE_STOPPING,  // ToneGenerator is stoping
180         TONE_STOPPED,  // ToneGenerator is stopped: the AudioTrack will be stopped
181         TONE_RESTARTING  // A start request was received in active state (playing or stopping)
182     };
183 
184 
185     // Region specific tones.
186     // These supervisory tones are different depending on the region (USA/CANADA, JAPAN, Singapore, Hong Kong, rest of the world).
187     // When a tone in the range [FIRST_SUP_TONE, LAST_SUP_TONE] is requested, the region is determined
188     // from system property gsm.operator.iso-country and the proper tone descriptor is selected with the
189     // help of sToneMappingTable[]
190     enum regional_tone_type {
191         // ANSI supervisory tones
192         TONE_ANSI_DIAL = NUM_TONES, // Dial tone: a continuous 350 Hz + 440 Hz tone.
193         TONE_ANSI_BUSY,             // Busy tone on:  a 480 Hz + 620 Hz tone repeated in a 500 ms on, 500 ms off cycle.
194         TONE_ANSI_CONGESTION,       // Network congestion (reorder) tone on:  a 480 Hz + 620 Hz tone repeated in a 250 ms on, 250 ms off cycle.
195         TONE_ANSI_CALL_WAITING,     // Call waiting tone on: 440 Hz, on for 300 ms, 9,7 s off followed by
196                                     // (440 Hz, on for 100 ms off for 100 ms, on for 100 ms, 9,7s off and repeated as necessary).
197         TONE_ANSI_RINGTONE,         // Ring Tone:  a 440 Hz + 480 Hz tone repeated in a 2 s on, 4 s off pattern.
198         // JAPAN Supervisory tones
199         TONE_JAPAN_DIAL,            // Dial tone: 400Hz, continuous
200         TONE_JAPAN_BUSY,            // Busy tone: 400Hz, 500ms ON, 500ms OFF...
201         TONE_JAPAN_RADIO_ACK,       // Radio path acknowlegment: 400Hz, 1s ON, 2s OFF...
202         TONE_JAPAN_RINGTONE,        // Ring Tone: 400 Hz repeated in a 1 s on, 2 s off pattern.
203         // GB Supervisory tones
204         TONE_GB_BUSY,               // Busy tone: 400 Hz, 375ms ON, 375ms OFF...
205         TONE_GB_CONGESTION,         // Congestion Tone: 400 Hz, 400ms ON, 350ms OFF, 225ms ON, 525ms OFF...
206         TONE_GB_RINGTONE,           // Ring Tone: A 400Hz + 450Hz tone repeated in a 0.4s on, 0.2s off, 0.4s on, 2.0s off pattern.
207         // AUSTRALIA Supervisory tones
208         TONE_AUSTRALIA_DIAL,        // Dial tone: 425 Hz tone modulated with 25 Hz, continuous
209         TONE_AUSTRALIA_RINGTONE,    // Ring tone: A 400Hz + 450Hz tone repeated in a 0.4s on, 0.2s off, 0.4s on, 2.0s off pattern.
210         TONE_AUSTRALIA_BUSY,        // Busy tone: 425 Hz repeated in a 0.375s on, 0.375s off pattern.
211         TONE_AUSTRALIA_CALL_WAITING,// Call waiting tone: 425Hz tone repeated in a 0.2s on, 0.2s off, 0.2s on, 4.4s off pattern.
212         TONE_AUSTRALIA_CONGESTION,  // Congestion tone: 425Hz tone repeated in a 0.375s on, 0.375s off pattern
213         // SINGAPORE Supervisory tones
214         TONE_SG_BUSY,               // Busy tone: 425 Hz, 750ms ON, 750ms OFF...
215         TONE_SG_RINGTONE,           // Ring Tone: 425 Hz tone modulated with 24 Hz, 400ms ON, 200ms OFF, 400ms ON, 2s OFF...
216         // HONG KONG Supervisory tones
217         TONE_HK_BUSY,               // Busy tone: 480 Hz + 620 Hz, 500ms ON, 500ms OFF...
218         TONE_HK_RINGTONE,           // Ring Tone: 440 Hz + 480 Hz repeated with pattern 0,4s on, 0,2s off, 0,4s on and 3s off.
219         // IRELAND Supervisory tones
220         TONE_IE_RINGTONE,           // Ring Tone: A 400Hz + 450Hz tone repeated in a 0.4s on, 0.2s off, 0.4s on, 2.0s off pattern.
221         TONE_IE_CALL_WAITING,       // Call waiting tone: 425Hz tone repeated in a 0.18s on, 0.2s off, 0.2s on, 4.5s off pattern.
222         // INDIA supervisory tones
223         TONE_INDIA_DIAL,            // Dial tone: 400 Hz tone modulated with 25Hz, continuous
224         TONE_INDIA_BUSY,            // Busy tone: 400 Hz, 750ms ON, 750ms OFF...
225         TONE_INDIA_CONGESTION,      // Congestion tone: 400 Hz, 250ms ON, 250ms OFF...
226         TONE_INDIA_CALL_WAITING,    // Call waiting tone: 400 Hz, tone repeated in a 0.2s on, 0.1s off, 0.2s on, 7.5s off pattern.
227         TONE_INDIA_RINGTONE,        // Ring tone: 400 Hz tone modulated with 25Hz, 0.4 on 0.2 off 0.4 on 2..0 off
228         // TAIWAN supervisory tones
229         TONE_TW_RINGTONE,           // Ring Tone: 440 Hz + 480 Hz repeated with pattern 1s on, 3s off.
230         // NEW ZEALAND supervisory tones
231         TONE_NZ_CALL_WAITING,       // Call waiting tone: 400 Hz,  0.2s ON, 3s OFF,
232                                     //        0.2s ON, 3s OFF, 0.2s ON, 3s OFF, 0.2s ON
233         // MALAYSIA supervisory tones
234         TONE_MY_CONGESTION,         // Congestion tone: 425 Hz, 500ms ON, 250ms OFF...
235         TONE_MY_RINGTONE,           // Ring tone: 425 Hz, 400ms ON 200ms OFF 400ms ON 2s OFF..
236         NUM_ALTERNATE_TONES
237     };
238 
239     enum region {
240         ANSI,
241         JAPAN,
242         GB,
243         AUSTRALIA,
244         SINGAPORE,
245         HONGKONG,
246         IRELAND,
247         INDIA,
248         TAIWAN,
249         NZ,
250         MY,
251         CEPT,
252         NUM_REGIONS
253     };
254 
255     static const unsigned char sToneMappingTable[NUM_REGIONS-1][NUM_SUP_TONES];
256 
257     static const unsigned int TONEGEN_MAX_WAVES = 3;     // Maximun number of sine waves in a tone segment
258     static const unsigned int TONEGEN_MAX_SEGMENTS = 12;  // Maximun number of segments in a tone descriptor
259     static const unsigned int TONEGEN_INF = 0xFFFFFFFF;  // Represents infinite time duration
260     static const CONSTEXPR float TONEGEN_GAIN = 0.9;  // Default gain passed to  WaveGenerator().
261 
262     // ToneDescriptor class contains all parameters needed to generate a tone:
263     //    - The array waveFreq[]:
264     //         1 for static tone descriptors: contains the frequencies of all individual waves making the multi-tone.
265     //         2 for active tone descritors: contains the indexes of the WaveGenerator objects in mWaveGens
266     //        The number of sine waves varies from 1 to TONEGEN_MAX_WAVES.
267     //        The first null value indicates that no more waves are needed.
268     //    - The array segments[] is used to generate the tone pulses. A segment is a period of time
269     //        during which the tone is ON or OFF.    Segments with even index (starting from 0)
270     //        correspond to tone ON state and segments with odd index to OFF state.
271     //        The data stored in segments[] is the duration of the corresponding period in ms.
272     //        The first segment encountered with a 0 duration    indicates that no more segment follows.
273     //    - loopCnt - Number of times to repeat a sequence of seqments after playing this
274     //    - loopIndx - The segment index to go back and play is loopcnt > 0
275     //    - repeatCnt indicates the number of times the sequence described by segments[] array must be repeated.
276     //        When the tone generator encounters the first 0 duration segment, it will compare repeatCnt to mCurCount.
277     //        If mCurCount > repeatCnt, the tone is stopped automatically. Otherwise, tone sequence will be
278     //        restarted from segment repeatSegment.
279     //    - repeatSegment number of the first repeated segment when repeatCnt is not null
280 
281     class ToneSegment {
282     public:
283         unsigned int duration;
284         uint16_t waveFreq[TONEGEN_MAX_WAVES+1];
285         uint16_t loopCnt;
286         uint16_t loopIndx;
287     };
288 
289     class ToneDescriptor {
290     public:
291         ToneSegment segments[TONEGEN_MAX_SEGMENTS+1];
292         unsigned long repeatCnt;
293         unsigned long repeatSegment;
294     };
295 
296     static const ToneDescriptor sToneDescriptors[];
297 
298     bool mThreadCanCallJava;
299     uint64_t mTotalSmp;  // Total number of audio samples played (gives current time)
300     // Since these types are 32 bit, we may have issues with aborting on
301     // overflow now that we have integer overflow sanitization enabled globally.
302     unsigned int mNextSegSmp;  // Position of next segment transition expressed in samples
303     unsigned int mMaxSmp;  // Maximum number of audio samples played (maximun tone duration)
304     int mDurationMs;  // Maximum tone duration in ms
305 
306     uint16_t mCurSegment;  // Current segment index in ToneDescriptor segments[]
307     uint16_t mCurCount;  // Current sequence repeat count
308     volatile uint16_t mState;  // ToneGenerator state (tone_state)
309     uint16_t mRegion;
310     const ToneDescriptor *mpToneDesc;  // pointer to active tone descriptor
311     const ToneDescriptor *mpNewToneDesc;  // pointer to next active tone descriptor
312 
313     uint16_t mLoopCounter; // Current tone loopback count
314 
315     uint32_t mSamplingRate;  // AudioFlinger Sampling rate
316     sp<AudioTrack> mpAudioTrack;  // Pointer to audio track used for playback
317     Mutex mLock;  // Mutex to control concurent access to ToneGenerator object from audio callback and application API
318     Mutex mCbkCondLock; // Mutex associated to mWaitCbkCond
319     Condition mWaitCbkCond; // condition enabling interface to wait for audio callback completion after a change is requested
320     float mVolume;  // Volume applied to audio track
321     audio_stream_type_t mStreamType; // Audio stream used for output
322     unsigned int mProcessSize;  // Size of audio blocks generated at a time by audioCallback() (in PCM frames).
323     struct timespec mStartTime; // tone start time: needed to guaranty actual tone duration
324 
325     size_t onMoreData(const AudioTrack::Buffer& buffer) override;
326     bool initAudioTrack();
327     static void audioCallback(int event, void* user, void *info);
328     bool prepareWave();
329     unsigned int numWaves(unsigned int segmentIdx);
330     void clearWaveGens();
331     tone_type getToneForRegion(tone_type toneType);
332 
333     // WaveGenerator generates a single sine wave
334     class WaveGenerator {
335     public:
336         enum gen_command {
337             WAVEGEN_START,  // Start/restart wave from phase 0
338             WAVEGEN_CONT,  // Continue wave from current phase
339             WAVEGEN_STOP  // Stop wave on zero crossing
340         };
341 
342         WaveGenerator(uint32_t samplingRate, uint16_t frequency,
343                 float volume);
344         ~WaveGenerator();
345 
346         void getSamples(int16_t *outBuffer, unsigned int count,
347                 unsigned int command);
348 
349     private:
350         static const int16_t GEN_AMP = 32000;  // amplitude of generator
351         static const int16_t S_Q14 = 14;  // shift for Q14
352         static const int16_t S_Q15 = 15;  // shift for Q15
353 
354         int16_t mA1_Q14;  // Q14 coefficient
355         // delay line of full amplitude generator
356         long mS1, mS2;  // delay line S2 oldest
357         int16_t mS2_0;  // saved value for reinitialisation
358         int16_t mAmplitude_Q15;  // Q15 amplitude
359     };
360 
361     KeyedVector<uint16_t, WaveGenerator *> mWaveGens;  // list of active wave generators.
362 
363     std::string mOpPackageName;
364 };
365 
366 }
367 ;  // namespace android
368 
369 #endif /*ANDROID_TONEGENERATOR_H_*/
370