aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/com/jsyn/io/AudioFifo.java
blob: 5a87643178fe040b25390944310fb6fd4989131a (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
/*
 * Copyright 2010 Phil Burk, Mobileer Inc
 *
 * 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 com.jsyn.io;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * FIFO that implements AudioInputStream, AudioOutputStream interfaces. This can be used to send
 * audio data between different threads. The reads or writes may or may not wait based on flags.
 *
 * @author Phil Burk (C) 2010 Mobileer Inc
 */
public class AudioFifo implements AudioInputStream, AudioOutputStream {
    // These indices run double the FIFO size so that we can tell empty from full.
    private volatile int readIndex;
    private volatile int writeIndex;
    private volatile double[] buffer;
    // Used to mask the index into range when accessing the buffer array.
    private int accessMask;
    // Used to mask the index so it wraps around.
    private int sizeMask;
    private boolean writeWaitEnabled = true;
    private boolean readWaitEnabled = true;
    private volatile boolean mOpen = true;
    final Lock lock = new ReentrantLock();
    final Condition notFull  = lock.newCondition();
    final Condition notEmpty = lock.newCondition();

    /**
     * @param size Number of doubles in the FIFO. Must be a power of 2. Eg. 1024.
     */
    public void allocate(int size) {
        if (!isPowerOfTwo(size)) {
            throw new IllegalArgumentException("Size must be a power of two.");
        }
        buffer = new double[size];
        accessMask = size - 1;
        sizeMask = (size * 2) - 1;
    }

    public int size() {
        return buffer.length;
    }

    public static boolean isPowerOfTwo(int size) {
        return ((size & (size - 1)) == 0);
    }

    /** How many samples are available for reading without blocking? */
    @Override
    public int available() {
        return (writeIndex - readIndex) & sizeMask;
    }

    @Override
    public void close() {
        // Tell any thread that is waiting that the FIFO is closed.
        mOpen = false;
        lock.lock();
        notEmpty.signal();
        notFull.signal();
        lock.unlock();
    }

    @Override
    public double read() {
        double value = Double.NaN;
        if (readWaitEnabled) {
            lock.lock();
            try {
              while (mOpen && available() < 1) {
                try {
                    notEmpty.await();
                } catch (InterruptedException e) {
                    return Double.NaN;
                }
              }
              if (mOpen) {
                  value = readOneInternal();
              }
            } finally {
              lock.unlock();
            }

        } else {
            if (mOpen && readIndex != writeIndex) {
                value = readOneInternal();
            }
        }

        if (writeWaitEnabled) {
            lock.lock();
            notFull.signal();
            lock.unlock();
        }

        return value;
    }

    private double readOneInternal() {
        double value = buffer[readIndex & accessMask];
        readIndex = (readIndex + 1) & sizeMask;
        return value;
    }

    @Override
    public void write(double value) {
        if (writeWaitEnabled) {
            lock.lock();
            try {
                while (mOpen && available() == buffer.length)
                {
                    try {
                        notFull.await();
                    } catch (InterruptedException e) {
                        return; // Silently fail
                    }
                }
                if (mOpen) {
                    writeOneInternal(value);
                }
            } finally {
                lock.unlock();
            }

        } else {
            if (available() != buffer.length) {
                writeOneInternal(value);
            }
        }

        if (readWaitEnabled) {
            lock.lock();
            notEmpty.signal();
            lock.unlock();
        }
    }

    private void writeOneInternal(double value) {
        buffer[writeIndex & accessMask] = value;
        writeIndex = (writeIndex + 1) & sizeMask;
    }

    @Override
    public int read(double[] buffer) {
        return read(buffer, 0, buffer.length);
    }

    @Override
    public int read(double[] buffer, int start, int count) {
        if (!mOpen) {
            return 0;
        }
        if (!readWaitEnabled) {
            count = Math.min(available(), count);
        }
        int numRead = 0;
        for (int i = 0; mOpen && i < count; i++) {
            double value = read();
            if (Double.isNaN(value)) break;
            buffer[i + start] = value;
            numRead++;
        }
        return numRead;
    }

    @Override
    public void write(double[] buffer) {
        write(buffer, 0, buffer.length);
    }

    @Override
    public void write(double[] buffer, int start, int count) {
        for (int i = 0; i < count; i++) {
            write(buffer[i + start]);
        }
    }

    /** If true then a subsequent write call will wait if there is no room to write. */
    public void setWriteWaitEnabled(boolean enabled) {
        writeWaitEnabled = enabled;

    }

    /** If true then a subsequent read call will wait if there is no data to read. */
    public void setReadWaitEnabled(boolean enabled) {
        readWaitEnabled = enabled;

    }

    public boolean isWriteWaitEnabled() {
        return writeWaitEnabled;
    }

    public boolean isReadWaitEnabled() {
        return readWaitEnabled;
    }
}