Jogamp
Bug 1270 - Fix OSX El Capitan 10.11 stuttering: ALAudioSink: DEBUG: Show OpenAL Version
[jogl.git] / src / jogl / classes / jogamp / opengl / openal / av / ALAudioSink.java
1 /**
2  * Copyright 2013 JogAmp Community. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without modification, are
5  * permitted provided that the following conditions are met:
6  *
7  *    1. Redistributions of source code must retain the above copyright notice, this list of
8  *       conditions and the following disclaimer.
9  *
10  *    2. Redistributions in binary form must reproduce the above copyright notice, this list
11  *       of conditions and the following disclaimer in the documentation and/or other materials
12  *       provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
15  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
16  * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
17  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
19  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
20  * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
21  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
22  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
23  *
24  * The views and conclusions contained in the software and documentation are those of the
25  * authors and should not be interpreted as representing official policies, either expressed
26  * or implied, of JogAmp Community.
27  */
28 package jogamp.opengl.openal.av;
29
30
31 import java.nio.ByteBuffer;
32 import java.util.Arrays;
33
34 import jogamp.opengl.Debug;
35
36 import com.jogamp.common.ExceptionUtils;
37 import com.jogamp.common.util.LFRingbuffer;
38 import com.jogamp.common.util.PropertyAccess;
39 import com.jogamp.common.util.Ringbuffer;
40 import com.jogamp.common.util.locks.LockFactory;
41 import com.jogamp.common.util.locks.RecursiveLock;
42 import com.jogamp.openal.AL;
43 import com.jogamp.openal.ALC;
44 import com.jogamp.openal.ALCConstants;
45 import com.jogamp.openal.ALCcontext;
46 import com.jogamp.openal.ALCdevice;
47 import com.jogamp.openal.ALConstants;
48 import com.jogamp.openal.ALExt;
49 import com.jogamp.openal.ALFactory;
50 import com.jogamp.openal.util.ALHelpers;
51 import com.jogamp.opengl.util.av.AudioSink;
52
53 /***
54  * OpenAL Audio Sink
55  */
56 public class ALAudioSink implements AudioSink {
57
58     private static final String AL_SOFT_buffer_samples = "AL_SOFT_buffer_samples";
59     private static final String ALC_EXT_thread_local_context = "ALC_EXT_thread_local_context";
60     private static final boolean DEBUG_TRACE;
61     private static final ALC alc;
62     private static final AL al;
63     private static final ALExt alExt;
64     private static final boolean staticAvailable;
65
66     private String deviceSpecifier;
67     private ALCdevice device;
68     private boolean hasSOFTBufferSamples;
69     private boolean hasALC_thread_local_context;
70     private AudioFormat preferredAudioFormat;
71     private ALCcontext context;
72     private final RecursiveLock lock = LockFactory.createRecursiveLock();
73
74     /** Playback speed, range [0.5 - 2.0], default 1.0. */
75     private float playSpeed;
76     private float volume = 1.0f;
77
78     static class ALAudioFrame extends AudioFrame {
79         private final int alBuffer;
80
81         ALAudioFrame(final int alBuffer) {
82             this.alBuffer = alBuffer;
83         }
84         public ALAudioFrame(final int alBuffer, final int pts, final int duration, final int dataSize) {
85             super(pts, duration, dataSize);
86             this.alBuffer = alBuffer;
87         }
88
89         /** Get this frame's OpenAL buffer name */
90         public final int getALBuffer() { return alBuffer; }
91
92         public String toString() {
93             return "ALAudioFrame[pts " + pts + " ms, l " + duration + " ms, " + byteSize + " bytes, buffer "+alBuffer+"]";
94         }
95     }
96
97     // private ALAudioFrame[] alFrames = null;
98     private int[] alBufferNames = null;
99     private int frameGrowAmount = 0;
100     private int frameLimit = 0;
101
102     private Ringbuffer<ALAudioFrame> alFramesAvail = null;
103     private Ringbuffer<ALAudioFrame> alFramesPlaying = null;
104     private volatile int alBufferBytesQueued = 0;
105     private volatile int playingPTS = AudioFrame.INVALID_PTS;
106     private volatile int enqueuedFrameCount;
107
108     private int[] alSource = null;
109     private AudioFormat chosenFormat;
110     private int alChannelLayout;
111     private int alSampleType;
112     private int alFormat;
113     private boolean initialized;
114
115     private volatile boolean playRequested = false;
116
117     static {
118         Debug.initSingleton();
119         DEBUG_TRACE = PropertyAccess.isPropertyDefined("jogl.debug.AudioSink.trace", true);
120
121         ALC _alc = null;
122         AL _al = null;
123         ALExt _alExt = null;
124         try {
125             _alc = ALFactory.getALC();
126             _al = ALFactory.getAL();
127             _alExt = ALFactory.getALExt();
128         } catch(final Throwable t) {
129             if( DEBUG ) {
130                 System.err.println("ALAudioSink: Caught "+t.getClass().getName()+": "+t.getMessage());
131                 t.printStackTrace();
132             }
133         }
134         alc = _alc;
135         al = _al;
136         alExt = _alExt;
137         staticAvailable = null != alc && null != al && null != alExt;
138     }
139
140     private void clearPreALError(final String prefix) {
141         checkALError(prefix);
142     }
143     private boolean checkALError(final String prefix) {
144         final int alcErr = alc.alcGetError(device);
145         final int alErr = al.alGetError();
146         final boolean ok = ALCConstants.ALC_NO_ERROR == alcErr && ALConstants.AL_NO_ERROR == alErr;
147         if( DEBUG ) {
148             System.err.println("ALAudioSink."+prefix+": ok "+ok+", err [alc "+toHexString(alcErr)+", al "+toHexString(alErr)+"]");
149         }
150         return ok;
151     }
152
153     public ALAudioSink() {
154         initialized = false;
155         chosenFormat = null;
156
157         if( !staticAvailable ) {
158             return;
159         }
160         synchronized(ALAudioSink.class) {
161             try {
162                 // Get handle to default device.
163                 device = alc.alcOpenDevice(null);
164                 if (device == null) {
165                     throw new RuntimeException(getThreadName()+": ALAudioSink: Error opening default OpenAL device");
166                 }
167                 int checkErrIter = 1;
168
169                 clearPreALError("init."+checkErrIter++);
170
171                 // Get the device specifier.
172                 deviceSpecifier = alc.alcGetString(device, ALCConstants.ALC_DEVICE_SPECIFIER);
173                 if (deviceSpecifier == null) {
174                     throw new RuntimeException(getThreadName()+": ALAudioSink: Error getting specifier for default OpenAL device");
175                 }
176
177                 // Create audio context.
178                 // final int[] attrs = new int[] { ALC.ALC_FREQUENCY, DefaultFormat.sampleRate, 0 };
179                 // context = alc.alcCreateContext(device, attrs, 0);
180                 context = alc.alcCreateContext(device, null);
181                 if (context == null) {
182                     throw new RuntimeException(getThreadName()+": ALAudioSink: Error creating OpenAL context for "+deviceSpecifier);
183                 }
184
185                 lockContext();
186                 try {
187                     // Check for an error.
188                     if ( alc.alcGetError(device) != ALCConstants.ALC_NO_ERROR ) {
189                         throw new RuntimeException(getThreadName()+": ALAudioSink: Error making OpenAL context current");
190                     }
191
192                     hasSOFTBufferSamples = al.alIsExtensionPresent(AL_SOFT_buffer_samples);
193                     hasALC_thread_local_context = alc.alcIsExtensionPresent(null, ALC_EXT_thread_local_context) ||
194                                                   alc.alcIsExtensionPresent(device, ALC_EXT_thread_local_context) ;
195                     clearPreALError("init."+checkErrIter++);
196                     preferredAudioFormat = new AudioFormat(querySampleRate(), DefaultFormat.sampleSize, DefaultFormat.channelCount, DefaultFormat.signed, DefaultFormat.fixedP, DefaultFormat.planar, DefaultFormat.littleEndian);
197                     if( DEBUG ) {
198                         final int[] alcvers = { 0, 0 };
199                         System.out.println("ALAudioSink: OpenAL Version: "+al.alGetString(ALConstants.AL_VERSION));
200                         System.out.println("ALAudioSink: OpenAL Extensions: "+al.alGetString(ALConstants.AL_EXTENSIONS));
201                         clearPreALError("init."+checkErrIter++);
202                         System.out.println("ALAudioSink: Null device OpenALC:");
203                         alc.alcGetIntegerv(null, ALCConstants.ALC_MAJOR_VERSION, 1, alcvers, 0);
204                         alc.alcGetIntegerv(null, ALCConstants.ALC_MINOR_VERSION, 1, alcvers, 1);
205                         System.out.println("  Version: "+alcvers[0]+"."+alcvers[1]);
206                         System.out.println("  Extensions: "+alc.alcGetString(null, ALCConstants.ALC_EXTENSIONS));
207                         clearPreALError("init."+checkErrIter++);
208                         System.out.println("ALAudioSink: Device "+deviceSpecifier+" OpenALC:");
209                         alc.alcGetIntegerv(device, ALCConstants.ALC_MAJOR_VERSION, 1, alcvers, 0);
210                         alc.alcGetIntegerv(device, ALCConstants.ALC_MINOR_VERSION, 1, alcvers, 1);
211                         System.out.println("  Version: "+alcvers[0]+"."+alcvers[1]);
212                         System.out.println("  Extensions: "+alc.alcGetString(device, ALCConstants.ALC_EXTENSIONS));
213                         System.out.println("ALAudioSink: hasSOFTBufferSamples "+hasSOFTBufferSamples);
214                         System.out.println("ALAudioSink: hasALC_thread_local_context "+hasALC_thread_local_context);
215                         System.out.println("ALAudioSink: preferredAudioFormat "+preferredAudioFormat);
216                         clearPreALError("init."+checkErrIter++);
217                     }
218
219                     // Create source
220                     {
221                         alSource = new int[1];
222                         al.alGenSources(1, alSource, 0);
223                         final int err = al.alGetError();
224                         if( ALConstants.AL_NO_ERROR != err ) {
225                             alSource = null;
226                             throw new RuntimeException(getThreadName()+": ALAudioSink: Error generating Source: 0x"+Integer.toHexString(err));
227                         }
228                     }
229
230                     if( DEBUG ) {
231                         System.err.println("ALAudioSink: Using device: " + deviceSpecifier);
232                     }
233                     initialized = true;
234                 } finally {
235                     unlockContext();
236                 }
237                 return;
238             } catch ( final Exception e ) {
239                 if( DEBUG ) {
240                     System.err.println(e.getMessage());
241                     e.printStackTrace();
242                 }
243                 destroy();
244             }
245         }
246     }
247
248     private final int querySampleRate() {
249         final int sampleRate;
250         final int[] value = new int[1];
251         alc.alcGetIntegerv(device, ALCConstants.ALC_FREQUENCY, 1, value, 0);
252         final int alcErr = alc.alcGetError(device);
253         final int alErr = al.alGetError();
254         if ( ALCConstants.ALC_NO_ERROR == alcErr && ALConstants.AL_NO_ERROR == alErr && 0 != value[0] ) {
255             sampleRate = value[0];
256         } else {
257             sampleRate = DefaultFormat.sampleRate;
258         }
259         if( DEBUG ) {
260             System.err.println("ALAudioSink.querySampleRate: err [alc "+toHexString(alcErr)+", al "+toHexString(alErr)+"], freq: "+value[0]+" -> "+sampleRate);
261         }
262         return sampleRate;
263     }
264
265     private final void lockContext() {
266         lock.lock();
267         if( hasALC_thread_local_context ) {
268             alExt.alcSetThreadContext(context);
269         } else {
270             alc.alcMakeContextCurrent(context);
271         }
272         final int alcErr = alc.alcGetError(null);
273         if( ALCConstants.ALC_NO_ERROR != alcErr ) {
274             final String err = getThreadName()+": ALCError "+toHexString(alcErr)+" while makeCurrent. "+this;
275             System.err.println(err);
276             ExceptionUtils.dumpStack(System.err);
277             lock.unlock();
278             throw new RuntimeException(err);
279         }
280         final int alErr = al.alGetError();
281         if( ALCConstants.ALC_NO_ERROR != alErr ) {
282             if( DEBUG ) {
283                 System.err.println(getThreadName()+": Prev - ALError "+toHexString(alErr)+" @ makeCurrent. "+this);
284                 ExceptionUtils.dumpStack(System.err);
285             }
286         }
287     }
288     private final void unlockContext() {
289         if( hasALC_thread_local_context ) {
290             alExt.alcSetThreadContext(null);
291         } else {
292             alc.alcMakeContextCurrent(null);
293         }
294         lock.unlock();
295     }
296     private final void destroyContext() {
297         lock.lock();
298         try {
299             if( null != context ) {
300                 try {
301                     alc.alcDestroyContext(context);
302                 } catch (final Throwable t) {
303                     if( DEBUG ) {
304                         ExceptionUtils.dumpThrowable("", t);
305                     }
306                 }
307                 context = null;
308             }
309             // unroll lock !
310             while(lock.getHoldCount() > 1) {
311                 lock.unlock();
312             }
313         } finally {
314             lock.unlock();
315         }
316     }
317
318     @Override
319     public final String toString() {
320         final int alSrcName = null != alSource ? alSource[0] : 0;
321         final int alBuffersLen = null != alBufferNames ? alBufferNames.length : 0;
322         final int ctxHash = context != null ? context.hashCode() : 0;
323         final int alFramesAvailSize = alFramesAvail != null ? alFramesAvail.size() : 0;
324         final int alFramesPlayingSize = alFramesPlaying != null ? alFramesPlaying.size() : 0;
325         return "ALAudioSink[init "+initialized+", playRequested "+playRequested+", device "+deviceSpecifier+", ctx "+toHexString(ctxHash)+", alSource "+alSrcName+
326                ", chosen "+chosenFormat+
327                ", al[chan "+ALHelpers.alChannelLayoutName(alChannelLayout)+", type "+ALHelpers.alSampleTypeName(alSampleType)+
328                ", fmt "+toHexString(alFormat)+", soft "+hasSOFTBufferSamples+
329                "], playSpeed "+playSpeed+", buffers[total "+alBuffersLen+", avail "+alFramesAvailSize+", "+
330                "queued["+alFramesPlayingSize+", apts "+getPTS()+", "+getQueuedTime() + " ms, " + alBufferBytesQueued+" bytes], "+
331                "queue[g "+frameGrowAmount+", l "+frameLimit+"]";
332     }
333
334     private final String shortString() {
335         final int alSrcName = null != alSource ? alSource[0] : 0;
336         final int ctxHash = context != null ? context.hashCode() : 0;
337         return "[ctx "+toHexString(ctxHash)+", playReq "+playRequested+", alSrc "+alSrcName+
338                ", queued["+alFramesPlaying.size()+", " + alBufferBytesQueued+" bytes], "+
339                "queue[g "+frameGrowAmount+", l "+frameLimit+"]";
340     }
341
342     public final String getPerfString() {
343         final int alBuffersLen = null != alBufferNames ? alBufferNames.length : 0;
344         return "Play [buffer "+alFramesPlaying.size()+"/"+alBuffersLen+", apts "+getPTS()+", "+getQueuedTime() + " ms, " + alBufferBytesQueued+" bytes]";
345     }
346
347     @Override
348     public final AudioFormat getPreferredFormat() {
349         if( !staticAvailable ) {
350             return null;
351         }
352         return preferredAudioFormat;
353     }
354
355     @Override
356     public final int getMaxSupportedChannels() {
357         if( !staticAvailable ) {
358             return 0;
359         }
360         return hasSOFTBufferSamples ? 8 : 2;
361     }
362
363     @Override
364     public final boolean isSupported(final AudioFormat format) {
365         if( !staticAvailable ) {
366             return false;
367         }
368         if( format.planar || !format.littleEndian ) {
369             // FIXME big-endian supported w/ SOFT where it's native format!
370             return false;
371         }
372         final int alChannelLayout = ALHelpers.getDefaultALChannelLayout(format.channelCount);
373         if( ALConstants.AL_NONE != alChannelLayout ) {
374             final int alSampleType = ALHelpers.getALSampleType(format.sampleSize, format.signed, format.fixedP);
375             if( ALConstants.AL_NONE != alSampleType ) {
376                 lockContext();
377                 try {
378                     final int alFormat = ALHelpers.getALFormat(alChannelLayout, alSampleType, hasSOFTBufferSamples, al, alExt);
379                     return ALConstants.AL_NONE != alFormat;
380                 } finally {
381                     unlockContext();
382                 }
383             }
384         }
385         return false;
386     }
387
388     @Override
389     public final boolean init(final AudioFormat requestedFormat, final float frameDuration, final int initialQueueSize, final int queueGrowAmount, final int queueLimit) {
390         if( !staticAvailable ) {
391             return false;
392         }
393         alChannelLayout = ALHelpers.getDefaultALChannelLayout(requestedFormat.channelCount);
394         alSampleType = ALHelpers.getALSampleType(requestedFormat.sampleSize, requestedFormat.signed, requestedFormat.fixedP);
395         lockContext();
396         try {
397             if( ALConstants.AL_NONE != alChannelLayout && ALConstants.AL_NONE != alSampleType ) {
398                 alFormat = ALHelpers.getALFormat(alChannelLayout, alSampleType, hasSOFTBufferSamples, al, alExt);
399             } else {
400                 alFormat = ALConstants.AL_NONE;
401             }
402             if( ALConstants.AL_NONE == alFormat ) {
403                 // not supported
404                 return false;
405             }
406             // Allocate buffers
407             destroyBuffers();
408             {
409                 final float useFrameDuration = frameDuration > 1f ? frameDuration : AudioSink.DefaultFrameDuration;
410                 final int initialFrameCount = requestedFormat.getFrameCount(
411                         initialQueueSize > 0 ? initialQueueSize : AudioSink.DefaultInitialQueueSize, useFrameDuration);
412                 // frameDuration, int initialQueueSize, int queueGrowAmount, int queueLimit) {
413                 alBufferNames = new int[initialFrameCount];
414                 al.alGenBuffers(initialFrameCount, alBufferNames, 0);
415                 final int err = al.alGetError();
416                 if( ALConstants.AL_NO_ERROR != err ) {
417                     alBufferNames = null;
418                     throw new RuntimeException(getThreadName()+": ALAudioSink: Error generating Buffers: 0x"+Integer.toHexString(err));
419                 }
420                 final ALAudioFrame[] alFrames = new ALAudioFrame[initialFrameCount];
421                 for(int i=0; i<initialFrameCount; i++) {
422                     alFrames[i] = new ALAudioFrame(alBufferNames[i]);
423                 }
424
425                 alFramesAvail = new LFRingbuffer<ALAudioFrame>(alFrames);
426                 alFramesPlaying = new LFRingbuffer<ALAudioFrame>(ALAudioFrame[].class, initialFrameCount);
427                 this.frameGrowAmount = requestedFormat.getFrameCount(
428                         queueGrowAmount > 0 ? queueGrowAmount : AudioSink.DefaultQueueGrowAmount, useFrameDuration);
429                 this.frameLimit = requestedFormat.getFrameCount(
430                         queueLimit > 0 ? queueLimit : AudioSink.DefaultQueueLimitWithVideo, useFrameDuration);
431                 if( DEBUG_TRACE ) {
432                     alFramesAvail.dump(System.err, "Avail-init");
433                     alFramesPlaying.dump(System.err, "Playi-init");
434                 }
435             }
436         } finally {
437             unlockContext();
438         }
439
440         chosenFormat = requestedFormat;
441         return true;
442     }
443
444     @Override
445     public final AudioFormat getChosenFormat() {
446         return chosenFormat;
447     }
448
449     private static int[] concat(final int[] first, final int[] second) {
450         final int[] result = Arrays.copyOf(first, first.length + second.length);
451         System.arraycopy(second, 0, result, first.length, second.length);
452         return result;
453     }
454     /**
455     private static <T> T[] concat(T[] first, T[] second) {
456         final T[] result = Arrays.copyOf(first, first.length + second.length);
457         System.arraycopy(second, 0, result, first.length, second.length);
458         return result;
459     } */
460
461     private boolean growBuffers() {
462         if( !alFramesAvail.isEmpty() || !alFramesPlaying.isFull() ) {
463             throw new InternalError("Buffers: Avail is !empty "+alFramesAvail+" or Playing is !full "+alFramesPlaying);
464         }
465         if( alFramesAvail.capacity() >= frameLimit || alFramesPlaying.capacity() >= frameLimit ) {
466             if( DEBUG ) {
467                 System.err.println(getThreadName()+": ALAudioSink.growBuffers: Frame limit "+frameLimit+" reached: Avail "+alFramesAvail+", Playing "+alFramesPlaying);
468             }
469             return false;
470         }
471
472         final int[] newALBufferNames = new int[frameGrowAmount];
473         al.alGenBuffers(frameGrowAmount, newALBufferNames, 0);
474         final int err = al.alGetError();
475         if( ALConstants.AL_NO_ERROR != err ) {
476             if( DEBUG ) {
477                 System.err.println(getThreadName()+": ALAudioSink.growBuffers: Error generating "+frameGrowAmount+" new Buffers: 0x"+Integer.toHexString(err));
478             }
479             return false;
480         }
481         alBufferNames = concat(alBufferNames, newALBufferNames);
482
483         final ALAudioFrame[] newALBuffers = new ALAudioFrame[frameGrowAmount];
484         for(int i=0; i<frameGrowAmount; i++) {
485             newALBuffers[i] = new ALAudioFrame(newALBufferNames[i]);
486         }
487         // alFrames = concat(alFrames , newALBuffers);
488
489         alFramesAvail.growEmptyBuffer(newALBuffers);
490         alFramesPlaying.growFullBuffer(frameGrowAmount);
491         if( alFramesAvail.isEmpty() || alFramesPlaying.isFull() ) {
492             throw new InternalError("Buffers: Avail is empty "+alFramesAvail+" or Playing is full "+alFramesPlaying);
493         }
494         if( DEBUG ) {
495             System.err.println(getThreadName()+": ALAudioSink: Buffer grown "+frameGrowAmount+": Avail "+alFramesAvail+", playing "+alFramesPlaying);
496         }
497         if( DEBUG_TRACE ) {
498             alFramesAvail.dump(System.err, "Avail-grow");
499             alFramesPlaying.dump(System.err, "Playi-grow");
500         }
501         return true;
502     }
503
504     private void destroyBuffers() {
505         if( !staticAvailable ) {
506             return;
507         }
508         if( null != alBufferNames ) {
509             try {
510                 al.alDeleteBuffers(alBufferNames.length, alBufferNames, 0);
511             } catch (final Throwable t) {
512                 if( DEBUG ) {
513                     System.err.println("Caught "+t.getClass().getName()+": "+t.getMessage());
514                     t.printStackTrace();
515                 }
516             }
517             alFramesAvail.clear();
518             alFramesAvail = null;
519             alFramesPlaying.clear();
520             alFramesPlaying = null;
521             alBufferBytesQueued = 0;
522             // alFrames = null;
523             alBufferNames = null;
524         }
525     }
526
527     @Override
528     public final void destroy() {
529         initialized = false;
530         if( !staticAvailable ) {
531             return;
532         }
533         if( null != context ) {
534             lockContext();
535         }
536         try {
537             stopImpl(true);
538             if( null != alSource ) {
539                 try {
540                     al.alDeleteSources(1, alSource, 0);
541                 } catch (final Throwable t) {
542                     if( DEBUG ) {
543                         System.err.println("Caught "+t.getClass().getName()+": "+t.getMessage());
544                         t.printStackTrace();
545                     }
546                 }
547                 alSource = null;
548             }
549
550             destroyBuffers();
551         } finally {
552             destroyContext();
553         }
554         if( null != device ) {
555             try {
556                 alc.alcCloseDevice(device);
557             } catch (final Throwable t) {
558                 if( DEBUG ) {
559                     System.err.println("Caught "+t.getClass().getName()+": "+t.getMessage());
560                     t.printStackTrace();
561                 }
562             }
563             device = null;
564         }
565         chosenFormat = null;
566     }
567
568     @Override
569     public final boolean isInitialized() {
570         return initialized;
571     }
572
573     private final int dequeueBuffer(final boolean wait, final boolean ignoreBufferInconsistency) {
574         int alErr = ALConstants.AL_NO_ERROR;
575         final int releaseBufferCount;
576         if( alBufferBytesQueued > 0 ) {
577             final int releaseBufferLimes = Math.max(1, alFramesPlaying.size() / 4 );
578             final int[] val=new int[1];
579             int i=0;
580             do {
581                 al.alGetSourcei(alSource[0], ALConstants.AL_BUFFERS_PROCESSED, val, 0);
582                 alErr = al.alGetError();
583                 if( ALConstants.AL_NO_ERROR != alErr ) {
584                     throw new RuntimeException(getThreadName()+": ALError "+toHexString(alErr)+" while quering processed buffers at source. "+this);
585                 }
586                 if( wait && val[0] < releaseBufferLimes ) {
587                     i++;
588                     // clip wait at [2 .. 100] ms
589                     final int avgBufferDura = chosenFormat.getBytesDuration( alBufferBytesQueued / alFramesPlaying.size() );
590                     final int sleep = Math.max(2, Math.min(100, releaseBufferLimes * avgBufferDura));
591                     if( DEBUG ) {
592                         System.err.println(getThreadName()+": ALAudioSink: Dequeue.wait["+i+"]: avgBufferDura "+avgBufferDura+", releaseBufferLimes "+releaseBufferLimes+", sleep "+sleep+" ms, playImpl "+(ALConstants.AL_PLAYING == getSourceState(false))+", processed "+val[0]+", "+this);
593                     }
594                     unlockContext();
595                     try {
596                         Thread.sleep( sleep - 1 );
597                     } catch (final InterruptedException e) {
598                     } finally {
599                         lockContext();
600                     }
601                 }
602             } while ( wait && val[0] < releaseBufferLimes && alBufferBytesQueued > 0 );
603             releaseBufferCount = val[0];
604         } else {
605             releaseBufferCount = 0;
606         }
607
608         if( releaseBufferCount > 0 ) {
609             final int[] buffers = new int[releaseBufferCount];
610             al.alSourceUnqueueBuffers(alSource[0], releaseBufferCount, buffers, 0);
611             alErr = al.alGetError();
612             if( ALConstants.AL_NO_ERROR != alErr ) {
613                 throw new RuntimeException(getThreadName()+": ALError "+toHexString(alErr)+" while dequeueing "+releaseBufferCount+" buffers. "+this);
614             }
615             for ( int i=0; i<releaseBufferCount; i++ ) {
616                 final ALAudioFrame releasedBuffer = alFramesPlaying.get();
617                 if( null == releasedBuffer ) {
618                     if( !ignoreBufferInconsistency ) {
619                         throw new InternalError("Internal Error: "+this);
620                     }
621                 } else {
622                     if(DEBUG_TRACE) {
623                         System.err.println("<  [al "+buffers[i]+", q "+releasedBuffer.alBuffer+"] <- "+shortString()+" @ "+getThreadName());
624                     }
625                     if( releasedBuffer.alBuffer != buffers[i] ) {
626                         if( !ignoreBufferInconsistency ) {
627                             alFramesAvail.dump(System.err, "Avail-deq02-post");
628                             alFramesPlaying.dump(System.err, "Playi-deq02-post");
629                             throw new InternalError("Buffer name mismatch: dequeued: "+buffers[i]+", released "+releasedBuffer+", "+this);
630                         }
631                     }
632                     alBufferBytesQueued -= releasedBuffer.getByteSize();
633                     if( !alFramesAvail.put(releasedBuffer) ) {
634                         throw new InternalError("Internal Error: "+this);
635                     }
636                     if(DEBUG_TRACE) {
637                         System.err.println("<< [al "+buffers[i]+", q "+releasedBuffer.alBuffer+"] <- "+shortString()+" @ "+getThreadName());
638                     }
639                 }
640             }
641         }
642         return releaseBufferCount;
643     }
644     private final void dequeueForceAll() {
645         if(DEBUG_TRACE) {
646             System.err.println("<   _FLUSH_  <- "+shortString()+" @ "+getThreadName());
647         }
648         final int[] val=new int[1];
649         al.alSourcei(alSource[0], ALConstants.AL_BUFFER, 0); // explicit force zero buffer!
650         if(DEBUG_TRACE) {
651             al.alGetSourcei(alSource[0], ALConstants.AL_BUFFERS_PROCESSED, val, 0);
652         }
653         final int alErr = al.alGetError();
654         while ( !alFramesPlaying.isEmpty() ) {
655             final ALAudioFrame releasedBuffer = alFramesPlaying.get();
656             if( null == releasedBuffer ) {
657                 throw new InternalError("Internal Error: "+this);
658             }
659             alBufferBytesQueued -= releasedBuffer.getByteSize();
660             if( !alFramesAvail.put(releasedBuffer) ) {
661                 throw new InternalError("Internal Error: "+this);
662             }
663         }
664         alBufferBytesQueued = 0;
665         if(DEBUG_TRACE) {
666             System.err.println("<<  _FLUSH_  [al "+val[0]+", err "+toHexString(alErr)+"] <- "+shortString()+" @ "+getThreadName());
667             ExceptionUtils.dumpStack(System.err);
668         }
669     }
670
671     private final int dequeueBuffer(final boolean wait, final int inPTS, final int inDuration) {
672         final int dequeuedBufferCount = dequeueBuffer( wait, false /* ignoreBufferInconsistency */ );
673         final ALAudioFrame currentBuffer = alFramesPlaying.peek();
674         if( null != currentBuffer ) {
675             playingPTS = currentBuffer.getPTS();
676         } else {
677             playingPTS = inPTS;
678         }
679         if( DEBUG ) {
680             if( dequeuedBufferCount > 0 ) {
681                 System.err.println(getThreadName()+": ALAudioSink: Write "+inPTS+", "+inDuration+" ms, dequeued "+dequeuedBufferCount+", wait "+wait+", "+getPerfString());
682             }
683         }
684         return dequeuedBufferCount;
685     }
686
687     @Override
688     public final AudioFrame enqueueData(final int pts, final ByteBuffer bytes, final int byteCount) {
689         if( !initialized || null == chosenFormat ) {
690             return null;
691         }
692         final ALAudioFrame alFrame;
693
694         // OpenAL consumes buffers in the background
695         // we first need to initialize the OpenAL buffers then
696         // start continuous playback.
697         lockContext();
698         try {
699             final int duration = chosenFormat.getBytesDuration(byteCount);
700             final boolean dequeueDone;
701             if( alFramesAvail.isEmpty() ) {
702                 // try to dequeue first
703                 dequeueDone = dequeueBuffer(false, pts, duration) > 0;
704                 if( alFramesAvail.isEmpty() ) {
705                     // try to grow
706                     growBuffers();
707                 }
708             } else {
709                 dequeueDone = false;
710             }
711             if( !dequeueDone && alFramesPlaying.size() > 0 ) { // dequeue only possible if playing ..
712                 final boolean wait = isPlayingImpl0() && alFramesAvail.isEmpty(); // possible if grow failed or already exceeds it's limit!
713                 dequeueBuffer(wait, pts, duration);
714             }
715
716             alFrame = alFramesAvail.get();
717             if( null == alFrame ) {
718                 alFramesAvail.dump(System.err, "Avail");
719                 throw new InternalError("Internal Error: avail.get null "+alFramesAvail+", "+this);
720             }
721             alFrame.setPTS(pts);
722             alFrame.setDuration(duration);
723             alFrame.setByteSize(byteCount);
724             if( !alFramesPlaying.put( alFrame ) ) {
725                 throw new InternalError("Internal Error: "+this);
726             }
727             final int[] alBufferNames = new int[] { alFrame.alBuffer };
728             if( hasSOFTBufferSamples ) {
729                 final int samplesPerChannel = chosenFormat.getBytesSampleCount(byteCount) / chosenFormat.channelCount;
730                 // final int samplesPerChannel = ALHelpers.bytesToSampleCount(byteCount, alChannelLayout, alSampleType);
731                 alExt.alBufferSamplesSOFT(alFrame.alBuffer, chosenFormat.sampleRate, alFormat,
732                                           samplesPerChannel, alChannelLayout, alSampleType, bytes);
733             } else {
734                 al.alBufferData(alFrame.alBuffer, alFormat, bytes, byteCount, chosenFormat.sampleRate);
735             }
736
737             if(DEBUG_TRACE) {
738                 System.err.println(">  "+alFrame.alBuffer+" -> "+shortString()+" @ "+getThreadName());
739             }
740
741             al.alSourceQueueBuffers(alSource[0], 1, alBufferNames, 0);
742             final int alErr = al.alGetError();
743             if( ALConstants.AL_NO_ERROR != alErr ) {
744                 throw new RuntimeException(getThreadName()+": ALError "+toHexString(alErr)+" while queueing buffer "+toHexString(alBufferNames[0])+". "+this);
745             }
746             alBufferBytesQueued += byteCount;
747             enqueuedFrameCount++; // safe: only written-to while locked!
748
749             if(DEBUG_TRACE) {
750                 System.err.println(">> "+alFrame.alBuffer+" -> "+shortString()+" @ "+getThreadName());
751             }
752
753             playImpl(); // continue playing, fixes issue where we ran out of enqueued data!
754         } finally {
755             unlockContext();
756         }
757         return alFrame;
758     }
759
760     @Override
761     public final boolean isPlaying() {
762         if( !initialized || null == chosenFormat ) {
763             return false;
764         }
765         if( playRequested ) {
766             lockContext();
767             try {
768                 return isPlayingImpl0();
769             } finally {
770                 unlockContext();
771             }
772         } else {
773             return false;
774         }
775     }
776     private final boolean isPlayingImpl0() {
777         if( playRequested ) {
778             return ALConstants.AL_PLAYING == getSourceState(false);
779         } else {
780             return false;
781         }
782     }
783     private final int getSourceState(final boolean ignoreError) {
784         final int[] val = new int[1];
785         al.alGetSourcei(alSource[0], ALConstants.AL_SOURCE_STATE, val, 0);
786         final int alErr = al.alGetError();
787         if( ALConstants.AL_NO_ERROR != alErr ) {
788             final String msg = getThreadName()+": ALError "+toHexString(alErr)+" while querying SOURCE_STATE. "+this;
789             if( ignoreError ) {
790                 if( DEBUG ) {
791                     System.err.println(msg);
792                 }
793             } else {
794                 throw new RuntimeException(msg);
795             }
796         }
797         return val[0];
798     }
799
800     @Override
801     public final void play() {
802         if( !initialized || null == chosenFormat ) {
803             return;
804         }
805         playRequested = true;
806         lockContext();
807         try {
808             playImpl();
809             if( DEBUG ) {
810                 System.err.println(getThreadName()+": ALAudioSink: PLAY playImpl "+(ALConstants.AL_PLAYING == getSourceState(false))+", "+this);
811             }
812         } finally {
813             unlockContext();
814         }
815     }
816     private final void playImpl() {
817         if( playRequested && ALConstants.AL_PLAYING != getSourceState(false) ) {
818             al.alSourcePlay(alSource[0]);
819             final int alErr = al.alGetError();
820             if( ALConstants.AL_NO_ERROR != alErr ) {
821                 throw new RuntimeException(getThreadName()+": ALError "+toHexString(alErr)+" while start playing. "+this);
822             }
823         }
824     }
825
826     @Override
827     public final void pause() {
828         if( !initialized || null == chosenFormat ) {
829             return;
830         }
831         if( playRequested ) {
832             lockContext();
833             try {
834                 pauseImpl();
835                 if( DEBUG ) {
836                     System.err.println(getThreadName()+": ALAudioSink: PAUSE playImpl "+(ALConstants.AL_PLAYING == getSourceState(false))+", "+this);
837                 }
838             } finally {
839                 unlockContext();
840             }
841         }
842     }
843     private final void pauseImpl() {
844         if( isPlayingImpl0() ) {
845             playRequested = false;
846             al.alSourcePause(alSource[0]);
847             final int alErr = al.alGetError();
848             if( ALConstants.AL_NO_ERROR != alErr ) {
849                 throw new RuntimeException(getThreadName()+": ALError "+toHexString(alErr)+" while pausing. "+this);
850             }
851         }
852     }
853     private final void stopImpl(final boolean ignoreError) {
854         if( ALConstants.AL_STOPPED != getSourceState(ignoreError) ) {
855             playRequested = false;
856             al.alSourceStop(alSource[0]);
857             final int alErr = al.alGetError();
858             if( ALConstants.AL_NO_ERROR != alErr ) {
859                 final String msg = "ALError "+toHexString(alErr)+" while stopping. "+this;
860                 if( ignoreError ) {
861                     if( DEBUG ) {
862                         System.err.println(getThreadName()+": "+msg);
863                     }
864                 } else {
865                     throw new RuntimeException(getThreadName()+": ALError "+toHexString(alErr)+" while stopping. "+this);
866                 }
867             }
868         }
869     }
870
871     @Override
872     public final float getPlaySpeed() { return playSpeed; }
873
874     @Override
875     public final boolean setPlaySpeed(float rate) {
876         if( !initialized || null == chosenFormat ) {
877             return false;
878         }
879         lockContext();
880         try {
881             if( Math.abs(1.0f - rate) < 0.01f ) {
882                 rate = 1.0f;
883             }
884             if( 0.5f <= rate && rate <= 2.0f ) { // OpenAL limits
885                 playSpeed = rate;
886                 al.alSourcef(alSource[0], ALConstants.AL_PITCH, playSpeed);
887                 return true;
888             }
889         } finally {
890             unlockContext();
891         }
892         return false;
893     }
894
895     @Override
896     public final float getVolume() {
897         return volume;
898     }
899
900     @Override
901     public final boolean setVolume(float v) {
902         if( !initialized || null == chosenFormat ) {
903             return false;
904         }
905         lockContext();
906         try {
907             if( Math.abs(v) < 0.01f ) {
908                 v = 0.0f;
909             } else if( Math.abs(1.0f - v) < 0.01f ) {
910                 v = 1.0f;
911             }
912             if( 0.0f <= v && v <= 1.0f ) { // OpenAL limits
913                 volume = v;
914                 al.alSourcef(alSource[0], ALConstants.AL_GAIN, v);
915                 return true;
916             }
917         } finally {
918             unlockContext();
919         }
920         return false;
921     }
922
923     @Override
924     public final void flush() {
925         if( !initialized || null == chosenFormat ) {
926             return;
927         }
928         lockContext();
929         try {
930             // pauseImpl();
931             stopImpl(false);
932             // Redundant: dequeueBuffer( false /* wait */, true /* ignoreBufferInconsistency */);
933             dequeueForceAll();
934             if( alBufferNames.length != alFramesAvail.size() || alFramesPlaying.size() != 0 ) {
935                 throw new InternalError("XXX: "+this);
936             }
937             if( DEBUG ) {
938                 System.err.println(getThreadName()+": ALAudioSink: FLUSH playImpl "+(ALConstants.AL_PLAYING == getSourceState(false))+", "+this);
939             }
940         } finally {
941             unlockContext();
942         }
943     }
944
945     @Override
946     public final int getEnqueuedFrameCount() {
947         return enqueuedFrameCount;
948     }
949
950     @Override
951     public final int getFrameCount() {
952         return null != alBufferNames ? alBufferNames.length : 0;
953     }
954
955     @Override
956     public final int getQueuedFrameCount() {
957         if( !initialized || null == chosenFormat ) {
958             return 0;
959         }
960         return alFramesPlaying.size();
961     }
962
963     @Override
964     public final int getFreeFrameCount() {
965         if( !initialized || null == chosenFormat ) {
966             return 0;
967         }
968         return alFramesAvail.size();
969     }
970
971     @Override
972     public final int getQueuedByteCount() {
973         if( !initialized || null == chosenFormat ) {
974             return 0;
975         }
976         return alBufferBytesQueued;
977     }
978
979     @Override
980     public final int getQueuedTime() {
981         if( !initialized || null == chosenFormat ) {
982             return 0;
983         }
984         return chosenFormat.getBytesDuration(alBufferBytesQueued);
985     }
986
987     @Override
988     public final int getPTS() { return playingPTS; }
989
990     private static final String toHexString(final int v) { return "0x"+Integer.toHexString(v); }
991     private static final String getThreadName() { return Thread.currentThread().getName(); }
992 }
http://JogAmp.org git info: FAQ, tutorial and man pages.