summaryrefslogtreecommitdiff
path: root/distrho/src/DistrhoPluginJack.cpp
blob: ef2b77a7bb6b2cf1c84885a03e8ac8ad298b5494 (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
/*
 * DISTRHO Plugin Framework (DPF)
 * Copyright (C) 2012-2018 Filipe Coelho <falktx@falktx.com>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * For a full copy of the license see the LGPL.txt file
 */

#include "DistrhoPluginInternal.hpp"

#if DISTRHO_PLUGIN_HAS_UI && ! DISTRHO_PLUGIN_HAS_EMBED_UI
# undef DISTRHO_PLUGIN_HAS_UI
# define DISTRHO_PLUGIN_HAS_UI 0
#endif

#if DISTRHO_PLUGIN_HAS_UI
# include "DistrhoUIInternal.hpp"
#else
# include "../extra/Sleep.hpp"
#endif

#include "jack/jack.h"
#include "jack/midiport.h"
#include "jack/transport.h"

#ifndef DISTRHO_OS_WINDOWS
# include <signal.h>
#endif

// -----------------------------------------------------------------------

START_NAMESPACE_DISTRHO

#if DISTRHO_PLUGIN_HAS_UI && ! DISTRHO_PLUGIN_WANT_STATE
static const setStateFunc setStateCallback = nullptr;
#endif
#if ! DISTRHO_PLUGIN_WANT_MIDI_OUTPUT
static const writeMidiFunc writeMidiCallback = nullptr;
#endif

// -----------------------------------------------------------------------

static volatile bool gCloseSignalReceived = false;

#ifdef DISTRHO_OS_WINDOWS
static BOOL WINAPI winSignalHandler(DWORD dwCtrlType) noexcept
{
    if (dwCtrlType == CTRL_C_EVENT)
    {
        gCloseSignalReceived = true;
        return TRUE;
    }
    return FALSE;
}

static void initSignalHandler()
{
    SetConsoleCtrlHandler(winSignalHandler, TRUE);
}
#else
static void closeSignalHandler(int) noexcept
{
    gCloseSignalReceived = true;
}

static void initSignalHandler()
{
    struct sigaction sig;
    memset(&sig, 0, sizeof(sig));

    sig.sa_handler = closeSignalHandler;
    sig.sa_flags   = SA_RESTART;
    sigemptyset(&sig.sa_mask);
    sigaction(SIGINT, &sig, nullptr);
    sigaction(SIGTERM, &sig, nullptr);
}
#endif

// -----------------------------------------------------------------------

#if DISTRHO_PLUGIN_HAS_UI
class PluginJack : public IdleCallback
#else
class PluginJack
#endif
{
public:
    PluginJack(jack_client_t* const client)
        : fPlugin(this, writeMidiCallback),
#if DISTRHO_PLUGIN_HAS_UI
          fUI(this, 0, nullptr, setParameterValueCallback, setStateCallback, nullptr, setSizeCallback, fPlugin.getInstancePointer()),
#endif
          fClient(client)
    {
#if DISTRHO_PLUGIN_NUM_INPUTS > 0 || DISTRHO_PLUGIN_NUM_OUTPUTS > 0
        char strBuf[0xff+1];
        strBuf[0xff] = '\0';

# if DISTRHO_PLUGIN_NUM_INPUTS > 0
        for (uint32_t i=0; i < DISTRHO_PLUGIN_NUM_INPUTS; ++i)
        {
            std::snprintf(strBuf, 0xff, "in%i", i+1);
            fPortAudioIns[i] = jack_port_register(fClient, strBuf, JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0);
        }
# endif
# if DISTRHO_PLUGIN_NUM_OUTPUTS > 0
        for (uint32_t i=0; i < DISTRHO_PLUGIN_NUM_OUTPUTS; ++i)
        {
            std::snprintf(strBuf, 0xff, "out%i", i+1);
            fPortAudioOuts[i] = jack_port_register(fClient, strBuf, JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0);
        }
# endif
#endif

        fPortEventsIn = jack_port_register(fClient, "events-in", JACK_DEFAULT_MIDI_TYPE, JackPortIsInput, 0);

#if DISTRHO_PLUGIN_WANT_MIDI_OUTPUT
        fPortMidiOut = jack_port_register(fClient, "midi-out", JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput, 0);
        fPortMidiOutBuffer = nullptr;
#endif

#if DISTRHO_PLUGIN_WANT_PROGRAMS
        if (fPlugin.getProgramCount() > 0)
        {
            fPlugin.loadProgram(0);
# if DISTRHO_PLUGIN_HAS_UI
            fUI.programLoaded(0);
# endif
        }
# if DISTRHO_PLUGIN_HAS_UI
        fProgramChanged = -1;
# endif
#endif

        if (const uint32_t count = fPlugin.getParameterCount())
        {
            fLastOutputValues = new float[count];
#if DISTRHO_PLUGIN_HAS_UI
            fParametersChanged = new bool[count];
            std::memset(fParametersChanged, 0, sizeof(bool)*count);
#endif

            for (uint32_t i=0; i < count; ++i)
            {
                if (fPlugin.isParameterOutput(i))
                {
                    fLastOutputValues[i] = fPlugin.getParameterValue(i);
                }
                else
                {
                    fLastOutputValues[i] = 0.0f;
#if DISTRHO_PLUGIN_HAS_UI
                    fUI.parameterChanged(i, fPlugin.getParameterValue(i));
#endif
                }
            }
        }
        else
        {
            fLastOutputValues = nullptr;
#if DISTRHO_PLUGIN_HAS_UI
            fParametersChanged = nullptr;
#endif
        }

        jack_set_buffer_size_callback(fClient, jackBufferSizeCallback, this);
        jack_set_sample_rate_callback(fClient, jackSampleRateCallback, this);
        jack_set_process_callback(fClient, jackProcessCallback, this);
        jack_on_shutdown(fClient, jackShutdownCallback, this);

        fPlugin.activate();

        jack_activate(fClient);

#if DISTRHO_PLUGIN_HAS_UI
        if (const char* const name = jack_get_client_name(fClient))
            fUI.setWindowTitle(name);
        else
            fUI.setWindowTitle(fPlugin.getName());

        fUI.exec(this);
#else
        while (! gCloseSignalReceived)
            d_sleep(1);
#endif
    }

    ~PluginJack()
    {
        if (fClient != nullptr)
            jack_deactivate(fClient);

        if (fLastOutputValues != nullptr)
        {
            delete[] fLastOutputValues;
            fLastOutputValues = nullptr;
        }

#if DISTRHO_PLUGIN_HAS_UI
        if (fParametersChanged != nullptr)
        {
            delete[] fParametersChanged;
            fParametersChanged = nullptr;
        }
#endif

        fPlugin.deactivate();

        if (fClient == nullptr)
            return;

#if DISTRHO_PLUGIN_WANT_MIDI_OUTPUT
        jack_port_unregister(fClient, fPortMidiOut);
        fPortMidiOut = nullptr;
#endif

        jack_port_unregister(fClient, fPortEventsIn);
        fPortEventsIn = nullptr;

#if DISTRHO_PLUGIN_NUM_INPUTS > 0
        for (uint32_t i=0; i < DISTRHO_PLUGIN_NUM_INPUTS; ++i)
        {
            jack_port_unregister(fClient, fPortAudioIns[i]);
            fPortAudioIns[i] = nullptr;
        }
#endif

#if DISTRHO_PLUGIN_NUM_OUTPUTS > 0
        for (uint32_t i=0; i < DISTRHO_PLUGIN_NUM_OUTPUTS; ++i)
        {
            jack_port_unregister(fClient, fPortAudioOuts[i]);
            fPortAudioOuts[i] = nullptr;
        }
#endif

        jack_client_close(fClient);
    }

    // -------------------------------------------------------------------

protected:
#if DISTRHO_PLUGIN_HAS_UI
    void idleCallback() override
    {
        if (gCloseSignalReceived)
            return fUI.quit();

# if DISTRHO_PLUGIN_WANT_PROGRAMS
        if (fProgramChanged >= 0)
        {
            fUI.programLoaded(fProgramChanged);
            fProgramChanged = -1;
        }
# endif

        for (uint32_t i=0, count=fPlugin.getParameterCount(); i < count; ++i)
        {
            if (fPlugin.isParameterOutput(i))
            {
                const float value = fPlugin.getParameterValue(i);

                if (d_isEqual(fLastOutputValues[i], value))
                    continue;

                fLastOutputValues[i] = value;
                fUI.parameterChanged(i, value);
            }
            else if (fParametersChanged[i])
            {
                fParametersChanged[i] = false;
                fUI.parameterChanged(i, fPlugin.getParameterValue(i));
            }
        }

        fUI.exec_idle();
    }
#endif

    void jackBufferSize(const jack_nframes_t nframes)
    {
        fPlugin.setBufferSize(nframes, true);
    }

    void jackSampleRate(const jack_nframes_t nframes)
    {
        fPlugin.setSampleRate(nframes, true);
    }

    void jackProcess(const jack_nframes_t nframes)
    {
#if DISTRHO_PLUGIN_NUM_INPUTS > 0
        const float* audioIns[DISTRHO_PLUGIN_NUM_INPUTS];

        for (uint32_t i=0; i < DISTRHO_PLUGIN_NUM_INPUTS; ++i)
            audioIns[i] = (const float*)jack_port_get_buffer(fPortAudioIns[i], nframes);
#else
        static const float** audioIns = nullptr;
#endif

#if DISTRHO_PLUGIN_NUM_OUTPUTS > 0
        float* audioOuts[DISTRHO_PLUGIN_NUM_OUTPUTS];

        for (uint32_t i=0; i < DISTRHO_PLUGIN_NUM_OUTPUTS; ++i)
            audioOuts[i] = (float*)jack_port_get_buffer(fPortAudioOuts[i], nframes);
#else
        static float** audioOuts = nullptr;
#endif

#if DISTRHO_PLUGIN_WANT_TIMEPOS
        jack_position_t pos;
        fTimePosition.playing = (jack_transport_query(fClient, &pos) == JackTransportRolling);

        if (pos.unique_1 == pos.unique_2)
        {
            fTimePosition.frame = pos.frame;

            if (pos.valid & JackTransportBBT)
            {
                fTimePosition.bbt.valid = true;

                fTimePosition.bbt.bar  = pos.bar;
                fTimePosition.bbt.beat = pos.beat;
                fTimePosition.bbt.tick = pos.tick;
                fTimePosition.bbt.barStartTick = pos.bar_start_tick;

                fTimePosition.bbt.beatsPerBar = pos.beats_per_bar;
                fTimePosition.bbt.beatType    = pos.beat_type;

                fTimePosition.bbt.ticksPerBeat   = pos.ticks_per_beat;
                fTimePosition.bbt.beatsPerMinute = pos.beats_per_minute;
            }
            else
                fTimePosition.bbt.valid = false;
        }
        else
        {
            fTimePosition.bbt.valid = false;
            fTimePosition.frame = 0;
        }

        fPlugin.setTimePosition(fTimePosition);
#endif

        void* const midiBuf = jack_port_get_buffer(fPortEventsIn, nframes);

#if DISTRHO_PLUGIN_WANT_MIDI_OUTPUT
        fPortMidiOutBuffer = jack_port_get_buffer(fPortMidiOut, nframes);
        jack_midi_clear_buffer(fPortMidiOutBuffer);
#endif

        if (const uint32_t eventCount = jack_midi_get_event_count(midiBuf))
        {
#if DISTRHO_PLUGIN_WANT_MIDI_INPUT
            uint32_t  midiEventCount = 0;
            MidiEvent midiEvents[eventCount];
#endif
            jack_midi_event_t jevent;

            for (uint32_t i=0; i < eventCount; ++i)
            {
                if (jack_midi_event_get(&jevent, midiBuf, i) != 0)
                    break;

                // Check if message is control change on channel 1
                if (jevent.buffer[0] == 0xB0 && jevent.size == 3)
                {
                    const uint8_t control = jevent.buffer[1];
                    const uint8_t value   = jevent.buffer[2];

                    /* NOTE: This is not optimal, we're iterating all parameters on every CC message.
                             Since the JACK standalone is more of a test tool, this will do for now. */
                    for (uint32_t j=0, paramCount=fPlugin.getParameterCount(); j < paramCount; ++j)
                    {
                        if (fPlugin.isParameterOutput(j))
                            continue;
                        if (fPlugin.getParameterMidiCC(j) != control)
                            continue;

                        const float scaled = static_cast<float>(value)/127.0f;
                        const float fvalue = fPlugin.getParameterRanges(j).getUnnormalizedValue(scaled);
                        fPlugin.setParameterValue(j, fvalue);
#if DISTRHO_PLUGIN_HAS_UI
                        fParametersChanged[j] = true;
#endif
                        break;
                    }
                }
#if DISTRHO_PLUGIN_WANT_PROGRAMS
                // Check if message is program change on channel 1
                else if (jevent.buffer[0] == 0xC0 && jevent.size == 2)
                {
                    const uint8_t program = jevent.buffer[1];

                    if (program < fPlugin.getProgramCount())
                    {
                        fPlugin.loadProgram(program);
# if DISTRHO_PLUGIN_HAS_UI
                        fProgramChanged = program;
# endif
                    }
                }
#endif

#if DISTRHO_PLUGIN_WANT_MIDI_INPUT
                MidiEvent& midiEvent(midiEvents[midiEventCount++]);

                midiEvent.frame = jevent.time;
                midiEvent.size  = jevent.size;

                if (midiEvent.size > MidiEvent::kDataSize)
                    midiEvent.dataExt = jevent.buffer;
                else
                    std::memcpy(midiEvent.data, jevent.buffer, midiEvent.size);
#endif
            }

#if DISTRHO_PLUGIN_WANT_MIDI_INPUT
            fPlugin.run(audioIns, audioOuts, nframes, midiEvents, midiEventCount);
#endif
        }
#if DISTRHO_PLUGIN_WANT_MIDI_INPUT
        else
        {
            fPlugin.run(audioIns, audioOuts, nframes, nullptr, 0);
        }
#else
        fPlugin.run(audioIns, audioOuts, nframes);
#endif

#if DISTRHO_PLUGIN_WANT_MIDI_OUTPUT
        fPortMidiOutBuffer = nullptr;
#endif

        updateParameterTriggers();
    }

    void jackShutdown()
    {
        d_stderr("jack has shutdown, quitting now...");
        fClient = nullptr;
#if DISTRHO_PLUGIN_HAS_UI
        fUI.quit();
#endif
    }

    // -------------------------------------------------------------------

    void setParameterValue(const uint32_t index, const float value)
    {
        fPlugin.setParameterValue(index, value);
    }

#if DISTRHO_PLUGIN_WANT_STATE
    void setState(const char* const key, const char* const value)
    {
        fPlugin.setState(key, value);
    }
#endif

#if DISTRHO_PLUGIN_HAS_UI
    void setSize(const uint width, const uint height)
    {
        fUI.setWindowSize(width, height);
    }
#endif

#if DISTRHO_PLUGIN_WANT_MIDI_OUTPUT
    bool writeMidi(const MidiEvent& midiEvent)
    {
        DISTRHO_SAFE_ASSERT_RETURN(fPortMidiOutBuffer != nullptr, false);

        return jack_midi_event_write(fPortMidiOutBuffer,
                                     midiEvent.frame,
                                     midiEvent.size > MidiEvent::kDataSize ? midiEvent.dataExt : midiEvent.data,
                                     midiEvent.size) == 0;
    }
#endif

    // NOTE: no trigger support for JACK, simulate it here
    void updateParameterTriggers()
    {
        float defValue;

        for (uint32_t i=0, count=fPlugin.getParameterCount(); i < count; ++i)
        {
            if ((fPlugin.getParameterHints(i) & kParameterIsTrigger) != kParameterIsTrigger)
                continue;

            defValue = fPlugin.getParameterRanges(i).def;

            if (d_isNotEqual(defValue, fPlugin.getParameterValue(i)))
                fPlugin.setParameterValue(i, defValue);
        }
    }

    // -------------------------------------------------------------------

private:
    PluginExporter fPlugin;
#if DISTRHO_PLUGIN_HAS_UI
    UIExporter     fUI;
#endif

    jack_client_t* fClient;

#if DISTRHO_PLUGIN_NUM_INPUTS > 0
    jack_port_t* fPortAudioIns[DISTRHO_PLUGIN_NUM_INPUTS];
#endif
#if DISTRHO_PLUGIN_NUM_OUTPUTS > 0
    jack_port_t* fPortAudioOuts[DISTRHO_PLUGIN_NUM_OUTPUTS];
#endif
    jack_port_t* fPortEventsIn;
#if DISTRHO_PLUGIN_WANT_MIDI_OUTPUT
    jack_port_t* fPortMidiOut;
    void*        fPortMidiOutBuffer;
#endif
#if DISTRHO_PLUGIN_WANT_TIMEPOS
    TimePosition fTimePosition;
#endif

    // Temporary data
    float* fLastOutputValues;

#if DISTRHO_PLUGIN_HAS_UI
    // Store DSP changes to send to UI
    bool* fParametersChanged;
# if DISTRHO_PLUGIN_WANT_PROGRAMS
    int fProgramChanged;
# endif
#endif

    // -------------------------------------------------------------------
    // Callbacks

    #define thisPtr ((PluginJack*)ptr)

    static int jackBufferSizeCallback(jack_nframes_t nframes, void* ptr)
    {
        thisPtr->jackBufferSize(nframes);
        return 0;
    }

    static int jackSampleRateCallback(jack_nframes_t nframes, void* ptr)
    {
        thisPtr->jackSampleRate(nframes);
        return 0;
    }

    static int jackProcessCallback(jack_nframes_t nframes, void* ptr)
    {
        thisPtr->jackProcess(nframes);
        return 0;
    }

    static void jackShutdownCallback(void* ptr)
    {
        thisPtr->jackShutdown();
    }

    static void setParameterValueCallback(void* ptr, uint32_t index, float value)
    {
        thisPtr->setParameterValue(index, value);
    }

#if DISTRHO_PLUGIN_WANT_STATE
    static void setStateCallback(void* ptr, const char* key, const char* value)
    {
        thisPtr->setState(key, value);
    }
#endif

#if DISTRHO_PLUGIN_HAS_UI
    static void setSizeCallback(void* ptr, uint width, uint height)
    {
        thisPtr->setSize(width, height);
    }
#endif

#if DISTRHO_PLUGIN_WANT_MIDI_OUTPUT
    static bool writeMidiCallback(void* ptr, const MidiEvent& midiEvent)
    {
        return thisPtr->writeMidi(midiEvent);
    }
#endif

    #undef thisPtr
};

END_NAMESPACE_DISTRHO

// -----------------------------------------------------------------------

int main()
{
    USE_NAMESPACE_DISTRHO;

    jack_status_t  status = jack_status_t(0x0);
    jack_client_t* client = jack_client_open(DISTRHO_PLUGIN_NAME, JackNoStartServer, &status);

    if (client == nullptr)
    {
        String errorString;

        if (status & JackFailure)
            errorString += "Overall operation failed;\n";
        if (status & JackInvalidOption)
            errorString += "The operation contained an invalid or unsupported option;\n";
        if (status & JackNameNotUnique)
            errorString += "The desired client name was not unique;\n";
        if (status & JackServerStarted)
            errorString += "The JACK server was started as a result of this operation;\n";
        if (status & JackServerFailed)
            errorString += "Unable to connect to the JACK server;\n";
        if (status & JackServerError)
            errorString += "Communication error with the JACK server;\n";
        if (status & JackNoSuchClient)
            errorString += "Requested client does not exist;\n";
        if (status & JackLoadFailure)
            errorString += "Unable to load internal client;\n";
        if (status & JackInitFailure)
            errorString += "Unable to initialize client;\n";
        if (status & JackShmFailure)
            errorString += "Unable to access shared memory;\n";
        if (status & JackVersionError)
            errorString += "Client's protocol version does not match;\n";
        if (status & JackBackendError)
            errorString += "Backend Error;\n";
        if (status & JackClientZombie)
            errorString += "Client is being shutdown against its will;\n";

        if (errorString.isNotEmpty())
        {
            errorString[errorString.length()-2] = '.';
            d_stderr("Failed to create jack client, reason was:\n%s", errorString.buffer());
        }
        else
            d_stderr("Failed to create jack client, cannot continue!");

        return 1;
    }

    USE_NAMESPACE_DISTRHO;

    initSignalHandler();

    d_lastBufferSize = jack_get_buffer_size(client);
    d_lastSampleRate = jack_get_sample_rate(client);
#if DISTRHO_PLUGIN_HAS_UI
    d_lastUiSampleRate = d_lastSampleRate;
#endif

    const PluginJack p(client);

    return 0;
}

// -----------------------------------------------------------------------