aboutsummaryrefslogtreecommitdiffstats
path: root/src/jogl/classes/jogamp/opengl/openal/av/ALAudioSink.java
blob: 87c7b937a5cc1b2a5bcd04dad3c70a10f3d8831a (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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
/**
 * Copyright 2013 JogAmp Community. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are
 * permitted provided that the following conditions are met:
 * 
 *    1. Redistributions of source code must retain the above copyright notice, this list of
 *       conditions and the following disclaimer.
 * 
 *    2. Redistributions in binary form must reproduce the above copyright notice, this list
 *       of conditions and the following disclaimer in the documentation and/or other materials
 *       provided with the distribution.
 * 
 * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * 
 * The views and conclusions contained in the software and documentation are those of the
 * authors and should not be interpreted as representing official policies, either expressed
 * or implied, of JogAmp Community.
 */
package jogamp.opengl.openal.av;


import jogamp.opengl.util.av.SyncedRingbuffer;

import com.jogamp.openal.AL;
import com.jogamp.openal.ALC;
import com.jogamp.openal.ALCcontext;
import com.jogamp.openal.ALCdevice;
import com.jogamp.openal.ALFactory;
import com.jogamp.opengl.util.av.AudioSink;

/***
 * OpenAL Audio Sink
 */
public class ALAudioSink implements AudioSink {

    /** Chunk of audio processed at one time. FIXME: Parameterize .. */
    public static final int BUFFER_SIZE = 4096;
    public static final int SAMPLES_PER_BUFFER = BUFFER_SIZE / 2;
    
    private static final ALC alc;
    private static final AL al;
    private static final boolean staticAvailable;    
    
    private String deviceSpecifier;
    private ALCdevice device;
    private ALCcontext context;

    /** Sample period in seconds */
    public float samplePeriod;
    /** Buffer period in seconds */
    public float bufferPeriod;
    
    static class ActiveBuffer {
        ActiveBuffer(Integer name, int size) {
            this.name = name;
            this.size = size;
        }
        public final Integer name;
        public final int size;
        public String toString() { return "ABuffer[name "+name+", size "+size+"]"; }
    }
    
    int[] alBuffers = null;
    private SyncedRingbuffer<Integer> alBufferAvail = null;
    private SyncedRingbuffer<ActiveBuffer> alBufferPlaying = null;
    private int alBufferBytesQueued = 0;

    private int[] alSource = null;
    private AudioDataFormat chosenFormat;
    private int alFormat;    
    private boolean initialized;

    static {
        ALC _alc = null;
        AL _al = null;
        try {
            _alc = ALFactory.getALC();            
            _al = ALFactory.getAL();
        } catch(Throwable t) {
            if( DEBUG ) {
                System.err.println("ALAudioSink: Catched "+t.getClass().getName()+": "+t.getMessage());
                t.printStackTrace();
            }
        }
        alc = _alc;
        al = _al;
        staticAvailable = null != alc && null != al;
    }
    
    public ALAudioSink() {
        initialized = false;
        chosenFormat = null;
        
        if( !staticAvailable ) {
            return;
        }
        
        try {
            // Get handle to default device.
            device = alc.alcOpenDevice(null);
            if (device == null) {
                throw new RuntimeException("ALAudioSink: Error opening default OpenAL device");
            }
        
            // Get the device specifier.
            deviceSpecifier = alc.alcGetString(device, ALC.ALC_DEVICE_SPECIFIER);
            if (deviceSpecifier == null) {
                throw new RuntimeException("ALAudioSink: Error getting specifier for default OpenAL device");
            }
                
            // Create audio context.
            context = alc.alcCreateContext(device, null);
            if (context == null) {
                throw new RuntimeException("ALAudioSink: Error creating OpenAL context");
            }
        
            // Set active context.
            alc.alcMakeContextCurrent(context);
        
            // Check for an error.
            if ( alc.alcGetError(device) != ALC.ALC_NO_ERROR ) {
                throw new RuntimeException("ALAudioSink: Error making OpenAL context current");
            }
            
            // Create source
            {
                alSource = new int[1];
                al.alGenSources(1, alSource, 0);
                final int err = al.alGetError();
                if( err != AL.AL_NO_ERROR ) {
                    alSource = null;
                    throw new RuntimeException("ALAudioSink: Error generating Source: 0x"+Integer.toHexString(err));
                }       
            }
            
            if( DEBUG ) {                
                System.err.println("ALAudioSink: Using device: " + deviceSpecifier);
            }
            initialized = true;
            return;
        } catch ( Exception e ) {
            if( DEBUG ) {
                System.err.println(e.getMessage());
            }
            destroy();
        }
    }
    
    @Override
    public String toString() {
        final int alSrcName = null != alSource ? alSource[0] : 0;
        final int alBuffersLen = null != alBuffers ? alBuffers.length : 0;
        return "ALAudioSink[init "+initialized+", device "+deviceSpecifier+", ctx "+context+", alSource "+alSrcName+
               ", chosen "+chosenFormat+", alFormat "+toHexString(alFormat)+
               ", buffers[total "+alBuffersLen+", avail "+alBufferAvail.size()+", "+alBufferPlaying.getFreeSlots()+
               ", queued[bufferCount "+alBufferPlaying.size()+", "+getQueuedTime() + " ms, " + alBufferBytesQueued+" bytes]";
    }
    
    @Override
    public AudioDataFormat getPreferredFormat() {
        return DefaultFormat;
    }
    
    @Override
    public AudioDataFormat initSink(AudioDataFormat requestedFormat, int bufferCount) {
        if( !staticAvailable ) {
            return null;
        }
        samplePeriod = 1.0f / requestedFormat.sampleRate;
        bufferPeriod = samplePeriod * SAMPLES_PER_BUFFER;
        switch( requestedFormat.channelCount ) {
            case 1: { 
                switch ( requestedFormat.sampleSize ) {
                    case 8: 
                        alFormat = AL.AL_FORMAT_MONO8; break;
                    case 16:
                        alFormat = AL.AL_FORMAT_MONO16; break;
                    default:
                        return null;
                }
            } break;
            case 2: 
                switch ( requestedFormat.sampleSize ) {
                    case 8: 
                        alFormat = AL.AL_FORMAT_STEREO8; break;
                    case 16:
                        alFormat = AL.AL_FORMAT_STEREO16; break;
                    default:
                        return null;
                }
        }
        // Allocate buffers
        destroyBuffers();
        {
            alBuffers = new int[bufferCount];
            al.alGenBuffers(bufferCount, alBuffers, 0);
            final int err = al.alGetError();
            if( err != AL.AL_NO_ERROR ) {
                alBuffers = null;
                throw new RuntimeException("ALAudioSink: Error generating Buffers: 0x"+Integer.toHexString(err));
            }
            final Integer[] alBufferRingArray = new Integer[bufferCount];
            for(int i=0; i<bufferCount; i++) {
                alBufferRingArray[i] = Integer.valueOf(alBuffers[i]);
            }
            alBufferAvail = new SyncedRingbuffer<Integer>(alBufferRingArray, true /* full */);
            alBufferPlaying = new SyncedRingbuffer<ActiveBuffer>(new ActiveBuffer[bufferCount], false /* full */);
        }
        
        
        chosenFormat = requestedFormat;
        return chosenFormat;
    }
    
    private void destroyBuffers() {
        if( !staticAvailable ) {
            return;
        }
        if( null != alBuffers ) {
            try {
                al.alDeleteBuffers(alBufferAvail.capacity(), alBuffers, 0);
            } catch (Throwable t) {
                if( DEBUG ) {
                    System.err.println("Catched "+t.getClass().getName()+": "+t.getMessage());
                    t.printStackTrace();
                }
            }
            alBufferAvail.clear(true);
            alBufferAvail = null;
            alBufferPlaying.clear(true);
            alBufferPlaying = null;
            alBufferBytesQueued = 0;
            alBuffers = null;
        }
    }
    
    @Override
    public void destroy() {
        initialized = false;
        if( !staticAvailable ) {
            return;
        }
        if( null != alSource ) {
            try {
                al.alDeleteSources(1, alSource, 0);
            } catch (Throwable t) {
                if( DEBUG ) {
                    System.err.println("Catched "+t.getClass().getName()+": "+t.getMessage());
                    t.printStackTrace();
                }
            }
            alSource = null;
        }
        
        destroyBuffers();

        if( null != context ) {
            try {
                alc.alcDestroyContext(context);
            } catch (Throwable t) {
                if( DEBUG ) {
                    System.err.println("Catched "+t.getClass().getName()+": "+t.getMessage());
                    t.printStackTrace();
                }
            }
            context = null;            
        }
        if( null != device ) {
            try {
                alc.alcCloseDevice(device);
            } catch (Throwable t) {
                if( DEBUG ) {
                    System.err.println("Catched "+t.getClass().getName()+": "+t.getMessage());
                    t.printStackTrace();
                }
            }
            device = null;            
        }
        chosenFormat = null;
    }
    
    @Override
    public boolean isInitialized() {
        return initialized;
    }
    
    private final void dequeueBuffer(boolean wait) {
        int alErr = AL.AL_NO_ERROR;
        final int[] val=new int[1];
        do {
            al.alGetSourcei(alSource[0], AL.AL_BUFFERS_PROCESSED, val, 0);
            alErr = al.alGetError();
            if( AL.AL_NO_ERROR != alErr ) {
                throw new RuntimeException("ALError "+toHexString(alErr)+" while quering processed buffers at source. "+this);                 
            }
            if( wait && val[0] <= 0 ) {
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e){
                }
            }
        } while (val[0] <= 0);
        final int processedBuffers = val[0];

        if( processedBuffers > 0 ) {
            int[] buffers=new int[processedBuffers];
            al.alSourceUnqueueBuffers(alSource[0], processedBuffers, buffers, 0);
            alErr = al.alGetError();
            if( AL.AL_NO_ERROR != alErr ) {
                throw new RuntimeException("ALError "+toHexString(alErr)+" while dequeueing "+processedBuffers+" processed buffers. "+this);                 
            }
            for ( int i=0; i<processedBuffers; i++ ) {
                final ActiveBuffer releasedBuffer = alBufferPlaying.get(true /* clearRef */);
                if( null == releasedBuffer ) {
                    throw new InternalError("Internal Error: "+this);
                }
                if( releasedBuffer.name.intValue() != buffers[i] ) {                    
                    throw new InternalError("Buffer name mismatch: dequeued: "+buffers[i]+", released "+releasedBuffer);
                    // System.err.println("XXX ["+i+"]: dequeued: "+buffers[i]+", released "+releasedBuffer);
                }
                alBufferBytesQueued -= releasedBuffer.size;
                if( !alBufferAvail.put(releasedBuffer.name) ) {
                    throw new InternalError("Internal Error: "+this);
                }
                if( DEBUG ) {
                    System.err.println("ALAudioSink: Dequeued "+processedBuffers+", wait "+wait+", "+this);
                }                
            }
        }
    }
    
    private static final String toHexString(int v) {
        return "0x"+Integer.toHexString(v);
    }
        
    @Override
    public void writeData(AudioFrame audioFrame) {
        if( !initialized || null == chosenFormat ) {
            return;
        }
        int alErr = AL.AL_NO_ERROR;
            
        // OpenAL consumes buffers in the background
        // we first need to initialize the OpenAL buffers then
        // start continuous playback.
        alc.alcMakeContextCurrent(context);
        alErr = al.alGetError();
        if(al.alGetError() != AL.AL_NO_ERROR) {
            throw new RuntimeException("ALError "+toHexString(alErr)+" while makeCurrent. "+this);
        }
        
        if( alBufferAvail.isEmpty() ) {
            dequeueBuffer(true);
        }
        
        final Integer alBufferName = alBufferAvail.get(true /* clearRef */);
        if( null == alBufferName ) {
            throw new InternalError("Internal Error: "+this);
        }
        if( !alBufferPlaying.put( new ActiveBuffer(alBufferName, audioFrame.dataSize) ) ) {
            throw new InternalError("Internal Error: "+this);
        }
        al.alBufferData(alBufferName.intValue(), alFormat, audioFrame.data, audioFrame.dataSize, chosenFormat.sampleRate);
        final int[] alBufferNames = new int[] { alBufferName.intValue() };
        al.alSourceQueueBuffers(alSource[0], 1, alBufferNames, 0);
        alErr = al.alGetError();
        if(al.alGetError() != AL.AL_NO_ERROR) {
            throw new RuntimeException("ALError "+toHexString(alErr)+" while queueing buffer "+toHexString(alBufferNames[0])+". "+this);
        }
        alBufferBytesQueued += audioFrame.dataSize;
        
        // Restart openal playback if needed
        {
            int[] val = new int[1];
            al.alGetSourcei(alSource[0], AL.AL_SOURCE_STATE, val, 0);
            if(val[0] != AL.AL_PLAYING) {
                if( DEBUG ) {
                    System.err.println("ALAudioSink: Start playing: "+this);
                }
                al.alSourcePlay(alSource[0]);
                alErr = al.alGetError();
                if(al.alGetError() != AL.AL_NO_ERROR) {
                    throw new RuntimeException("ALError "+toHexString(alErr)+" while start playing. "+this);
                }
            }
        }
    }

    @Override
    public int getQueuedByteCount() {
        if( !initialized || null == chosenFormat ) {
            return 0;
        }
        return alBufferBytesQueued;
    }
    
    @Override
    public int getQueuedTime() {
        if( !initialized || null == chosenFormat ) {
            return 0;
        }
        final int bps = chosenFormat.sampleSize / 8;
        return alBufferBytesQueued / ( chosenFormat.channelCount * bps * ( chosenFormat.sampleRate / 1000 ) );
    }
    
    @Override
    public int getWritableBufferCount() {
        if( !initialized || null == chosenFormat ) {
            return 0;
        }
        return alBufferPlaying.getFreeSlots();
    }
    
    @Override
    public boolean isDataAvailable(int data_size) {               
        return initialized && null != chosenFormat;
    }
    
}