summaryrefslogtreecommitdiff
path: root/LoopbackApp/app/src/main/java/org/drrickorang/loopback/NativeAudioThread.java
blob: da6610ffa32ed7369d49e850becaa19150bf1463 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
/*
 * Copyright (C) 2015 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.drrickorang.loopback;

//import android.content.Context;
//import android.app.Activity;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
//import android.media.MediaPlayer;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.util.Log;

import android.os.Handler;
import  android.os.Message;

/**
 * A thread/audio track based audio synth.
 */
public class NativeAudioThread extends Thread {

    public boolean isRunning = false;
    double twoPi = 6.28318530718;

    public int mSessionId;

    public double[] mvSamples; //captured samples
    int mSamplesIndex;

    private final int mSecondsToRun = 2;
    public int mSamplingRate = 48000;
    private int mChannelConfigIn = AudioFormat.CHANNEL_IN_MONO;
    private int mAudioFormat = AudioFormat.ENCODING_PCM_16BIT;

    int mMinPlayBufferSizeInBytes = 0;
    int mMinRecordBuffSizeInBytes = 0;
    private int mChannelConfigOut = AudioFormat.CHANNEL_OUT_MONO;

    int mMicSource = 0;

//    private double [] samples = new double[50000];

    boolean isPlaying = false;
    private Handler mMessageHandler;
    boolean isDestroying = false;
    boolean hasDestroyingErrors = false;

    static final int FUN_PLUG_NATIVE_AUDIO_THREAD_MESSAGE_REC_STARTED = 892;
    static final int FUN_PLUG_NATIVE_AUDIO_THREAD_MESSAGE_REC_ERROR = 893;
    static final int FUN_PLUG_NATIVE_AUDIO_THREAD_MESSAGE_REC_COMPLETE = 894;
    static final int FUN_PLUG_NATIVE_AUDIO_THREAD_MESSAGE_REC_COMPLETE_ERRORS = 895;

    public void setParams(int samplingRate, int playBufferInBytes, int recBufferInBytes, int micSource) {
        mSamplingRate = samplingRate;

        mMinPlayBufferSizeInBytes = playBufferInBytes;
        mMinRecordBuffSizeInBytes = recBufferInBytes;

        mMicSource = micSource;

    }

    //JNI load
    static {
        try {
            System.loadLibrary("loopback");
        } catch (UnsatisfiedLinkError e) {
            log("Error loading loopback JNI library");
            e.printStackTrace();
        }

        /* TODO: gracefully fail/notify if the library can't be loaded */
    }

    //jni calls
    public native long slesInit(int samplingRate, int frameCount, int micSource);
    public native int slesProcessNext(long sles_data, double[] samples, long offset);
    public native int slesDestroy(long sles_data);

    public void run() {

        setPriority(Thread.MAX_PRIORITY);
        isRunning = true;

        //erase output buffer
        if (mvSamples != null)
            mvSamples = null;

        //resize
        int nNewSize = (int)(1.1* mSamplingRate * mSecondsToRun ); //10% more just in case
        mvSamples = new double[nNewSize];
        mSamplesIndex = 0; //reset index

        //clear samples
        for(int i=0; i<nNewSize; i++) {
            mvSamples[i] = 0;
        }

        //start playing
        isPlaying = true;


        log(" Started capture test");
        if (mMessageHandler != null) {
            Message msg = Message.obtain();
            msg.what = FUN_PLUG_NATIVE_AUDIO_THREAD_MESSAGE_REC_STARTED;
            mMessageHandler.sendMessage(msg);
        }



        log(String.format("about to init, sampling rate: %d, buffer:%d", mSamplingRate,
                mMinPlayBufferSizeInBytes/2 ));
        long sles_data = slesInit(mSamplingRate, mMinPlayBufferSizeInBytes/2, mMicSource);
        log(String.format("sles_data = 0x%X",sles_data));

        if(sles_data == 0 ) {
            //notify error!!

            log(" ERROR at JNI initialization");
            if (mMessageHandler != null) {
                Message msg = Message.obtain();
                msg.what = FUN_PLUG_NATIVE_AUDIO_THREAD_MESSAGE_REC_ERROR;
                mMessageHandler.sendMessage(msg);
            }
        }  else {

            //wait a little bit...
            try {
                sleep(10); //just to let it start properly?
            } catch (InterruptedException e) {
                e.printStackTrace();
            }



            mSamplesIndex = 0;
            int totalSamplesRead = 0;
            long offset = 0;
            for (int ii = 0; ii < mSecondsToRun; ii++) {
                log(String.format("block %d...", ii));
                int samplesRead = slesProcessNext(sles_data, mvSamples,offset);
                totalSamplesRead += samplesRead;

                offset += samplesRead;
                log(" [" + ii + "] jni samples read:" + samplesRead + "  currentOffset:" + offset);

//                log(" [" + ii + "] jni samples read:" + samplesRead + "  currentSampleIndex:" + mSamplesIndex);
//                {
//                    for (int jj = 0; jj < samplesRead && mSamplesIndex < mvSamples.length; jj++) {
//                        mvSamples[mSamplesIndex++] = samples[jj];
//                    }
//                }
            }

            //log(String.format(" samplesRead: %d, samplesIndex:%d", totalSamplesRead, mSamplesIndex));
            log(String.format(" samplesRead: %d, sampleOffset:%d", totalSamplesRead, offset));
            log(String.format("about to destroy..."));
//        int status = slesDestroy(sles_data);
//        log(String.format("sles delete status: %d", status));


            runDestroy(sles_data);

            int maxTry = 20;
            int tryCount = 0;
            //isDestroying = true;
            while (isDestroying) {

                try {
                    sleep(40);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                tryCount++;

                log("destroy try: " + tryCount);

                if (tryCount >= maxTry) {
                    hasDestroyingErrors = true;
                    log("WARNING: waited for max time to properly destroy JNI.");
                    break;
                }
            }
            log(String.format("after destroying. TotalSamplesRead = %d", totalSamplesRead));

            if(totalSamplesRead==0)
            {
                hasDestroyingErrors = true;
            }

            endTest();
        }
    }

    public void setMessageHandler(Handler messageHandler) {
        mMessageHandler = messageHandler;
    }

    private void runDestroy(final long sles_data ) {
        isDestroying = true;

        //start thread

        final long local_sles_data = sles_data;
        ////
        Thread thread = new Thread(new Runnable() {
            public void run() {
                isDestroying = true;
                log("**Start runnable destroy");

                int status = slesDestroy(local_sles_data);
                log(String.format("**End runnable destroy sles delete status: %d", status));
                isDestroying = false;
            }
        });

        thread.start();



        log("end of runDestroy()");


    }

    public void togglePlay() {

    }

    public void runTest() {


    }

   public void endTest() {
       log("--Ending capture test--");
       isPlaying = false;


       if (mMessageHandler != null) {
           Message msg = Message.obtain();
           if(hasDestroyingErrors)
               msg.what = FUN_PLUG_NATIVE_AUDIO_THREAD_MESSAGE_REC_COMPLETE_ERRORS;
           else
               msg.what = FUN_PLUG_NATIVE_AUDIO_THREAD_MESSAGE_REC_COMPLETE;
           mMessageHandler.sendMessage(msg);
       }

   }

    public void finish() {

        if (isRunning) {
            isRunning = false;
            try {
                sleep(20);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private static void log(String msg) {
        Log.v("Loopback", msg);
    }

    double [] getWaveData () {
        return mvSamples;
    }

}  //end thread.