aboutsummaryrefslogtreecommitdiffstats
path: root/src/com/jsyn/engine/SynthesisEngine.java
blob: b49e78e66a70f4ff7e1230b3711cbbffb61b13f0 (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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
/*
 * Copyright 2009 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.engine;

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.Logger;

import com.jsyn.JSyn;
import com.jsyn.Synthesizer;
import com.jsyn.devices.AudioDeviceFactory;
import com.jsyn.devices.AudioDeviceInputStream;
import com.jsyn.devices.AudioDeviceManager;
import com.jsyn.devices.AudioDeviceOutputStream;
import com.jsyn.unitgen.UnitGenerator;
import com.softsynth.shared.time.ScheduledCommand;
import com.softsynth.shared.time.ScheduledQueue;
import com.softsynth.shared.time.TimeStamp;

//TODO Resolve problem with HearDAHDSR where "Rate" port.set is not reflected in knob. Engine not running.
//TODO new tutorial and docs on website
//TODO AutoStop on DAHDSR
//TODO Test/example SequentialData queueOn and queueOff

//TODO Abstract device interface. File device!
//TODO Measure thread switching sync, performance for multi-core synthesis. Use 4 core pro.
//TODO Optimize SineOscillatorPhaseModulated
//TODO More circuits.
//TODO DC blocker
//TODO Swing scope probe UIs, auto ranging

/**
 * Internal implementation of JSyn Synthesizer. The public API is in the Synthesizer interface. This
 * class might be used directly internally.
 *
 * @author Phil Burk (C) 2009 Mobileer Inc
 * @see Synthesizer
 */
public class SynthesisEngine implements Synthesizer {
    private final static int BLOCKS_PER_BUFFER = 8;
    private final static int FRAMES_PER_BUFFER = Synthesizer.FRAMES_PER_BLOCK * BLOCKS_PER_BUFFER;
    // I have measured JavaSound taking 1200 msec to close devices.
    private static final int MAX_THREAD_STOP_TIME = 2000;

    public static final int DEFAULT_FRAME_RATE = 44100;

    private final AudioDeviceManager audioDeviceManager;
    private EngineThread engineThread;
    private final ScheduledQueue<ScheduledCommand> commandQueue = new ScheduledQueue<ScheduledCommand>();

    private InterleavingBuffer inputBuffer;
    private InterleavingBuffer outputBuffer;
    private double inverseNyquist;
    private long frameCount;
    private boolean pullDataEnabled = true;
    private boolean useRealTime = true;
    private boolean started;
    private int frameRate = DEFAULT_FRAME_RATE;
    private double framePeriod = 1.0 / frameRate;

    // List of all units added to the synth.
    private final ArrayList<UnitGenerator> allUnitList = new ArrayList<UnitGenerator>();
    // List of running units.
    private final ArrayList<UnitGenerator> runningUnitList = new ArrayList<UnitGenerator>();
    // List of units stopping because of autoStop.
    private final ArrayList<UnitGenerator> stoppingUnitList = new ArrayList<UnitGenerator>();

    private LoadAnalyzer loadAnalyzer;
    // private int numOutputChannels;
    // private int numInputChannels;
    private final CopyOnWriteArrayList<Runnable> audioTasks = new CopyOnWriteArrayList<Runnable>();
    private double mOutputLatency;
    private double mInputLatency;
    /** A fraction corresponding to exactly -96 dB. */
    public static final double DB96 = (1.0 / 63095.73444801943);
    /** A fraction that is approximately -90.3 dB. Defined as 1 bit of an S16. */
    public static final double DB90 = (1.0 / (1 << 15));

    static Logger logger = Logger.getLogger(SynthesisEngine.class.getName());

    public SynthesisEngine(AudioDeviceManager audioDeviceManager) {
        this.audioDeviceManager = audioDeviceManager;
    }

    public SynthesisEngine() {
        this(AudioDeviceFactory.createAudioDeviceManager());
    }

    @Override
    public String getVersion() {
        return JSyn.VERSION;
    }

    @Override
    public int getVersionCode() {
        return JSyn.VERSION_CODE;
    }

    @Override
    public String toString() {
        return "JSyn " + JSyn.VERSION_TEXT;
    }

    public boolean isPullDataEnabled() {
        return pullDataEnabled;
    }

    /**
     * If set true then audio data will be pulled from the output ports of connected unit
     * generators. The final unit in a tree of units needs to be start()ed.
     *
     * @param pullDataEnabled
     */
    public void setPullDataEnabled(boolean pullDataEnabled) {
        this.pullDataEnabled = pullDataEnabled;
    }

    private void setupAudioBuffers(int numInputChannels, int numOutputChannels) {
        inputBuffer = new InterleavingBuffer(FRAMES_PER_BUFFER, Synthesizer.FRAMES_PER_BLOCK,
                numInputChannels);
        outputBuffer = new InterleavingBuffer(FRAMES_PER_BUFFER, Synthesizer.FRAMES_PER_BLOCK,
                numOutputChannels);
    }

    public void terminate() {
    }

    class InterleavingBuffer {
        private final double[] interleavedBuffer;
        ChannelBlockBuffer[] blockBuffers;

        InterleavingBuffer(int framesPerBuffer, int framesPerBlock, int samplesPerFrame) {
            interleavedBuffer = new double[framesPerBuffer * samplesPerFrame];
            // Allocate buffers for each channel of synthesis output.
            blockBuffers = new ChannelBlockBuffer[samplesPerFrame];
            for (int i = 0; i < blockBuffers.length; i++) {
                blockBuffers[i] = new ChannelBlockBuffer(framesPerBlock);
            }
        }

        int deinterleave(int inIndex) {
            for (int jf = 0; jf < Synthesizer.FRAMES_PER_BLOCK; jf++) {
                for (int iob = 0; iob < blockBuffers.length; iob++) {
                    ChannelBlockBuffer buffer = blockBuffers[iob];
                    buffer.values[jf] = interleavedBuffer[inIndex++];
                }
            }
            return inIndex;
        }

        int interleave(int outIndex) {
            for (int jf = 0; jf < Synthesizer.FRAMES_PER_BLOCK; jf++) {
                for (int iob = 0; iob < blockBuffers.length; iob++) {
                    ChannelBlockBuffer buffer = blockBuffers[iob];
                    interleavedBuffer[outIndex++] = buffer.values[jf];
                }
            }
            return outIndex;
        }

        public double[] getChannelBuffer(int i) {
            return blockBuffers[i].values;
        }

        public void clear() {
            for (int i = 0; i < blockBuffers.length; i++) {
                blockBuffers[i].clear();
            }
        }
    }

    class ChannelBlockBuffer {
        private final double[] values;

        ChannelBlockBuffer(int framesPerBlock) {
            values = new double[framesPerBlock];
        }

        void clear() {
            for (int i = 0; i < values.length; i++) {
                values[i] = 0.0f;
            }
        }
    }

    @Override
    public void start() {
        // TODO Use constants.
        start(DEFAULT_FRAME_RATE, -1, 0, -1, 2);
    }

    @Override
    public void start(int frameRate) {
        // TODO Use constants.
        start(frameRate, -1, 0, -1, 2);
    }

    @Override
    public synchronized void start(int frameRate, int inputDeviceID, int numInputChannels,
            int outputDeviceID, int numOutputChannels) {
        if (started) {
            logger.info("JSyn already started.");
            return;
        }

        this.frameRate = frameRate;
        this.framePeriod = 1.0 / frameRate;

        setupAudioBuffers(numInputChannels, numOutputChannels);

        logger.info("Pure Java JSyn from www.softsynth.com, rate = " + frameRate + ", "
                + (useRealTime ? "RT" : "NON-RealTime") + ", " + JSyn.VERSION_TEXT);

        inverseNyquist = 2.0 / frameRate;

        if (useRealTime) {
            engineThread = new EngineThread(inputDeviceID, numInputChannels,
                    outputDeviceID, numOutputChannels);
            logger.fine("Synth thread old priority = " + engineThread.getPriority());
            int engineThreadPriority = engineThread.getPriority() + 2 > Thread.MAX_PRIORITY ?
                Thread.MAX_PRIORITY : engineThread.getPriority() + 2;
            engineThread.setPriority(engineThreadPriority);
            logger.fine("Synth thread new priority = " + engineThread.getPriority());
            engineThread.start();
        }

        started = true;
    }

    @Override
    public boolean isRunning() {
        Thread thread = engineThread;
        return (thread != null) && thread.isAlive();
    }

    @Override
    public synchronized void stop() {
        if (!started) {
            logger.info("JSyn already stopped.");
            return;
        }

        if (useRealTime) {
            // Stop audio synthesis and all units.
            if (engineThread != null) {
                try {
                    // Interrupt now, otherwise audio thread will wait for audio I/O.
                    engineThread.requestStop();
                    engineThread.join(MAX_THREAD_STOP_TIME);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        synchronized (runningUnitList) {
            runningUnitList.clear();
        }
        started = false;
    }

    private class EngineThread extends Thread
    {
        private AudioDeviceOutputStream audioOutputStream;
        private AudioDeviceInputStream audioInputStream;
        private volatile boolean go = true;

        EngineThread(int inputDeviceID, int numInputChannels,
            int outputDeviceID, int numOutputChannels) {
            if (numInputChannels > 0) {
                audioInputStream = audioDeviceManager.createInputStream(inputDeviceID, frameRate,
                        numInputChannels);
            }
            if (numOutputChannels > 0) {
                audioOutputStream = audioDeviceManager.createOutputStream(outputDeviceID,
                        frameRate, numOutputChannels);
            }
        }

        public void requestStop() {
            go = false;
            interrupt();
        }

        @Override
        public void run() {
            logger.fine("JSyn synthesis thread starting.");
            try {
                if (audioInputStream != null) {
                    logger.finer("JSyn synthesis thread trying to start audio INPUT!");
                    audioInputStream.start();
                    mInputLatency = audioInputStream.getLatency();
                    String msg = String.format("Input Latency in = %5.1f msec",
                            1000 * mInputLatency);
                    logger.fine(msg);
                }
                if (audioOutputStream != null) {
                    logger.finer("JSyn synthesis thread trying to start audio OUTPUT!");
                    audioOutputStream.start();
                    mOutputLatency = audioOutputStream.getLatency();
                    String msg = String.format("Output Latency = %5.1f msec",
                            1000 * mOutputLatency);
                    logger.fine(msg);
                    // Buy some time while we fill the buffer.
                    audioOutputStream.write(outputBuffer.interleavedBuffer);
                }
                loadAnalyzer = new LoadAnalyzer();
                while (go) {
                    boolean throttled = false;
                    if (audioInputStream != null) {
                        // This call will block when the input is empty.
                        audioInputStream.read(inputBuffer.interleavedBuffer);
                        throttled = true;
                    }

                    loadAnalyzer.start();
                    runAudioTasks();
                    generateNextBuffer();
                    loadAnalyzer.stop();

                    if (audioOutputStream != null) {
                        // This call will block when the output is full.
                        audioOutputStream.write(outputBuffer.interleavedBuffer);
                        throttled = true;
                    }
                    if (!throttled && isRealTime()) {
                        Thread.sleep(2); // avoid spinning and eating up CPU
                    }
                }

            } catch (Throwable e) {
                e.printStackTrace();
                go = false;

            } finally {
                logger.info("JSyn synthesis thread in finally code.");
                // Stop audio system.
                if (audioInputStream != null) {
                    audioInputStream.stop();
                }
                if (audioOutputStream != null) {
                    audioOutputStream.stop();
                }
            }
            logger.fine("JSyn synthesis thread exiting.");
        }
    }

    private void runAudioTasks() {
        for (Runnable task : audioTasks) {
            task.run();
        }
    }

    // TODO We need to implement a sharedSleeper like we use in JSyn1.
    public void generateNextBuffer() {
        int outIndex = 0;
        int inIndex = 0;
        for (int i = 0; i < BLOCKS_PER_BUFFER; i++) {
            if (inputBuffer != null) {
                inIndex = inputBuffer.deinterleave(inIndex);
            }

            TimeStamp timeStamp = createTimeStamp();
            // Try putting this up here so incoming time-stamped events will get
            // scheduled later.
            processScheduledCommands(timeStamp);
            clearBlockBuffers();
            synthesizeBuffer();

            if (outputBuffer != null) {
                outIndex = outputBuffer.interleave(outIndex);
            }
            frameCount += Synthesizer.FRAMES_PER_BLOCK;
        }
    }

    @Override
    public double getCurrentTime() {
        return frameCount * framePeriod;
    }

    @Override
    public TimeStamp createTimeStamp() {
        return new TimeStamp(getCurrentTime());
    }

    private void processScheduledCommands(TimeStamp timeStamp) {
        List<ScheduledCommand> timeList = commandQueue.removeNextList(timeStamp);

        while (timeList != null) {
            while (!timeList.isEmpty()) {
                ScheduledCommand command = timeList.remove(0);
                logger.fine("processing " + command + ", at time " + timeStamp.getTime());
                command.run();
            }
            // Get next list of commands at the given time.
            timeList = commandQueue.removeNextList(timeStamp);
        }
    }

    @Override
    public void scheduleCommand(TimeStamp timeStamp, ScheduledCommand command) {
        if ((Thread.currentThread() == engineThread) && (timeStamp.getTime() <= getCurrentTime())) {
            command.run();
        } else {
            logger.fine("scheduling " + command + ", at time " + timeStamp.getTime());
            commandQueue.add(timeStamp, command);
        }
    }

    @Override
    public void scheduleCommand(double time, ScheduledCommand command) {
        TimeStamp timeStamp = new TimeStamp(time);
        scheduleCommand(timeStamp, command);
    }

    @Override
    public void queueCommand(ScheduledCommand command) {
        TimeStamp timeStamp = createTimeStamp();
        scheduleCommand(timeStamp, command);
    }

    @Override
    public void clearCommandQueue() {
        commandQueue.clear();
    }

    private void clearBlockBuffers() {
        outputBuffer.clear();
    }

    private void synthesizeBuffer() {
        synchronized (runningUnitList) {
            ListIterator<UnitGenerator> iterator = runningUnitList.listIterator();
            while (iterator.hasNext()) {
                UnitGenerator unit = iterator.next();
                if (pullDataEnabled) {
                    unit.pullData(getFrameCount(), 0, Synthesizer.FRAMES_PER_BLOCK);
                } else {
                    unit.generate(0, Synthesizer.FRAMES_PER_BLOCK);
                }
            }
            // Remove any units that got auto stopped.
            for (UnitGenerator ugen : stoppingUnitList) {
                runningUnitList.remove(ugen);
                ugen.flattenOutputs();
            }
        }
        stoppingUnitList.clear();
    }

    public double[] getInputBuffer(int i) {
        try {
            return inputBuffer.getChannelBuffer(i);
        } catch (ArrayIndexOutOfBoundsException e) {
            throw new RuntimeException("Audio Input not configured in start() method.");
        }
    }

    public double[] getOutputBuffer(int i) {
        try {
            return outputBuffer.getChannelBuffer(i);
        } catch (ArrayIndexOutOfBoundsException e) {
            throw new RuntimeException("Audio Output not configured in start() method.");
        }
    }

    private void internalStopUnit(UnitGenerator unit) {
        synchronized (runningUnitList) {
            runningUnitList.remove(unit);
        }
        unit.flattenOutputs();
    }

    public void autoStopUnit(UnitGenerator unitGenerator) {
        synchronized (stoppingUnitList) {
            stoppingUnitList.add(unitGenerator);
        }
    }

    @Override
    public void startUnit(UnitGenerator unit, double time) {
        startUnit(unit, new TimeStamp(time));
    }

    @Override
    public void stopUnit(UnitGenerator unit, double time) {
        stopUnit(unit, new TimeStamp(time));
    }

    @Override
    public void startUnit(final UnitGenerator unit, TimeStamp timeStamp) {
        // Don't start if it is a component in a circuit because it will be
        // executed by the circuit.
        if (unit.getCircuit() == null) {
            scheduleCommand(timeStamp, new ScheduledCommand() {
                @Override
                public void run() {
                    internalStartUnit(unit);
                }
            });
        }
    }

    @Override
    public void stopUnit(final UnitGenerator unit, TimeStamp timeStamp) {
        scheduleCommand(timeStamp, new ScheduledCommand() {
            @Override
            public void run() {
                internalStopUnit(unit);
            }
        });
    }

    @Override
    public void startUnit(UnitGenerator unit) {
        startUnit(unit, createTimeStamp());
    }

    @Override
    public void stopUnit(UnitGenerator unit) {
        stopUnit(unit, createTimeStamp());
    }

    private void internalStartUnit(UnitGenerator unit) {
        // logger.info( "internalStartUnit " + unit + " with circuit " +
        // unit.getCircuit() );
        if (unit.getCircuit() == null) {
            synchronized (runningUnitList) {
                if (!runningUnitList.contains(unit)) {
                    runningUnitList.add(unit);
                }
            }
        }
        // else
        // {
        // logger.info(
        // "internalStartUnit detected race condition !!!! from old JSyn" + unit
        // + " with circuit " + unit.getCircuit() );
        // }
    }

    public double getInverseNyquist() {
        return inverseNyquist;
    }

    public double convertTimeToExponentialScaler(double duration) {
        // Calculate scaler so that scaler^frames = target/source
        double numFrames = duration * getFrameRate();
        return Math.pow(DB90, (1.0 / numFrames));
    }

    @Override
    public long getFrameCount() {
        return frameCount;
    }

    /**
     * @return the frameRate
     */
    @Override
    public int getFrameRate() {
        return frameRate;
    }

    /**
     * @return the inverse of the frameRate for efficiency
     */
    @Override
    public double getFramePeriod() {
        return framePeriod;
    }

    /** Convert a short value to a double in the range -1.0 to almost 1.0. */
    public static double convertShortToDouble(short sdata) {
        return (sdata * (1.0 / Short.MAX_VALUE));
    }

    /**
     * Convert a double value in the range -1.0 to almost 1.0 to a short. Double value is clipped
     * before converting.
     */
    public static short convertDoubleToShort(double d) {
        final double maxValue = ((double) (Short.MAX_VALUE - 1)) / Short.MAX_VALUE;
        if (d > maxValue) {
            d = maxValue;
        } else if (d < -1.0) {
            d = -1.0;
        }
        return (short) (d * Short.MAX_VALUE);
    }

    @Override
    public void addAudioTask(Runnable blockTask) {
        audioTasks.add(blockTask);
    }

    @Override
    public void removeAudioTask(Runnable blockTask) {
        audioTasks.remove(blockTask);
    }

    @Override
    public double getUsage() {
        // use temp so we don't have to synchronize
        LoadAnalyzer temp = loadAnalyzer;
        if (temp != null) {
            return temp.getAverageLoad();
        } else {
            return 0.0;
        }
    }

    @Override
    public AudioDeviceManager getAudioDeviceManager() {
        return audioDeviceManager;
    }

    @Override
    public void setRealTime(boolean realTime) {
        useRealTime = realTime;
    }

    @Override
    public boolean isRealTime() {
        return useRealTime;
    }

    public double getOutputLatency() {
        return mOutputLatency;
    }

    public double getInputLatency() {
        return mInputLatency;
    }

    @Override
    public void add(UnitGenerator ugen) {
        ugen.setSynthesisEngine(this);
        allUnitList.add(ugen);
    }

    @Override
    public void remove(UnitGenerator ugen) {
        allUnitList.remove(ugen);
    }

    @Override
    public void sleepUntil(double time) throws InterruptedException {
        double timeToSleep = time - getCurrentTime();
        while (timeToSleep > 0.0) {
            if (useRealTime) {
                long msecToSleep = (long) (1000 * timeToSleep);
                if (msecToSleep <= 0) {
                    msecToSleep = 1;
                }
                Thread.sleep(msecToSleep);
            } else {

                generateNextBuffer();
            }
            timeToSleep = time - getCurrentTime();
        }
    }

    @Override
    public void sleepFor(double duration) throws InterruptedException {
        sleepUntil(getCurrentTime() + duration);
    }

    public void printConnections() {
        if (pullDataEnabled) {
            ListIterator<UnitGenerator> iterator = runningUnitList.listIterator();
            while (iterator.hasNext()) {
                UnitGenerator unit = iterator.next();
                unit.printConnections();
            }
        }

    }

}