1/*
2 * Copyright (C) 2016 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
17package org.drrickorang.loopback;
18
19import android.content.Context;
20import android.media.AudioManager;
21import android.os.Handler;
22import android.os.Looper;
23import android.util.Log;
24
25class SoundLevelCalibration {
26    private static final int SECONDS_PER_LEVEL = 1;
27    private static final int MAX_STEPS = 15; // The maximum number of levels that should be tried
28    private static final double CRITICAL_RATIO = 0.41; // Ratio of input over output amplitude at
29                                                      // which the feedback loop neither decays nor
30                                                      // grows (determined experimentally)
31    private static final String TAG = "SoundLevelCalibration";
32
33    private NativeAudioThread mNativeAudioThread = null;
34    private AudioManager mAudioManager;
35
36    private SoundLevelChangeListener mChangeListener;
37
38    abstract static class SoundLevelChangeListener {
39        // used to run the callback on the UI thread
40        private Handler handler = new Handler(Looper.getMainLooper());
41
42        abstract void onChange(int newLevel);
43
44        private void go(final int newLevel) {
45            handler.post(new Runnable() {
46                @Override
47                public void run() {
48                    onChange(newLevel);
49                }
50            });
51        }
52    }
53
54    SoundLevelCalibration(int samplingRate, int playerBufferSizeInBytes,
55                                 int recorderBufferSizeInBytes, int micSource, int performanceMode, Context context) {
56
57        // TODO: Allow capturing wave data without doing glitch detection.
58        CaptureHolder captureHolder = new CaptureHolder(0, "", false, false, false, context,
59                samplingRate);
60        // TODO: Run for less than 1 second.
61        mNativeAudioThread = new NativeAudioThread(samplingRate, playerBufferSizeInBytes,
62                recorderBufferSizeInBytes, micSource, performanceMode,
63                Constant.LOOPBACK_PLUG_AUDIO_THREAD_TEST_TYPE_BUFFER_PERIOD, SECONDS_PER_LEVEL,
64                SECONDS_PER_LEVEL, 0, captureHolder);
65        mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
66    }
67
68    // TODO: Allow stopping in the middle of calibration
69    int calibrate() {
70        final int maxLevel = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
71        int levelBottom = 0;
72        int levelTop = maxLevel + 1;
73        while(levelTop - levelBottom > 1) {
74            int level = (levelBottom + levelTop) / 2;
75            Log.d(TAG, "setting level to " + level);
76            setVolume(level);
77
78            double amplitude = runAudioThread(mNativeAudioThread);
79            mNativeAudioThread = new NativeAudioThread(mNativeAudioThread); // generate fresh thread
80            Log.d(TAG, "calibrate: at sound level " + level + " volume was " + amplitude);
81
82            if (amplitude < Constant.SINE_WAVE_AMPLITUDE * CRITICAL_RATIO) {
83                levelBottom = level;
84            } else {
85                levelTop = level;
86            }
87        }
88        // At this point, levelBottom has the highest proper value, if there is one (0 otherwise)
89        Log.d(TAG, "Final level: " + levelBottom);
90        setVolume(levelBottom);
91        return levelBottom;
92    }
93
94    private double runAudioThread(NativeAudioThread thread) {
95        // runs the native audio thread and returns the average amplitude
96        thread.start();
97        try {
98            thread.join();
99        } catch (InterruptedException e) {
100            e.printStackTrace();
101        }
102        double[] data = thread.getWaveData();
103        return averageAmplitude(data);
104    }
105
106    // TODO: Only gives accurate results for an undistorted sine wave. Check for distortion.
107    private static double averageAmplitude(double[] data) {
108        if (data == null || data.length == 0) {
109            return 0; // no data is present
110        }
111        double sumSquare = 0;
112        for (double x : data) {
113            sumSquare += x * x;
114        }
115        return Math.sqrt(2.0 * sumSquare / data.length); // amplitude of the sine wave
116    }
117
118    private void setVolume(int level) {
119        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, level, 0);
120        if (mChangeListener != null) {
121            mChangeListener.go(level);
122        }
123    }
124
125    void setChangeListener(SoundLevelChangeListener changeListener) {
126        mChangeListener = changeListener;
127    }
128}
129