1 /* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
2
3 /*
4 Rosegarden
5 A sequencer and musical notation editor.
6 Copyright 2000-2021 the Rosegarden development team.
7 See the AUTHORS file for more details.
8
9 This program is free software; you can redistribute it and/or
10 modify it under the terms of the GNU General Public License as
11 published by the Free Software Foundation; either version 2 of the
12 License, or (at your option) any later version. See the file
13 COPYING included with this distribution for more information.
14 */
15
16 #define RG_MODULE_STRING "[JackDriver]"
17
18 #include "JackDriver.h"
19 #include "AlsaDriver.h"
20 #include "MappedStudio.h"
21 #include "AudioProcess.h"
22 #include "base/Profiler.h"
23 #include "base/AudioLevel.h"
24 #include "Audit.h"
25 #include "PluginFactory.h"
26 #include "SequencerDataBlock.h"
27
28 #include "misc/ConfigGroups.h"
29 #include "misc/Debug.h"
30
31 #include <QSettings>
32 #include <QtGlobal>
33
34 #ifdef HAVE_ALSA
35 #ifdef HAVE_LIBJACK
36
37 //#define DEBUG_JACK_DRIVER 1
38 //#define DEBUG_JACK_TRANSPORT 1
39 //#define DEBUG_JACK_PROCESS 1
Thumbwheel(Qt::Orientation orientation,bool useRed,QWidget * parent)40 //#define DEBUG_JACK_XRUN 1
41
42 namespace Rosegarden
43 {
44
45 #if (defined(DEBUG_JACK_DRIVER) || defined(DEBUG_JACK_PROCESS) || defined(DEBUG_JACK_TRANSPORT))
46 static unsigned long framesThisPlay = 0;
47 static RealTime startTime;
48 #endif
49
50 JackDriver::JackDriver(AlsaDriver *alsaDriver) :
51 m_client(nullptr),
52 m_bufferSize(0),
53 m_sampleRate(0),
54 m_tempOutBuffer(nullptr),
55 m_jackTransportEnabled(false),
56 m_jackTransportSource(false),
57 m_waiting(false),
58 m_waitingState(JackTransportStopped),
59 m_waitingToken(0),
60 m_ignoreProcessTransportCount(0),
61 m_bussMixer(nullptr),
62 m_instrumentMixer(nullptr),
63 m_fileReader(nullptr),
64 m_fileWriter(nullptr),
65 m_alsaDriver(alsaDriver),
66 m_masterLevel(1.0),
67 m_directMasterAudioInstruments(0L),
68 m_directMasterSynthInstruments(0L),
69 m_haveAsyncAudioEvent(false),
70 m_kickedOutAt(0),
71 m_framesProcessed(0),
72 m_ok(false)
73 {
74 Q_ASSERT(sizeof(sample_t) == sizeof(float));
75 initialise();
76 }
77
78 JackDriver::~JackDriver()
79 {
80 #ifdef DEBUG_JACK_DRIVER
81 RG_DEBUG << "dtor";
82 #endif
83
84 m_ok = false; // prevent any more work in process()
85
86 if (m_client) {
87 #ifdef DEBUG_JACK_DRIVER
88 RG_DEBUG << "dtor: deactivating JACK client";
89 #endif
90
91 if (jack_deactivate(m_client)) {
92 RG_WARNING << "dtor: WARNING: deactivation failed";
93 }
94 }
95
96 #ifdef DEBUG_JACK_DRIVER
97 RG_DEBUG << "dtor: terminating buss mixer";
98 #endif
99
100 AudioBussMixer *bussMixer = m_bussMixer;
101 m_bussMixer = nullptr;
102 if (bussMixer)
103 bussMixer->terminate();
104
105 #ifdef DEBUG_JACK_DRIVER
106 RG_DEBUG << "dtor: terminating instrument mixer";
107 #endif
108
109 AudioInstrumentMixer *instrumentMixer = m_instrumentMixer;
110 m_instrumentMixer = nullptr;
111 if (instrumentMixer) {
112 instrumentMixer->terminate();
113 instrumentMixer->destroyAllPlugins();
114 }
115
116 #ifdef DEBUG_JACK_DRIVER
117 RG_DEBUG << "dtor: terminating file reader";
118 #endif
119
120 AudioFileReader *reader = m_fileReader;
121 m_fileReader = nullptr;
122 if (reader)
123 reader->terminate();
124
125 #ifdef DEBUG_JACK_DRIVER
126 RG_DEBUG << "dtor: terminating file writer";
127 #endif
128
129 AudioFileWriter *writer = m_fileWriter;
130 m_fileWriter = nullptr;
131 if (writer)
132 writer->terminate();
133
134 if (m_client) {
135
136 #ifdef DEBUG_JACK_DRIVER
137 RG_DEBUG << "dtor: tearing down JACK client";
138 #endif
139
140 for (size_t i = 0; i < m_inputPorts.size(); ++i) {
141 #ifdef DEBUG_JACK_DRIVER
142 RG_DEBUG << "dtor: unregistering input " << i;
143 #endif
144
145 if (jack_port_unregister(m_client, m_inputPorts[i])) {
146 RG_WARNING << "dtor: WARNING: can't unregister input port " << i + 1;
147 }
148 }
149
150 for (size_t i = 0; i < m_outputSubmasters.size(); ++i) {
151 #ifdef DEBUG_JACK_DRIVER
152 RG_DEBUG << "dtor: unregistering output sub " << i;
153 #endif
154
155 if (jack_port_unregister(m_client, m_outputSubmasters[i])) {
156 RG_WARNING << "dtor: WARNING: can't unregister output submaster " << i + 1;
157 }
158 }
159
160 for (size_t i = 0; i < m_outputMonitors.size(); ++i) {
161 #ifdef DEBUG_JACK_DRIVER
162 RG_DEBUG << "dtor: unregistering output mon " << i;
163 #endif
164
165 if (jack_port_unregister(m_client, m_outputMonitors[i])) {
166 RG_WARNING << "dtor: WARNING: can't unregister output monitor " << i + 1;
167 }
168 }
169
170 for (size_t i = 0; i < m_outputMasters.size(); ++i) {
171 #ifdef DEBUG_JACK_DRIVER
172 RG_DEBUG << "dtor: unregistering output master " << i;
173 #endif
174
175 if (jack_port_unregister(m_client, m_outputMasters[i])) {
176 RG_WARNING << "dtor: WARNING: can't unregister output master " << i + 1;
177 }
178 }
179
180 #ifdef DEBUG_JACK_DRIVER
181 RG_DEBUG << "dtor: closing client";
182 #endif
183
184 jack_client_close(m_client);
185 RG_DEBUG << "dtor: done";
186 m_client = nullptr;
187 }
188
189 #ifdef DEBUG_JACK_DRIVER
190 RG_DEBUG << "dtor: deleting mixers etc";
191 #endif
192
193 delete bussMixer;
194 delete instrumentMixer;
195 delete reader;
196 delete writer;
197
198 #ifdef DEBUG_JACK_DRIVER
199 RG_DEBUG << "dtor: exiting";
200 #endif
201 }
202
203 void
204 JackDriver::initialise(bool reinitialise)
205 {
206 m_ok = false;
207
208 // Create a log that the user can easily see through the preferences
209 // even in a release build.
210 AUDIT << '\n';
211 AUDIT << "===============================================================\n";
212 AUDIT << "JackDriver::initialise() begin...\n";
213 RG_DEBUG << "initialise() begin...";
214
215 std::string jackClientName = "rosegarden";
216
217 // set up JackOpenOptions per user config
218 QSettings settings;
219 settings.beginGroup(SequencerOptionsConfigGroup);
220 bool autoStartJack = settings.value("autostartjack", true).toBool();
221 settings.endGroup();
222 // default is to auto start JACK; use JackNullOption
223 jack_options_t jackOptions = JackNullOption;
224 if (!autoStartJack) jackOptions = JackNoStartServer;
225
226 // attempt connection to JACK server
227 //
228 if ((m_client = jack_client_open(jackClientName.c_str(), jackOptions, nullptr)) == nullptr) {
229 RG_WARNING << "initialise() - JACK server not running";
230 RG_WARNING << " Attempt to start JACK server was " << (jackOptions & JackNoStartServer ? "NOT " : "") << "made per user config";
231 // Also send to user log.
232 AUDIT << "JACK server not running\n";
233 AUDIT << " Attempt to start JACK server was " << (jackOptions & JackNoStartServer ? "NOT " : "") << "made per user config\n";
234 return ;
235 }
236
237 InstrumentId instrumentBase;
238 int instrumentCount;
239 m_alsaDriver->getAudioInstrumentNumbers(instrumentBase, instrumentCount);
240 for (InstrumentId id = instrumentBase;
241 id < instrumentBase + instrumentCount; ++id) {
242 // prefill so that we can refer to the map without a lock (as
243 // the number of instruments won't change)
244 m_recordInputs[id] = RecordInputDesc(1000, -1, 0.0);
245 }
246
247 // set callbacks
248 //
249 jack_set_process_callback(m_client, jackProcessStatic, this);
250 jack_set_buffer_size_callback(m_client, jackBufferSize, this);
251 jack_set_sample_rate_callback(m_client, jackSampleRate, this);
252 jack_on_shutdown(m_client, jackShutdown, this);
253 jack_set_xrun_callback(m_client, jackXRun, this);
254 jack_set_sync_callback(m_client, jackSyncCallback, this);
255
256 // get and report the sample rate and buffer size
257 //
258 m_sampleRate = jack_get_sample_rate(m_client);
259 m_bufferSize = jack_get_buffer_size(m_client);
260
261 RG_DEBUG << "initialise() - JACK sample rate = " << m_sampleRate << "Hz, buffer size = " << m_bufferSize;
262 AUDIT << "JACK sample rate = " << m_sampleRate << "Hz, buffer size = " << m_bufferSize << '\n';
263
264 PluginFactory::setSampleRate(m_sampleRate);
265
266 // Get the initial buffer size before we activate the client
267 //
268
269 if (!reinitialise) {
270
271 // create processing buffer(s)
272 //
273 m_tempOutBuffer = new sample_t[m_bufferSize];
274
275 RG_DEBUG << "initialise() - creating disk thread...";
276 AUDIT << "Creating audio file thread...\n";
277
278 m_fileReader = new AudioFileReader(m_alsaDriver, m_sampleRate);
279 m_fileWriter = new AudioFileWriter(m_alsaDriver, m_sampleRate);
280 m_instrumentMixer = new AudioInstrumentMixer
281 (m_alsaDriver, m_fileReader, m_sampleRate, m_bufferSize);
282 m_bussMixer = new AudioBussMixer
283 (m_alsaDriver, m_instrumentMixer, m_sampleRate, m_bufferSize);
284 m_instrumentMixer->setBussMixer(m_bussMixer);
285
286 // We run the file reader whatever, but we only run the other
287 // threads (instrument mixer, buss mixer, file writer) when we
288 // actually need them. (See updateAudioData and createRecordFile.)
289 m_fileReader->run();
290 }
291
292 // Create and connect the default numbers of ports. We always create
293 // one stereo pair each of master and monitor outs, and then we create
294 // record ins, fader outs and submaster outs according to the user's
295 // preferences. Since we don't know the user's preferences yet, we'll
296 // start by creating one pair of record ins and no fader or submaster
297 // outs.
298 //
299 m_outputMasters.clear();
300 m_outputMonitors.clear();
301 m_outputSubmasters.clear();
302 m_outputInstruments.clear();
303 m_inputPorts.clear();
304
305 if (!createMainOutputs()) { // one stereo pair master, one pair monitor
306 RG_WARNING << "initialise() - failed to create main outputs!";
307 AUDIT << "WARNING: failed to create main outputs!\n";
308 return ;
309 }
310
311 if (!createRecordInputs(1)) {
312 RG_WARNING << "initialise() - failed to create record inputs!";
313 AUDIT << "WARNING: failed to create record inputs!\n";
314 return ;
315 }
316
317 if (jack_activate(m_client)) {
318 RG_WARNING << "initialise() - client activation failed";
319 AUDIT << "WARNING: client activation failed\n";
320 return ;
321 }
322
323 // Now set up the default connections, if configured to do so
324 settings.beginGroup(SequencerOptionsConfigGroup);
325 bool connectDefaultOutputs = settings.value("connect_default_jack_outputs", true).toBool();
326 bool connectDefaultInputs = settings.value("connect_default_jack_inputs", true).toBool();
327 settings.endGroup();
328
329 const char **ports = jack_get_ports(m_client, nullptr, nullptr,
330 JackPortIsPhysical | JackPortIsInput);
331
332 if (connectDefaultOutputs) {
333
334 std::string playback_1, playback_2;
335
336 if (ports) {
337 if (ports[0])
338 playback_1 = std::string(ports[0]);
339 if (ports[1])
340 playback_2 = std::string(ports[1]);
341
342 // count ports
343 unsigned int i = 0;
344 for (i = 0; ports[i]; i++)
345 ;
346 RG_DEBUG << "initialise() - found " << i << " JACK physical outputs";
347 AUDIT << "Found " << i << " JACK physical outputs\n";
348
349 jack_free(ports);
350
351 } else {
352 RG_WARNING << "initialise() - no JACK physical outputs found";
353 AUDIT << "WARNING: no JACK physical outputs found\n";
354 }
355
356 if (playback_1 != "") {
357 RG_DEBUG << "initialise() - connecting from " << "\"" << jack_port_name(m_outputMasters[0]) << "\" to \"" << playback_1.c_str() << "\"";
358 AUDIT << "connecting from " << "\"" << jack_port_name(m_outputMasters[0]) << "\" to \"" << playback_1.c_str() << "\"\n";
359
360 // connect our client up to the ALSA ports - first left output
361 //
362 if (jack_connect(m_client, jack_port_name(m_outputMasters[0]),
363 playback_1.c_str())) {
364 RG_WARNING << "initialise() - cannot connect to JACK output port";
365 AUDIT << "WARNING: cannot connect to JACK output port\n";
366 return ;
367 }
368
369 /*
370 // ??? monitors?
371 if (jack_connect(m_client, jack_port_name(m_outputMonitors[0]),
372 playback_1.c_str()))
373 {
374 RG_WARNING << "initialise() - cannot connect to JACK output port";
375 audit << "WARNING: cannot connect to JACK output port\n";
376 return;
377 }
378 */
379 }
380
381 if (playback_2 != "") {
382 RG_DEBUG << "initialise() - connecting from " << "\"" << jack_port_name(m_outputMasters[1]) << "\" to \"" << playback_2.c_str() << "\"";
383 AUDIT << "WARNING: connecting from " << "\"" << jack_port_name(m_outputMasters[1]) << "\" to \"" << playback_2.c_str() << "\"\n";
384
385 if (jack_connect(m_client, jack_port_name(m_outputMasters[1]),
386 playback_2.c_str())) {
387 RG_WARNING << "initialise() - cannot connect to JACK output port";
388 AUDIT << "WARNING: cannot connect to JACK output port\n";
389 }
390
391 /*
392 // ??? monitors?
393 if (jack_connect(m_client, jack_port_name(m_outputMonitors[1]),
394 playback_2.c_str()))
395 {
396 RG_WARNING << "initialise() - cannot connect to JACK output port";
397 audit << "WARNING: cannot connect to JACK output port\n";
398 }
399 */
400 }
401
402 }
403
404 if (connectDefaultInputs) {
405
406 std::string capture_1, capture_2;
407
408 ports =
409 jack_get_ports(m_client, nullptr, nullptr,
410 JackPortIsPhysical | JackPortIsOutput);
411
412 if (ports) {
413 if (ports[0])
414 capture_1 = std::string(ports[0]);
415 if (ports[1])
416 capture_2 = std::string(ports[1]);
417
418 // count ports
419 unsigned int i = 0;
420 for (i = 0; ports[i]; i++)
421 ;
422 RG_DEBUG << "initialise() - found " << i << " JACK physical inputs";
423 AUDIT << "found " << i << " JACK physical inputs\n";
424
425 jack_free(ports);
426
427 } else {
428 RG_WARNING << "initialise() - no JACK physical inputs found";
429 AUDIT << "WARNING: no JACK physical inputs found\n";
430 }
431
432 if (capture_1 != "") {
433
434 RG_DEBUG << "initialise() - connecting from " << "\"" << capture_1.c_str() << "\" to \"" << jack_port_name(m_inputPorts[0]) << "\"";
435 AUDIT << "connecting from " << "\"" << capture_1.c_str() << "\" to \"" << jack_port_name(m_inputPorts[0]) << "\"\n";
436
437 if (jack_connect(m_client, capture_1.c_str(),
438 jack_port_name(m_inputPorts[0]))) {
439 RG_WARNING << "initialise() - cannot connect to JACK input port";
440 AUDIT << "WARNING: cannot connect to JACK input port\n";
441 }
442 }
443
444 if (capture_2 != "") {
445
446 RG_DEBUG << "initialise() - connecting from " << "\"" << capture_2.c_str() << "\" to \"" << jack_port_name(m_inputPorts[1]) << "\"";
447 AUDIT << "connecting from " << "\"" << capture_2.c_str() << "\" to \"" << jack_port_name(m_inputPorts[1]) << "\"\n";
448
449 if (jack_connect(m_client, capture_2.c_str(),
450 jack_port_name(m_inputPorts[1]))) {
451 RG_WARNING << "initialise() - cannot connect to JACK input port";
452 AUDIT << "WARNING: cannot connect to JACK input port\n";
453 }
454 }
455 }
456
457 RG_DEBUG << "initialise() - initialised JACK audio subsystem";
458 AUDIT << "initialised JACK audio subsystem\n";
459
460 m_ok = true;
461 }
462
463 bool
464 JackDriver::createMainOutputs()
465 {
466 if (!m_client)
467 return false;
468
469 jack_port_t *port = jack_port_register
470 (m_client, "master out L",
471 JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0);
472 if (!port)
473 return false;
474 m_outputMasters.push_back(port);
475
476 port = jack_port_register
477 (m_client, "master out R",
478 JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0);
479 if (!port)
480 return false;
481 m_outputMasters.push_back(port);
482
483 port = jack_port_register
484 (m_client, "record monitor out L",
485 JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0);
486 if (!port)
487 return false;
488 m_outputMonitors.push_back(port);
489
490 port = jack_port_register
491 (m_client, "record monitor out R",
492 JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0);
493 if (!port)
494 return false;
495 m_outputMonitors.push_back(port);
496
497 return true;
498 }
499
500 bool
501 JackDriver::createFaderOutputs(int audioPairs, int synthPairs)
502 {
503 if (!m_client)
504 return false;
505
506 int pairs = audioPairs + synthPairs;
507 int pairsNow = int(m_outputInstruments.size()) / 2;
508 if (pairs == pairsNow)
509 return true;
510
511 for (int i = pairsNow; i < pairs; ++i) {
512
513 QString portName;
514
515 if (i < audioPairs) {
516 portName = QString("audio fader %1 out L").arg(i+1);
517 } else {
518 portName = QString("synth fader %1 out L").arg(i - audioPairs + 1);
519 }
520
521 jack_port_t *port;
522
523 port = jack_port_register(m_client,
524 portName.toLocal8Bit().constData(),
525 JACK_DEFAULT_AUDIO_TYPE,
526 JackPortIsOutput,
527 0);
528 if (!port)
529 return false;
530 m_outputInstruments.push_back(port);
531
532 if (i < audioPairs) {
533 portName = QString("audio fader %1 out R").arg(i+1);
534 } else {
535 portName = QString("synth fader %1 out R").arg(i - audioPairs + 1);
536 }
537
538 port = jack_port_register(m_client,
539 portName.toLocal8Bit().constData(),
540 JACK_DEFAULT_AUDIO_TYPE,
541 JackPortIsOutput,
542 0);
543 if (!port)
544 return false;
545 m_outputInstruments.push_back(port);
546 }
547
548 while ((int)m_outputInstruments.size() > pairs * 2) {
549 std::vector<jack_port_t *>::iterator itr = m_outputInstruments.end();
550 --itr;
551 jack_port_unregister(m_client, *itr);
552 m_outputInstruments.erase(itr);
553 }
554
555 return true;
556 }
557
558 bool
559 JackDriver::createSubmasterOutputs(int pairs)
560 {
561 if (!m_client)
562 return false;
563
564 int pairsNow = int(m_outputSubmasters.size()) / 2;
565 if (pairs == pairsNow)
566 return true;
567
568 for (int i = pairsNow; i < pairs; ++i) {
569
570 QString name;
571 jack_port_t *port;
572
573 name = QString("submaster %d out L").arg(i + 1);
574 port = jack_port_register(m_client,
575 name.toLocal8Bit(),
576 JACK_DEFAULT_AUDIO_TYPE,
577 JackPortIsOutput,
578 0);
579 if (!port)
580 return false;
581 m_outputSubmasters.push_back(port);
582
583 name = QString("submaster %d out R").arg(i + 1);
584 port = jack_port_register(m_client,
585 name.toLocal8Bit(),
586 JACK_DEFAULT_AUDIO_TYPE,
587 JackPortIsOutput,
588 0);
589 if (!port)
590 return false;
591 m_outputSubmasters.push_back(port);
592 }
593
594 while ((int)m_outputSubmasters.size() > pairs * 2) {
595 std::vector<jack_port_t *>::iterator itr = m_outputSubmasters.end();
596 --itr;
597 jack_port_unregister(m_client, *itr);
598 m_outputSubmasters.erase(itr);
599 }
600
601 return true;
602 }
603
604 bool
605 JackDriver::createRecordInputs(int pairs)
606 {
607 if (!m_client)
608 return false;
609
610 int pairsNow = int(m_inputPorts.size()) / 2;
611 if (pairs == pairsNow)
612 return true;
613
614 for (int i = pairsNow; i < pairs; ++i) {
615
616 QString name;
617 jack_port_t *port;
618
619 name = QString("record in %1 L").arg(i + 1);
620 port = jack_port_register(m_client,
621 name.toLocal8Bit(),
622 JACK_DEFAULT_AUDIO_TYPE,
623 JackPortIsInput,
624 0);
625 if (!port)
626 return false;
627 m_inputPorts.push_back(port);
628
629 name = QString("record in %1 R").arg(i + 1);
630 port = jack_port_register(m_client,
631 name.toLocal8Bit(),
632 JACK_DEFAULT_AUDIO_TYPE,
633 JackPortIsInput,
634 0);
635 if (!port)
636 return false;
637 m_inputPorts.push_back(port);
638 }
639
640 while ((int)m_outputSubmasters.size() > pairs * 2) {
641 std::vector<jack_port_t *>::iterator itr = m_outputSubmasters.end();
642 --itr;
643 jack_port_unregister(m_client, *itr);
644 m_outputSubmasters.erase(itr);
645 }
646
647 return true;
648 }
649
650
651 void
652 JackDriver::setAudioPorts(bool faderOuts, bool submasterOuts)
653 {
654 if (!m_client)
655 return ;
656
657 // Create a log that the user can easily see through the preferences
658 // even in a release build.
659 AUDIT << '\n';
660 AUDIT << "===============================================================\n";
661 AUDIT << "JackDriver::setAudioPorts() begin...\n";
662
663 #ifdef DEBUG_JACK_DRIVER
664 RG_DEBUG << "setAudioPorts(" << faderOuts << "," << submasterOuts << ")";
665 #endif
666
667 if (!m_client) {
668 RG_WARNING << "setAudioPorts(" << faderOuts << "," << submasterOuts << "): no client yet";
669 AUDIT << "WARNING: setAudioPorts(" << faderOuts << "," << submasterOuts << "): no client yet\n";
670 return ;
671 }
672
673 if (faderOuts) {
674 InstrumentId instrumentBase;
675 int audioInstruments;
676 int synthInstruments;
677 m_alsaDriver->getAudioInstrumentNumbers(instrumentBase, audioInstruments);
678 m_alsaDriver->getSoftSynthInstrumentNumbers(instrumentBase, synthInstruments);
679 if (!createFaderOutputs(audioInstruments, synthInstruments)) {
680 m_ok = false;
681 RG_WARNING << "setAudioPorts(): Failed to create fader outs!";
682 AUDIT << "WARNING: Failed to create fader outs!\n";
683 return ;
684 }
685 } else {
686 createFaderOutputs(0, 0);
687 }
688
689 if (submasterOuts) {
690
691 // one fewer than returned here, because the master has a buss object too
692 int count = m_alsaDriver->getMappedStudio()->getObjectCount(
693 MappedObject::AudioBuss);
694 if (count == 0) {
695 RG_WARNING << "setAudioPorts(): Mapped studio contains no master buss! Probably a symptom of a serious error";
696 AUDIT << "WARNING: Mapped studio contains no master buss! Probably a symptom of a serious error\n";
697 } else {
698 count = count - 1;
699 }
700 if (!createSubmasterOutputs(count)) {
701 m_ok = false;
702 RG_WARNING << "setAudioPorts(): Failed to create submaster outs!";
703 AUDIT << "WARNING(): Failed to create submaster outs!\n";
704 return ;
705 }
706
707 } else {
708 createSubmasterOutputs(0);
709 }
710 }
711
712 RealTime
713 JackDriver::getAudioPlayLatency() const
714 {
715 if (!m_client)
716 return RealTime::zeroTime;
717
718 #if 0
719 // ??? DEPRECATED
720 // jack_port_get_total_latency() is deprecated. Replace with
721 // jack_port_get_latency_range().
722
723 jack_nframes_t latency =
724 jack_port_get_total_latency(m_client, m_outputMasters[0]);
725
726 return RealTime::frame2RealTime(latency, m_sampleRate);
727 #else
728 jack_latency_range_t latencyRange;
729 jack_port_get_latency_range(
730 m_outputMasters[0], JackPlaybackLatency, &latencyRange);
731
732 // min and max appear to be the same, so we'll just go with max.
733 // ??? Might be better to average them?
734 return RealTime::frame2RealTime(latencyRange.max, m_sampleRate);
735 #endif
736 }
737
738 RealTime
739 JackDriver::getAudioRecordLatency() const
740 {
741 if (!m_client)
742 return RealTime::zeroTime;
743
744 #if 0
745 // ??? DEPRECATED
746 // jack_port_get_total_latency() is deprecated. Replace with
747 // jack_port_get_latency_range().
748
749 jack_nframes_t latency =
750 jack_port_get_total_latency(m_client, m_inputPorts[0]);
751
752 return RealTime::frame2RealTime(latency, m_sampleRate);
753 #else
754 jack_latency_range_t latencyRange;
755 jack_port_get_latency_range(
756 m_inputPorts[0], JackCaptureLatency, &latencyRange);
757
758 // min and max appear to be the same, so we'll just go with max.
759 // ??? Might be better to average them?
760 return RealTime::frame2RealTime(latencyRange.max, m_sampleRate);
761 #endif
762 }
763
764 RealTime
765 JackDriver::getInstrumentPlayLatency(InstrumentId id) const
766 {
767 if (m_instrumentLatencies.find(id) == m_instrumentLatencies.end()) {
768 return RealTime::zeroTime;
769 } else {
770 return m_instrumentLatencies.find(id)->second;
771 }
772 }
773
774 RealTime
775 JackDriver::getMaximumPlayLatency() const
776 {
777 return m_maxInstrumentLatency;
778 }
779
780 int
781 JackDriver::jackProcessStatic(jack_nframes_t nframes, void *arg)
782 {
783 JackDriver *inst = static_cast<JackDriver*>(arg);
784 if (inst)
785 return inst->jackProcess(nframes);
786 else
787 return 0;
788 }
789
790 int
791 JackDriver::jackProcess(jack_nframes_t nframes)
792 {
793 if (!m_ok || !m_client) {
794 #ifdef DEBUG_JACK_PROCESS
795 RG_DEBUG << "jackProcess(): not OK";
796 #endif
797
798 return 0;
799 }
800
801 if (!m_bussMixer) {
802 #ifdef DEBUG_JACK_PROCESS
803 RG_DEBUG << "jackProcess(): no buss mixer";
804 #endif
805
806 return jackProcessEmpty(nframes);
807 }
808
809 // synchronize MIDI and audio by adjusting MIDI playback rate
810 if (m_alsaDriver->areClocksRunning()) {
811 m_alsaDriver->checkTimerSync(m_framesProcessed);
812 } else {
813 m_alsaDriver->checkTimerSync(0);
814 }
815
816 bool lowLatencyMode = m_alsaDriver->getLowLatencyMode();
817 bool clocksRunning = m_alsaDriver->areClocksRunning();
818 bool playing = m_alsaDriver->isPlaying();
819 bool asyncAudio = m_haveAsyncAudioEvent;
820
821 #ifdef DEBUG_JACK_PROCESS
822 Profiler profiler("jackProcess", true);
823 #else
824 #ifdef DEBUG_JACK_XRUN
825 Profiler profiler("jackProcess", false);
826 #endif
827 #endif
828
829 if (lowLatencyMode) {
830 if (clocksRunning) {
831 if (playing || asyncAudio) {
832 if (m_instrumentMixer->tryLock() == 0) {
833 m_instrumentMixer->kick(false);
834 m_instrumentMixer->releaseLock();
835 //#ifdef DEBUG_JACK_PROCESS
836 } else {
837 RG_WARNING << "jackProcess(): WARNING: no instrument mixer lock available";
838 //#endif
839 }
840 if (m_bussMixer->getBussCount() > 0) {
841 if (m_bussMixer->tryLock() == 0) {
842 m_bussMixer->kick(false, false);
843 m_bussMixer->releaseLock();
844 //#ifdef DEBUG_JACK_PROCESS
845 } else {
846 RG_WARNING << "jackProcess(): WARNING: no buss mixer lock available";
847 //#endif
848 }
849 }
850 }
851 }
852 }
853
854 if (jack_cpu_load(m_client) > 97.0) {
855 reportFailure(MappedEvent::FailureCPUOverload);
856 return jackProcessEmpty(nframes);
857 }
858
859 #ifdef DEBUG_JACK_PROCESS
860 Profiler profiler2("jackProcess post mix", true);
861 #else
862 #ifdef DEBUG_JACK_XRUN
863 Profiler profiler2("jackProcess post mix", false);
864 #endif
865 #endif
866
867 jack_position_t position;
868 jack_transport_state_t state = JackTransportRolling;
869 bool doneRecord = false;
870
871 int ignoreCount = m_ignoreProcessTransportCount;
872 if (ignoreCount > 0)
873 --m_ignoreProcessTransportCount;
874
875 InstrumentId audioInstrumentBase;
876 int audioInstruments;
877 m_alsaDriver->getAudioInstrumentNumbers(audioInstrumentBase, audioInstruments);
878
879 if (m_jackTransportEnabled) {
880 state = jack_transport_query(m_client, &position);
881
882 #ifdef DEBUG_JACK_PROCESS
883 RG_DEBUG << "jackProcess(): JACK transport state is " << state;
884 #endif
885
886 if (state == JackTransportStopped) {
887 if (playing && clocksRunning && !m_waiting) {
888 RosegardenSequencer *sequencer =
889 RosegardenSequencer::getInstance();
890 if (sequencer) {
891 #ifdef DEBUG_JACK_TRANSPORT
892 RG_DEBUG << "jackProcess(): JACK transport stopped externally at " << position.frame;
893 #endif
894
895 m_waitingToken = sequencer->transportJump(
896 RosegardenSequencer::TransportStopAtTime,
897 RealTime::frame2RealTime(position.frame,
898 position.frame_rate));
899 }
900 } else if (clocksRunning) {
901 if (!asyncAudio) {
902 #ifdef DEBUG_JACK_PROCESS
903 RG_DEBUG << "jackProcess(): no interesting async events";
904 #endif
905 // do this before record monitor, otherwise we lose monitor out
906 jackProcessEmpty(nframes);
907 }
908
909 // for monitoring:
910 int rv = 0;
911 for (InstrumentId id = audioInstrumentBase;
912 id < audioInstrumentBase + audioInstruments; ++id) {
913 int irv = jackProcessRecord(id, nframes, nullptr, nullptr, clocksRunning);
914 if (irv != 0)
915 rv = irv;
916 }
917 doneRecord = true;
918
919 if (!asyncAudio) {
920 return rv;
921 }
922
923 } else {
924 return jackProcessEmpty(nframes);
925 }
926 } else if (state == JackTransportStarting) {
927 return jackProcessEmpty(nframes);
928 } else if (state != JackTransportRolling) {
929 RG_WARNING << "jackProcess(): WARNING: unexpected JACK transport state " << state;
930 }
931 }
932
933 if (state == JackTransportRolling) { // also covers not-on-transport case
934 if (m_waiting) {
935 if (ignoreCount > 0) {
936 #ifdef DEBUG_JACK_TRANSPORT
937 RG_DEBUG << "jackProcess(): transport rolling, but we're ignoring it (count = " << ignoreCount << ")";
938 #endif
939 } else {
940 #ifdef DEBUG_JACK_TRANSPORT
941 RG_DEBUG << "jackProcess(): transport rolling, telling ALSA driver to go!";
942 #endif
943
944 m_alsaDriver->startClocksApproved();
945 m_waiting = false;
946 }
947 }
948
949 #ifdef DEBUG_JACK_PROCESS
950 RG_DEBUG << "jackProcess(): (rolling or not on JACK transport)";
951 #endif
952
953 if (!clocksRunning) {
954 #ifdef DEBUG_JACK_PROCESS
955 RG_DEBUG << "jackProcess(): clocks stopped";
956 #endif
957
958 return jackProcessEmpty(nframes);
959
960 } else if (!playing) {
961 #ifdef DEBUG_JACK_PROCESS
962 RG_DEBUG << "jackProcess(): not playing";
963 #endif
964
965 if (!asyncAudio) {
966 #ifdef DEBUG_JACK_PROCESS
967 RG_DEBUG << "jackProcess(): no interesting async events";
968 #endif
969 // do this before record monitor, otherwise we lose monitor out
970 jackProcessEmpty(nframes);
971 }
972
973 // for monitoring:
974 int rv = 0;
975 for (InstrumentId id = audioInstrumentBase;
976 id < audioInstrumentBase + audioInstruments; ++id) {
977 int irv = jackProcessRecord(id, nframes, nullptr, nullptr, clocksRunning);
978 if (irv != 0)
979 rv = irv;
980 }
981 doneRecord = true;
982
983 if (!asyncAudio) {
984 return rv;
985 }
986 }
987 }
988
989 #ifdef DEBUG_JACK_PROCESS
990 Profiler profiler3("jackProcess post transport", true);
991 #else
992 #ifdef DEBUG_JACK_XRUN
993 Profiler profiler3("jackProcess post transport", false);
994 #endif
995 #endif
996
997 InstrumentId synthInstrumentBase;
998 int synthInstruments;
999 m_alsaDriver->getSoftSynthInstrumentNumbers(synthInstrumentBase, synthInstruments);
1000
1001 // We always have the master out
1002
1003 sample_t *master[2] = {
1004 static_cast<sample_t *>(jack_port_get_buffer(m_outputMasters[0], nframes)),
1005 static_cast<sample_t *>(jack_port_get_buffer(m_outputMasters[1], nframes))
1006 };
1007
1008 memset(master[0], 0, nframes * sizeof(sample_t));
1009 memset(master[1], 0, nframes * sizeof(sample_t));
1010
1011 // Reset monitor outs (if present) here prior to mixing
1012
1013 if (!m_outputMonitors.empty()) {
1014 sample_t *buffer =
1015 static_cast<sample_t *>(jack_port_get_buffer(m_outputMonitors[0], nframes));
1016 if (buffer)
1017 memset(buffer, 0, nframes * sizeof(sample_t));
1018 }
1019
1020 if (m_outputMonitors.size() > 1) {
1021 sample_t *buffer =
1022 static_cast<sample_t *>(jack_port_get_buffer(m_outputMonitors[1], nframes));
1023 if (buffer)
1024 memset(buffer, 0, nframes * sizeof(sample_t));
1025 }
1026
1027 int bussCount = m_bussMixer->getBussCount();
1028
1029 // If we have any busses, then we just mix from them (but we still
1030 // need to keep ourselves up to date by reading and monitoring the
1031 // instruments). If we have no busses, mix direct from instruments.
1032
1033 for (int buss = 0; buss < bussCount; ++buss) {
1034
1035 sample_t *submaster[2] = { nullptr, nullptr };
1036 sample_t peak[2] = { 0.0, 0.0 };
1037
1038 if ((int)m_outputSubmasters.size() > buss * 2 + 1) {
1039 submaster[0] =
1040 static_cast<sample_t *>(jack_port_get_buffer(m_outputSubmasters[buss * 2], nframes));
1041 submaster[1] =
1042 static_cast<sample_t *>(jack_port_get_buffer(m_outputSubmasters[buss * 2 + 1], nframes));
1043 }
1044
1045 if (!submaster[0])
1046 submaster[0] = m_tempOutBuffer;
1047 if (!submaster[1])
1048 submaster[1] = m_tempOutBuffer;
1049
1050 for (int ch = 0; ch < 2; ++ch) {
1051
1052 RingBuffer<AudioBussMixer::sample_t> *rb =
1053 m_bussMixer->getRingBuffer(buss, ch);
1054
1055 if (!rb || m_bussMixer->isBussDormant(buss)) {
1056 if (rb)
1057 rb->skip(nframes);
1058 if (submaster[ch])
1059 memset(submaster[ch], 0, nframes * sizeof(sample_t));
1060 } else {
1061 size_t actual = rb->read(submaster[ch], nframes);
1062 if (actual < nframes) {
1063 reportFailure(MappedEvent::FailureBussMixUnderrun);
1064 }
1065 for (size_t i = 0; i < nframes; ++i) {
1066 sample_t sample = submaster[ch][i];
1067 if (sample > peak[ch])
1068 peak[ch] = sample;
1069 master[ch][i] += sample;
1070 }
1071 }
1072 }
1073
1074 LevelInfo info;
1075 info.level = AudioLevel::multiplier_to_fader(
1076 peak[0], 127, AudioLevel::LongFader);
1077 info.levelRight = AudioLevel::multiplier_to_fader(
1078 peak[1], 127, AudioLevel::LongFader);
1079
1080 SequencerDataBlock::getInstance()->setSubmasterLevel(buss, info);
1081
1082 for (InstrumentId id = audioInstrumentBase;
1083 id < audioInstrumentBase + audioInstruments; ++id) {
1084 if (buss + 1 == m_recordInputs[id].input) {
1085 jackProcessRecord(id, nframes, submaster[0], submaster[1], clocksRunning);
1086 }
1087 }
1088 }
1089
1090 #ifdef DEBUG_JACK_PROCESS
1091 RG_DEBUG << "jackProcess(): have " << audioInstruments << " audio and " << synthInstruments << " synth instruments and " << bussCount << " busses";
1092 #endif
1093
1094 bool allInstrumentsDormant = true;
1095 static RealTime dormantTime = RealTime::zeroTime;
1096
1097 for (int i = 0; i < audioInstruments + synthInstruments; ++i) {
1098
1099 InstrumentId id;
1100 if (i < audioInstruments)
1101 id = audioInstrumentBase + i;
1102 else
1103 id = synthInstrumentBase + (i - audioInstruments);
1104
1105 if (m_instrumentMixer->isInstrumentEmpty(id))
1106 continue;
1107
1108 sample_t *instrument[2] = { nullptr, nullptr };
1109 sample_t peak[2] = { 0.0, 0.0 };
1110
1111 if (int(m_outputInstruments.size()) > i * 2 + 1) {
1112 instrument[0] =
1113 static_cast<sample_t *>(jack_port_get_buffer(m_outputInstruments[i * 2], nframes));
1114 instrument[1] =
1115 static_cast<sample_t *>(jack_port_get_buffer(m_outputInstruments[i * 2 + 1], nframes));
1116 }
1117
1118 if (!instrument[0])
1119 instrument[0] = m_tempOutBuffer;
1120 if (!instrument[1])
1121 instrument[1] = m_tempOutBuffer;
1122
1123 for (int ch = 0; ch < 2; ++ch) {
1124
1125 // We always need to read from an instrument's ring buffer
1126 // to keep the instrument moving along, as well as for
1127 // monitoring. If the instrument is connected straight to
1128 // the master, then we also need to mix from it. (We have
1129 // that information cached courtesy of updateAudioData.)
1130
1131 bool directToMaster = false;
1132 if (i < audioInstruments) {
1133 directToMaster = (m_directMasterAudioInstruments & (1 << i));
1134 } else {
1135 directToMaster = (m_directMasterSynthInstruments &
1136 (1 << (i - audioInstruments)));
1137 }
1138
1139 #ifdef DEBUG_JACK_PROCESS
1140 if (id == 1000 || id == 10000) {
1141 RG_DEBUG << "jackProcess(): instrument id " << id << ", base " << audioInstrumentBase << ", direct masters " << m_directMasterAudioInstruments << ": " << directToMaster;
1142 }
1143 #endif
1144
1145 RingBuffer<AudioInstrumentMixer::sample_t, 2> *rb =
1146 m_instrumentMixer->getRingBuffer(id, ch);
1147
1148 if (!rb || m_instrumentMixer->isInstrumentDormant(id)) {
1149 #ifdef DEBUG_JACK_PROCESS
1150 if (id == 1000 || id == 10000) {
1151 if (rb) {
1152 RG_DEBUG << "jackProcess(): instrument " << id << " dormant";
1153 } else {
1154 RG_DEBUG << "jackProcess(): instrument " << id << " has no ring buffer for channel " << ch;
1155 }
1156 }
1157 #endif
1158 if (rb)
1159 rb->skip(nframes);
1160 if (instrument[ch])
1161 memset(instrument[ch], 0, nframes * sizeof(sample_t));
1162
1163 } else {
1164
1165 allInstrumentsDormant = false;
1166
1167 size_t actual = rb->read(instrument[ch], nframes);
1168
1169 #ifdef DEBUG_JACK_PROCESS
1170
1171 if (id == 1000) {
1172 RG_DEBUG << "jackProcess(): read " << actual << " of " << nframes << " frames for instrument " << id << " channel " << ch;
1173 }
1174 #endif
1175
1176 if (actual < nframes) {
1177 RG_WARNING << "jackProcess(): WARNING: read " << actual << " of " << nframes << " frames for " << id << " ch " << ch << " (pl " << playing << ", cl " << clocksRunning << ", aa " << asyncAudio << ")";
1178 reportFailure(MappedEvent::FailureMixUnderrun);
1179 }
1180
1181 for (size_t f = 0; f < nframes; ++f) {
1182 sample_t sample = instrument[ch][f];
1183 if (sample > peak[ch])
1184 peak[ch] = sample;
1185 if (directToMaster)
1186 master[ch][f] += sample;
1187 }
1188 }
1189
1190 // If the instrument is connected straight to master we
1191 // also need to skip() on the buss mixer's reader for it,
1192 // otherwise it'll block because the buss mixer isn't
1193 // needing to read it.
1194
1195 if (rb && directToMaster) {
1196 rb->skip(nframes, 1); // 1 is the buss mixer's reader (magic)
1197 }
1198 }
1199
1200 LevelInfo info;
1201 info.level = AudioLevel::multiplier_to_fader(
1202 peak[0], 127, AudioLevel::LongFader);
1203 info.levelRight = AudioLevel::multiplier_to_fader(
1204 peak[1], 127, AudioLevel::LongFader);
1205
1206 SequencerDataBlock::getInstance()->setInstrumentLevel(id, info);
1207 }
1208
1209 if (asyncAudio) {
1210 if (!allInstrumentsDormant) {
1211 dormantTime = RealTime::zeroTime;
1212 } else {
1213 dormantTime = dormantTime +
1214 RealTime::frame2RealTime(m_bufferSize, m_sampleRate);
1215 if (dormantTime > RealTime(10, 0)) {
1216 RG_WARNING << "jackProcess(): WARNING: dormantTime = " << dormantTime << ", resetting m_haveAsyncAudioEvent";
1217 m_haveAsyncAudioEvent = false;
1218 }
1219 }
1220 }
1221
1222 // Get master fader levels. There's no pan on the master.
1223 float gain = AudioLevel::dB_to_multiplier(m_masterLevel);
1224 float masterPeak[2] = { 0.0, 0.0 };
1225
1226 for (int ch = 0; ch < 2; ++ch) {
1227 for (size_t i = 0; i < nframes; ++i) {
1228 sample_t sample = master[ch][i] * gain;
1229 if (sample > masterPeak[ch])
1230 masterPeak[ch] = sample;
1231 master[ch][i] = sample;
1232 }
1233 }
1234
1235 LevelInfo info;
1236 info.level = AudioLevel::multiplier_to_fader(
1237 masterPeak[0], 127, AudioLevel::LongFader);
1238 info.levelRight = AudioLevel::multiplier_to_fader(
1239 masterPeak[1], 127, AudioLevel::LongFader);
1240
1241 SequencerDataBlock::getInstance()->setMasterLevel(info);
1242
1243 for (InstrumentId id = audioInstrumentBase;
1244 id < audioInstrumentBase + audioInstruments; ++id) {
1245 if (m_recordInputs[id].input == 0) {
1246 jackProcessRecord(id, nframes, master[0], master[1], clocksRunning);
1247 } else if (m_recordInputs[id].input < 1000) { // buss, already done
1248 // nothing
1249 } else if (!doneRecord) {
1250 jackProcessRecord(id, nframes, nullptr, nullptr, clocksRunning);
1251 }
1252 }
1253
1254 if (playing) {
1255 if (!lowLatencyMode) {
1256 if (m_bussMixer->getBussCount() == 0) {
1257 m_instrumentMixer->signal();
1258 } else {
1259 m_bussMixer->signal();
1260 }
1261 }
1262 }
1263
1264 m_framesProcessed += nframes;
1265
1266 #if (defined(DEBUG_JACK_DRIVER) || defined(DEBUG_JACK_PROCESS) || defined(DEBUG_JACK_TRANSPORT))
1267 framesThisPlay += nframes; //!!!
1268 #endif
1269
1270 #ifdef DEBUG_JACK_PROCESS
1271 RG_DEBUG << "jackProcess(): " << nframes << " frames, " << framesThisPlay << " this play, " << m_framesProcessed << " total";
1272 #endif
1273
1274 return 0;
1275 }
1276
1277 int
1278 JackDriver::jackProcessEmpty(jack_nframes_t nframes)
1279 {
1280 sample_t *buffer;
1281
1282 #ifdef DEBUG_JACK_PROCESS
1283 RG_DEBUG << "jackProcessEmpty() begin";
1284 #endif
1285
1286 buffer = static_cast<sample_t *>
1287 (jack_port_get_buffer(m_outputMasters[0], nframes));
1288 if (buffer)
1289 memset(buffer, 0, nframes * sizeof(sample_t));
1290
1291 buffer = static_cast<sample_t *>
1292 (jack_port_get_buffer(m_outputMasters[1], nframes));
1293 if (buffer)
1294 memset(buffer, 0, nframes * sizeof(sample_t));
1295
1296 buffer = static_cast<sample_t *>
1297 (jack_port_get_buffer(m_outputMonitors[0], nframes));
1298 if (buffer)
1299 memset(buffer, 0, nframes * sizeof(sample_t));
1300
1301 buffer = static_cast<sample_t *>
1302 (jack_port_get_buffer(m_outputMonitors[1], nframes));
1303 if (buffer)
1304 memset(buffer, 0, nframes * sizeof(sample_t));
1305
1306 for (size_t i = 0; i < m_outputSubmasters.size(); ++i) {
1307 buffer = static_cast<sample_t *>
1308 (jack_port_get_buffer(m_outputSubmasters[i], nframes));
1309 if (buffer)
1310 memset(buffer, 0, nframes * sizeof(sample_t));
1311 }
1312
1313 for (size_t i = 0; i < m_outputInstruments.size(); ++i) {
1314 buffer = static_cast<sample_t *>
1315 (jack_port_get_buffer(m_outputInstruments[i], nframes));
1316 if (buffer)
1317 memset(buffer, 0, nframes * sizeof(sample_t));
1318 }
1319
1320 m_framesProcessed += nframes;
1321
1322 #if (defined(DEBUG_JACK_DRIVER) || defined(DEBUG_JACK_PROCESS) || defined(DEBUG_JACK_TRANSPORT))
1323
1324 framesThisPlay += nframes;
1325 #endif
1326 #ifdef DEBUG_JACK_PROCESS
1327 RG_DEBUG << "jackProcess(): " << nframes << " frames, " << framesThisPlay << " this play, " << m_framesProcessed << " total";
1328 #endif
1329
1330 return 0;
1331 }
1332
1333 int
1334 JackDriver::jackProcessRecord(InstrumentId id,
1335 jack_nframes_t nframes,
1336 sample_t *sourceBufferLeft,
1337 sample_t *sourceBufferRight,
1338 bool clocksRunning)
1339 {
1340 #ifdef DEBUG_JACK_PROCESS
1341 Profiler profiler("jackProcessRecord", true);
1342 #else
1343 #ifdef DEBUG_JACK_XRUN
1344
1345 Profiler profiler("jackProcessRecord", false);
1346 #endif
1347 #endif
1348
1349 bool wroteSomething = false;
1350 sample_t peakLeft = 0.0, peakRight = 0.0;
1351
1352 #ifdef DEBUG_JACK_PROCESS
1353 RG_DEBUG << "jackProcessRecord(" << id << "): clocksRunning " << clocksRunning;
1354 #endif
1355
1356 // Get input buffers
1357 //
1358 sample_t *inputBufferLeft = nullptr, *inputBufferRight = nullptr;
1359
1360 int recInput = m_recordInputs[id].input;
1361
1362 int channel = m_recordInputs[id].channel;
1363 int channels = (channel == -1 ? 2 : 1);
1364 if (channels == 2)
1365 channel = 0;
1366
1367 float level = m_recordInputs[id].level;
1368
1369 if (sourceBufferLeft) {
1370
1371 #ifdef DEBUG_JACK_PROCESS
1372 RG_DEBUG << "jackProcessRecord(" << id << "): buss input provided";
1373 #endif
1374
1375 inputBufferLeft = sourceBufferLeft;
1376 if (sourceBufferRight)
1377 inputBufferRight = sourceBufferRight;
1378
1379 } else if (recInput < 1000) {
1380
1381 #ifdef DEBUG_JACK_PROCESS
1382 RG_DEBUG << "jackProcessRecord(" << id << "): no known input";
1383 #endif
1384
1385 return 0;
1386
1387 } else {
1388
1389 #ifdef DEBUG_JACK_PROCESS
1390 RG_DEBUG << "jackProcessRecord(" << id << "): record input " << recInput;
1391 #endif
1392
1393 int input = recInput - 1000;
1394
1395 int port = input * channels + channel;
1396 int portRight = input * channels + 1;
1397
1398 if (port < int(m_inputPorts.size())) {
1399 inputBufferLeft = static_cast<sample_t*>
1400 (jack_port_get_buffer(m_inputPorts[port], nframes));
1401 }
1402
1403 if (channels == 2 && portRight < int(m_inputPorts.size())) {
1404 inputBufferRight = static_cast<sample_t*>
1405 (jack_port_get_buffer(m_inputPorts[portRight], nframes));
1406 }
1407 }
1408
1409 float gain = AudioLevel::dB_to_multiplier(level);
1410
1411 if (m_alsaDriver->getRecordStatus() == RECORD_ON &&
1412 clocksRunning &&
1413 m_fileWriter->haveRecordFileOpen(id)) {
1414
1415 #ifdef DEBUG_JACK_PROCESS
1416 RG_DEBUG << "jackProcessRecord(" << id << "): recording";
1417 #endif
1418
1419 memset(m_tempOutBuffer, 0, nframes * sizeof(sample_t));
1420
1421 if (inputBufferLeft) {
1422 for (size_t i = 0; i < nframes; ++i) {
1423 sample_t sample = inputBufferLeft[i] * gain;
1424 if (sample > peakLeft)
1425 peakLeft = sample;
1426 m_tempOutBuffer[i] = sample;
1427 }
1428
1429 if (!m_outputMonitors.empty()) {
1430 sample_t *buf =
1431 static_cast<sample_t *>
1432 (jack_port_get_buffer(m_outputMonitors[0], nframes));
1433 if (buf) {
1434 for (size_t i = 0; i < nframes; ++i) {
1435 buf[i] += m_tempOutBuffer[i];
1436 }
1437 }
1438 }
1439
1440 m_fileWriter->write(id, m_tempOutBuffer, 0, nframes);
1441 }
1442
1443 if (channels == 2) {
1444
1445 if (inputBufferRight) {
1446 for (size_t i = 0; i < nframes; ++i) {
1447 sample_t sample = inputBufferRight[i] * gain;
1448 if (sample > peakRight)
1449 peakRight = sample;
1450 m_tempOutBuffer[i] = sample;
1451 }
1452 if (m_outputMonitors.size() > 1) {
1453 sample_t *buf =
1454 static_cast<sample_t *>
1455 (jack_port_get_buffer(m_outputMonitors[1], nframes));
1456 if (buf) {
1457 for (size_t i = 0; i < nframes; ++i) {
1458 buf[i] += m_tempOutBuffer[i];
1459 }
1460 }
1461 }
1462 }
1463
1464 m_fileWriter->write(id, m_tempOutBuffer, 1, nframes);
1465 }
1466
1467 wroteSomething = true;
1468
1469 } else {
1470
1471 // want peak levels and monitors anyway, even if not recording
1472
1473 #ifdef DEBUG_JACK_PROCESS
1474 RG_DEBUG << "jackProcessRecord(" << id << "): monitoring only";
1475 #endif
1476
1477 if (inputBufferLeft) {
1478
1479 sample_t *buf = nullptr;
1480 if (!m_outputMonitors.empty()) {
1481 buf = static_cast<sample_t *>
1482 (jack_port_get_buffer(m_outputMonitors[0], nframes));
1483 }
1484
1485 for (size_t i = 0; i < nframes; ++i) {
1486 sample_t sample = inputBufferLeft[i] * gain;
1487 if (sample > peakLeft)
1488 peakLeft = sample;
1489 if (buf)
1490 buf[i] = sample;
1491 }
1492
1493 if (channels == 2 && inputBufferRight) {
1494
1495 buf = nullptr;
1496 if (m_outputMonitors.size() > 1) {
1497 buf = static_cast<sample_t *>
1498 (jack_port_get_buffer(m_outputMonitors[1], nframes));
1499 }
1500
1501 for (size_t i = 0; i < nframes; ++i) {
1502 sample_t sample = inputBufferRight[i] * gain;
1503 if (sample > peakRight)
1504 peakRight = sample;
1505 if (buf)
1506 buf[i] = sample;
1507 }
1508 }
1509 }
1510 }
1511
1512 if (channels < 2)
1513 peakRight = peakLeft;
1514
1515 LevelInfo info;
1516 info.level = AudioLevel::multiplier_to_fader
1517 (peakLeft, 127, AudioLevel::LongFader);
1518 info.levelRight = AudioLevel::multiplier_to_fader
1519 (peakRight, 127, AudioLevel::LongFader);
1520 SequencerDataBlock::getInstance()->setInstrumentRecordLevel(id, info);
1521
1522 if (wroteSomething) {
1523 m_fileWriter->signal();
1524 }
1525
1526 return 0;
1527 }
1528
1529
1530 int
1531 JackDriver::jackSyncCallback(jack_transport_state_t state,
1532 jack_position_t *position,
1533 void *arg)
1534 {
1535 JackDriver *inst = (JackDriver *)arg;
1536 if (!inst)
1537 return true; // or rather, return "huh?"
1538
1539 inst->m_alsaDriver->checkTimerSync(0); // reset, as not processing
1540
1541 if (!inst->m_jackTransportEnabled)
1542 return true; // ignore
1543
1544 RosegardenSequencer *sequencer =
1545 RosegardenSequencer::getInstance();
1546 if (!sequencer)
1547 return true;
1548
1549 #ifdef DEBUG_JACK_TRANSPORT
1550
1551 RG_DEBUG << "jackSyncCallback(): state " << state << " [" << (state == 0 ? "stopped" : state == 1 ? "rolling" : state == 2 ? "looping" : state == 3 ? "starting" : "unknown") << "], frame " << position->frame << ", waiting " << inst->m_waiting << ", playing " << inst->m_alsaDriver->isPlaying();
1552 RG_DEBUG << "jackSyncCallback(): m_waitingState " << inst->m_waitingState << ", unique_1 " << position->unique_1 << ", unique_2 " << position->unique_2;
1553 RG_DEBUG << "jackSyncCallback(): rate " << position->frame_rate << ", bar " << position->bar << ", beat " << position->beat << ", tick " << position->tick << ", bpm " << position->beats_per_minute;
1554
1555 #endif
1556
1557 RosegardenSequencer::TransportRequest request =
1558 RosegardenSequencer::TransportNoChange;
1559
1560 if (inst->m_alsaDriver->isPlaying()) {
1561
1562 if (state == JackTransportStarting) {
1563 request = RosegardenSequencer::TransportJumpToTime;
1564 } else if (state == JackTransportStopped) {
1565 request = RosegardenSequencer::TransportStop;
1566 }
1567
1568 } else {
1569
1570 if (state == JackTransportStarting) {
1571 request = RosegardenSequencer::TransportStartAtTime;
1572 } else if (state == JackTransportStopped) {
1573 request = RosegardenSequencer::TransportNoChange;
1574 }
1575 }
1576
1577 if (!inst->m_waiting || inst->m_waitingState != state) {
1578
1579 if (request == RosegardenSequencer::TransportJumpToTime ||
1580 request == RosegardenSequencer::TransportStartAtTime) {
1581
1582 RealTime rt = RealTime::frame2RealTime(position->frame,
1583 position->frame_rate);
1584
1585 #ifdef DEBUG_JACK_TRANSPORT
1586 RG_DEBUG << "jackSyncCallback(): Requesting jump to " << rt;
1587 #endif
1588
1589 inst->m_waitingToken = sequencer->transportJump(request, rt);
1590
1591 #ifdef DEBUG_JACK_TRANSPORT
1592 RG_DEBUG << "jackSyncCallback(): My token is " << inst->m_waitingToken;
1593 #endif
1594
1595 } else if (request == RosegardenSequencer::TransportStop) {
1596
1597 #ifdef DEBUG_JACK_TRANSPORT
1598 RG_DEBUG << "jackSyncCallback(): Requesting state change to " << request;
1599 #endif
1600
1601 inst->m_waitingToken = sequencer->transportChange(request);
1602
1603 #ifdef DEBUG_JACK_TRANSPORT
1604 RG_DEBUG << "jackSyncCallback(): My token is " << inst->m_waitingToken;
1605 #endif
1606
1607 } else if (request == RosegardenSequencer::TransportNoChange) {
1608
1609 #ifdef DEBUG_JACK_TRANSPORT
1610 RG_DEBUG << "jackSyncCallback(): Requesting no state change!";
1611 #endif
1612
1613 inst->m_waitingToken = sequencer->transportChange(request);
1614
1615 #ifdef DEBUG_JACK_TRANSPORT
1616 RG_DEBUG << "jackSyncCallback(): My token is " << inst->m_waitingToken;
1617 #endif
1618
1619 }
1620
1621 inst->m_waiting = true;
1622 inst->m_waitingState = state;
1623
1624 #ifdef DEBUG_JACK_TRANSPORT
1625 RG_DEBUG << "jackSyncCallback(): Setting waiting to " << inst->m_waiting << " and waiting state to " << inst->m_waitingState << " (request was " << request << ")";
1626 #endif
1627
1628 return 0;
1629
1630 } else {
1631
1632 if (sequencer->isTransportSyncComplete(inst->m_waitingToken)) {
1633 #ifdef DEBUG_JACK_TRANSPORT
1634 RG_DEBUG << "jackSyncCallback(): Sync complete";
1635 #endif
1636
1637 return 1;
1638 } else {
1639 #ifdef DEBUG_JACK_TRANSPORT
1640 RG_DEBUG << "jackSyncCallback(): Sync not complete";
1641 #endif
1642
1643 return 0;
1644 }
1645 }
1646 }
1647
1648 bool
1649 JackDriver::relocateTransportInternal(bool alsoStart)
1650 {
1651 if (!m_client)
1652 return true;
1653
1654 #ifdef DEBUG_JACK_TRANSPORT
1655 const char *fn = (alsoStart ?
1656 "JackDriver::startTransport()" :
1657 "JackDriver::relocateTransport()");
1658 #endif
1659
1660 #ifdef DEBUG_JACK_TRANSPORT
1661 RG_DEBUG << "relocateTransportInternal(): called by " << fn;
1662 #else
1663 #ifdef DEBUG_JACK_DRIVER
1664 RG_DEBUG << "relocateTransportInternal()";
1665 #endif
1666 #endif
1667
1668 // m_waiting is true if we are waiting for the JACK transport
1669 // to finish a change of state.
1670
1671 if (m_jackTransportEnabled) {
1672
1673 // If on the transport, we never return true here -- instead
1674 // the JACK process calls startClocksApproved() to signal to
1675 // the ALSA driver that it's time to go. But we do use this
1676 // to manage our JACK transport state requests.
1677
1678 // Where did this request come from? Are we just responding
1679 // to an external sync?
1680
1681 RosegardenSequencer *sequencer =
1682 RosegardenSequencer::getInstance();
1683
1684 if (sequencer) {
1685 if (sequencer->isTransportSyncComplete(m_waitingToken)) {
1686
1687 // Nope, this came from Rosegarden
1688
1689 #ifdef DEBUG_JACK_TRANSPORT
1690 RG_DEBUG << "relocateTransportInternal(): called by " << fn << ": asking JACK transport to start, setting wait state";
1691 #endif
1692
1693 m_waiting = true;
1694 m_waitingState = JackTransportStarting;
1695
1696 long frame = RealTime::realTime2Frame
1697 (m_alsaDriver->getSequencerTime(), m_sampleRate);
1698
1699 if (frame < 0) {
1700 // JACK Transport doesn't support preroll and
1701 // can't set transport position to before zero
1702 // (frame count is unsigned), so there's no very
1703 // satisfactory fix for what to do for count-in
1704 // bars. Let's just start at zero instead.
1705 jack_transport_locate(m_client, 0);
1706 } else {
1707 jack_transport_locate(m_client, frame);
1708 }
1709
1710 if (alsoStart) {
1711 jack_transport_start(m_client);
1712 m_ignoreProcessTransportCount = 1;
1713 } else {
1714 m_ignoreProcessTransportCount = 2;
1715 }
1716 } else {
1717 #ifdef DEBUG_JACK_TRANSPORT
1718 RG_DEBUG << "relocateTransportInternal(): called by " << fn << ": waiting already";
1719 #endif
1720
1721 }
1722 }
1723 return false;
1724 }
1725
1726 #if (defined(DEBUG_JACK_DRIVER) || defined(DEBUG_JACK_PROCESS) || defined(DEBUG_JACK_TRANSPORT))
1727 framesThisPlay = 0; //!!!
1728 struct timeval tv;
1729 (void)gettimeofday(&tv, 0);
1730 startTime = RealTime(tv.tv_sec, tv.tv_usec * 1000); //!!!
1731 #endif
1732 #ifdef DEBUG_JACK_TRANSPORT
1733
1734 RG_DEBUG << "relocateTransportInternal(): called by " << fn << ": not on JACK transport, accepting right away";
1735 #endif
1736
1737 return true;
1738 }
1739
1740 bool
1741 JackDriver::startTransport()
1742 {
1743 return relocateTransportInternal(true);
1744 }
1745
1746 bool
1747 JackDriver::relocateTransport()
1748 {
1749
1750 return relocateTransportInternal(false);
1751 }
1752
1753 void
1754 JackDriver::stopTransport()
1755 {
1756 if (!m_client)
1757 return ;
1758
1759 RG_DEBUG << "stopTransport(): resetting m_haveAsyncAudioEvent";
1760
1761 m_haveAsyncAudioEvent = false;
1762
1763 #ifdef DEBUG_JACK_TRANSPORT
1764
1765 struct timeval tv;
1766 (void)gettimeofday(&tv, 0);
1767 RealTime endTime = RealTime(tv.tv_sec, tv.tv_usec * 1000); //!!!
1768 RG_DEBUG << "stopTransport(): frames this play: " << framesThisPlay << ", elapsed " << (endTime - startTime);
1769 #endif
1770
1771 if (m_jackTransportEnabled) {
1772
1773 // Where did this request come from? Is this a result of our
1774 // sync to a transport that has in fact already stopped?
1775
1776 RosegardenSequencer *sequencer =
1777 RosegardenSequencer::getInstance();
1778
1779 if (sequencer) {
1780 if (sequencer->isTransportSyncComplete(m_waitingToken)) {
1781
1782 // No, we have no outstanding external requests; this
1783 // must have genuinely been requested from within
1784 // Rosegarden, so:
1785
1786 #ifdef DEBUG_JACK_TRANSPORT
1787 RG_DEBUG << "stopTransport(): internal request, asking JACK transport to stop";
1788 #endif
1789
1790 jack_transport_stop(m_client);
1791
1792 } else {
1793 // Nothing to do
1794
1795 #ifdef DEBUG_JACK_TRANSPORT
1796 RG_DEBUG << "stopTransport(): external request, JACK transport is already stopped";
1797 #endif
1798
1799 }
1800 }
1801 }
1802
1803 if (m_instrumentMixer)
1804 m_instrumentMixer->resetAllPlugins(true); // discard events too
1805 }
1806
1807
1808 // Pick up any change of buffer size
1809 //
1810 int
1811 JackDriver::jackBufferSize(jack_nframes_t nframes, void *arg)
1812 {
1813 JackDriver *inst = static_cast<JackDriver*>(arg);
1814
1815 #ifdef DEBUG_JACK_DRIVER
1816 RG_DEBUG << "jackBufferSize() - buffer size changed to " << nframes;
1817 #endif
1818
1819 inst->m_bufferSize = nframes;
1820
1821 // Recreate our temporary mix buffers to the new size
1822 //
1823 //!!! need buffer size change callbacks on plugins (so long as they
1824 // have internal buffers) and the mix manager, with locks acquired
1825 // appropriately
1826
1827 delete [] inst->m_tempOutBuffer;
1828 inst->m_tempOutBuffer = new sample_t[inst->m_bufferSize];
1829
1830 return 0;
1831 }
1832
1833 // Sample rate change
1834 //
1835 int
1836 JackDriver::jackSampleRate(jack_nframes_t nframes, void *arg)
1837 {
1838 JackDriver *inst = static_cast<JackDriver*>(arg);
1839
1840 #ifdef DEBUG_JACK_DRIVER
1841 RG_DEBUG << "jackSampleRate() - sample rate changed to " << nframes;
1842 #endif
1843
1844 inst->m_sampleRate = nframes;
1845
1846 return 0;
1847 }
1848
1849 void
1850 JackDriver::jackShutdown(void *arg)
1851 {
1852 #ifdef DEBUG_JACK_DRIVER
1853 RG_DEBUG << "jackShutdown() - callback received - informing GUI";
1854 #endif
1855
1856 #ifdef DEBUG_JACK_XRUN
1857 RG_DEBUG << "jackShutdown()";
1858 Profiles::getInstance()->dump();
1859 #endif
1860
1861 JackDriver *inst = static_cast<JackDriver*>(arg);
1862 inst->m_ok = false;
1863 inst->m_kickedOutAt = time(nullptr);
1864 inst->reportFailure(MappedEvent::FailureJackDied);
1865 }
1866
1867 int
1868 JackDriver::jackXRun(void *arg)
1869 {
1870 #ifdef DEBUG_JACK_DRIVER
1871 RG_DEBUG << "jackXRun()";
1872 #endif
1873
1874 #ifdef DEBUG_JACK_XRUN
1875 RG_DEBUG << "jackXRun()";
1876 Profiles::getInstance()->dump();
1877 #endif
1878
1879 // Report to GUI
1880 //
1881 JackDriver *inst = static_cast<JackDriver*>(arg);
1882 inst->reportFailure(MappedEvent::FailureXRuns);
1883
1884 return 0;
1885 }
1886
1887
1888 void
1889
1890 JackDriver::restoreIfRestorable()
1891 {
1892 if (m_kickedOutAt == 0)
1893 return ;
1894
1895 if (m_client) {
1896 jack_client_close(m_client);
1897 RG_DEBUG << "restoreIfRestorable(): closed client";
1898 m_client = nullptr;
1899 }
1900
1901 time_t now = time(nullptr);
1902
1903 if (now < m_kickedOutAt || now >= m_kickedOutAt + 3) {
1904
1905 if (m_instrumentMixer)
1906 m_instrumentMixer->resetAllPlugins(true);
1907 RG_DEBUG << "restoreIfRestorable(): reset plugins";
1908
1909 initialise(true);
1910
1911 if (m_ok) {
1912 reportFailure(MappedEvent::FailureJackRestart);
1913 } else {
1914 reportFailure(MappedEvent::FailureJackRestartFailed);
1915 }
1916
1917 m_kickedOutAt = 0;
1918 }
1919 }
1920
1921 void
1922 JackDriver::prepareAudio()
1923 {
1924 if (!m_instrumentMixer)
1925 return ;
1926
1927 // This is used when restarting clocks after repositioning, but
1928 // when not actually playing (yet). We need to do things like
1929 // regenerating the processing buffers here. prebufferAudio()
1930 // also does all of this, but rather more besides.
1931
1932 m_instrumentMixer->allocateBuffers();
1933 m_instrumentMixer->resetAllPlugins(false);
1934 }
1935
1936 void
1937 JackDriver::prebufferAudio()
1938 {
1939 if (!m_instrumentMixer)
1940 return ;
1941
1942 // We want this to happen when repositioning during playback, and
1943 // stopTransport no longer happens then, so we call it from here.
1944 // NB. Don't want to discard events here as this is called after
1945 // pushing events to the soft synth queues at startup
1946 m_instrumentMixer->resetAllPlugins(false);
1947
1948 #ifdef DEBUG_JACK_DRIVER
1949 RG_DEBUG << "prebufferAudio(): sequencer time is " << m_alsaDriver->getSequencerTime();
1950 #endif
1951
1952 RealTime sliceStart = getNextSliceStart(m_alsaDriver->getSequencerTime());
1953
1954 m_fileReader->fillBuffers(sliceStart);
1955
1956 if (m_bussMixer->getBussCount() > 0) {
1957 m_bussMixer->fillBuffers(sliceStart); // also calls on m_instrumentMixer
1958 } else {
1959 m_instrumentMixer->fillBuffers(sliceStart);
1960 }
1961 }
1962
1963 void
1964 JackDriver::kickAudio()
1965 {
1966 #ifdef DEBUG_JACK_PROCESS
1967 RG_DEBUG << "kickAudio()";
1968 #endif
1969
1970 if (m_fileReader)
1971 m_fileReader->kick();
1972 if (m_instrumentMixer)
1973 m_instrumentMixer->kick();
1974 if (m_bussMixer)
1975 m_bussMixer->kick();
1976 if (m_fileWriter)
1977 m_fileWriter->kick();
1978 }
1979
1980 void
1981 JackDriver::updateAudioData()
1982 {
1983 if (!m_ok || !m_client)
1984 return ;
1985
1986 #ifdef DEBUG_JACK_DRIVER
1987 //RG_DEBUG << "updateAudioData() begin...";
1988 #endif
1989
1990 MappedAudioBuss *mbuss =
1991 m_alsaDriver->getMappedStudio()->getAudioBuss(0);
1992
1993 if (mbuss) {
1994 float level = 0.0;
1995 (void)mbuss->getProperty(MappedAudioBuss::Level, level);
1996 m_masterLevel = level;
1997 }
1998
1999 unsigned long directMasterAudioInstruments = 0L;
2000 unsigned long directMasterSynthInstruments = 0L;
2001
2002 InstrumentId audioInstrumentBase;
2003 int audioInstruments;
2004 m_alsaDriver->getAudioInstrumentNumbers(audioInstrumentBase, audioInstruments);
2005
2006 InstrumentId synthInstrumentBase;
2007 int synthInstruments;
2008 m_alsaDriver->getSoftSynthInstrumentNumbers(synthInstrumentBase, synthInstruments);
2009
2010 RealTime jackLatency = getAudioPlayLatency();
2011 RealTime maxLatency = RealTime::zeroTime;
2012
2013 for (int i = 0; i < audioInstruments + synthInstruments; ++i) {
2014
2015 InstrumentId id;
2016 if (i < audioInstruments)
2017 id = audioInstrumentBase + i;
2018 else
2019 id = synthInstrumentBase + (i - audioInstruments);
2020
2021 MappedAudioFader *fader = m_alsaDriver->getMappedStudio()->getAudioFader(id);
2022 if (!fader)
2023 continue;
2024
2025 float f = 2;
2026 (void)fader->getProperty(MappedAudioFader::Channels, f);
2027 int channels = (int)f;
2028
2029 int inputChannel = -1;
2030 if (channels == 1) {
2031 float f = 0;
2032 (void)fader->getProperty(MappedAudioFader::InputChannel, f);
2033 inputChannel = (int)f;
2034 }
2035
2036 float level = 0.0;
2037 (void)fader->getProperty(MappedAudioFader::FaderRecordLevel, level);
2038
2039 // Like in base/Instrument.h, we use numbers < 1000 to
2040 // mean buss numbers and >= 1000 to mean record ins
2041 // when recording the record input number.
2042
2043 MappedObjectValueList connections = fader->getConnections
2044 (MappedConnectableObject::In);
2045 int input = 1000;
2046
2047 if (connections.empty()) {
2048
2049 RG_WARNING << "updateAudioData(): WARNING: No connections in for record instrument " << (id) << " (mapped id " << fader->getId() << ")";
2050
2051 // oh dear.
2052 input = 1000;
2053
2054 } else if (*connections.begin() == mbuss->getId()) {
2055
2056 input = 0;
2057
2058 } else {
2059
2060 MappedObject *obj = m_alsaDriver->getMappedStudio()->
2061 getObjectById(MappedObjectId(*connections.begin()));
2062
2063 if (!obj) {
2064
2065 RG_WARNING << "updateAudioData(): WARNING: No such object as " << *connections.begin();
2066 input = 1000;
2067 } else if (obj->getType() == MappedObject::AudioBuss) {
2068 input = (int)((MappedAudioBuss *)obj)->getBussId();
2069 } else if (obj->getType() == MappedObject::AudioInput) {
2070 input = (int)((MappedAudioInput *)obj)->getInputNumber()
2071 + 1000;
2072 } else {
2073 RG_WARNING << "updateAudioData(): WARNING: Object " << *connections.begin() << " is not buss or input";
2074 input = 1000;
2075 }
2076 }
2077
2078 if (m_recordInputs[id].input != input) {
2079 RG_DEBUG << "updateAudioData(): Changing record input for instrument " << id << " to " << input;
2080 }
2081 m_recordInputs[id] = RecordInputDesc(input, inputChannel, level);
2082
2083 size_t pluginLatency = 0;
2084 bool empty = m_instrumentMixer->isInstrumentEmpty(id);
2085
2086 if (!empty) {
2087 pluginLatency = m_instrumentMixer->getPluginLatency(id);
2088 }
2089
2090 // If we find the object is connected to no output, or to buss
2091 // number 0 (the master), then we set the bit appropriately.
2092
2093 connections = fader->getConnections(MappedConnectableObject::Out);
2094
2095 if (connections.empty() || (*connections.begin() == mbuss->getId())) {
2096 if (i < audioInstruments) {
2097 directMasterAudioInstruments |= (1 << i);
2098 } else {
2099 directMasterSynthInstruments |= (1 << (i - audioInstruments));
2100 }
2101 } else if (!empty) {
2102 pluginLatency +=
2103 m_instrumentMixer->getPluginLatency((unsigned int) * connections.begin() - 1);
2104 }
2105
2106 if (empty) {
2107 m_instrumentLatencies[id] = RealTime::zeroTime;
2108 } else {
2109 m_instrumentLatencies[id] = jackLatency +
2110 RealTime::frame2RealTime(pluginLatency, m_sampleRate);
2111 if (m_instrumentLatencies[id] > maxLatency) {
2112 maxLatency = m_instrumentLatencies[id];
2113 }
2114 }
2115 }
2116
2117 m_maxInstrumentLatency = maxLatency;
2118 m_directMasterAudioInstruments = directMasterAudioInstruments;
2119 m_directMasterSynthInstruments = directMasterSynthInstruments;
2120 m_maxInstrumentLatency = maxLatency;
2121
2122 int inputs = m_alsaDriver->getMappedStudio()->
2123 getObjectCount(MappedObject::AudioInput);
2124
2125 if (m_client) {
2126 // this will return with no work if the inputs are already correct:
2127 createRecordInputs(inputs);
2128 }
2129
2130 m_bussMixer->updateInstrumentConnections();
2131 m_instrumentMixer->updateInstrumentMuteStates();
2132
2133 if (m_bussMixer->getBussCount() == 0 || m_alsaDriver->getLowLatencyMode()) {
2134 if (m_bussMixer->running()) {
2135 m_bussMixer->terminate();
2136 }
2137 } else {
2138 if (!m_bussMixer->running()) {
2139 m_bussMixer->run();
2140 }
2141 }
2142
2143 if (m_alsaDriver->getLowLatencyMode()) {
2144 if (m_instrumentMixer->running()) {
2145 m_instrumentMixer->terminate();
2146 }
2147 } else {
2148 if (!m_instrumentMixer->running()) {
2149 m_instrumentMixer->run();
2150 }
2151 }
2152
2153 #ifdef DEBUG_JACK_DRIVER
2154 //RG_DEBUG << "updateAudioData() end";
2155 #endif
2156 }
2157
2158 void
2159 JackDriver::setAudioBussLevels(int bussNo, float dB, float pan)
2160 {
2161 if (m_bussMixer) {
2162 m_bussMixer->setBussLevels(bussNo, dB, pan);
2163 }
2164 }
2165
2166 void
2167 JackDriver::setAudioInstrumentLevels(InstrumentId instrument, float dB, float pan)
2168 {
2169 if (m_instrumentMixer) {
2170 m_instrumentMixer->setInstrumentLevels(instrument, dB, pan);
2171 }
2172 }
2173
2174 RealTime
2175 JackDriver::getNextSliceStart(const RealTime &now) const
2176 {
2177 jack_nframes_t frame;
2178 bool neg = false;
2179
2180 if (now < RealTime::zeroTime) {
2181 neg = true;
2182 frame = RealTime::realTime2Frame(RealTime::zeroTime - now, m_sampleRate);
2183 } else {
2184 frame = RealTime::realTime2Frame(now, m_sampleRate);
2185 }
2186
2187 jack_nframes_t rounded = frame;
2188 rounded /= m_bufferSize;
2189 rounded *= m_bufferSize;
2190
2191 RealTime roundrt;
2192
2193 if (rounded == frame)
2194 roundrt = RealTime::frame2RealTime(rounded, m_sampleRate);
2195 else if (neg)
2196 roundrt = RealTime::frame2RealTime(rounded, m_sampleRate);
2197 else
2198 roundrt = RealTime::frame2RealTime(rounded + m_bufferSize, m_sampleRate);
2199
2200 if (neg)
2201 roundrt = RealTime::zeroTime - roundrt;
2202
2203 return roundrt;
2204 }
2205
2206
2207 int
2208 JackDriver::getAudioQueueLocks()
2209 {
2210 // We have to lock the mixers first, because the mixers can try to
2211 // lock the disk manager from within a locked section -- so if we
2212 // locked the disk manager first we would risk deadlock when
2213 // trying to acquire the instrument mixer lock
2214
2215 int rv = 0;
2216 if (m_bussMixer) {
2217 #ifdef DEBUG_JACK_DRIVER
2218 RG_DEBUG << "getAudioQueueLocks(): trying to lock buss mixer";
2219 #endif
2220
2221 rv = m_bussMixer->getLock();
2222 if (rv)
2223 return rv;
2224 }
2225 if (m_instrumentMixer) {
2226 #ifdef DEBUG_JACK_DRIVER
2227 RG_DEBUG << "getAudioQueueLocks(): ok, now trying for instrument mixer";
2228 #endif
2229
2230 rv = m_instrumentMixer->getLock();
2231 if (rv)
2232 return rv;
2233 }
2234 if (m_fileReader) {
2235 #ifdef DEBUG_JACK_DRIVER
2236 RG_DEBUG << "getAudioQueueLocks(): ok, now trying for disk reader";
2237 #endif
2238
2239 rv = m_fileReader->getLock();
2240 if (rv)
2241 return rv;
2242 }
2243 if (m_fileWriter) {
2244 #ifdef DEBUG_JACK_DRIVER
2245 RG_DEBUG << "getAudioQueueLocks(): ok, now trying for disk writer";
2246 #endif
2247
2248 rv = m_fileWriter->getLock();
2249 }
2250 #ifdef DEBUG_JACK_DRIVER
2251 RG_DEBUG << "getAudioQueueLocks(): ok";
2252 #endif
2253
2254 return rv;
2255 }
2256
2257 int
2258 JackDriver::tryAudioQueueLocks()
2259 {
2260 int rv = 0;
2261 if (m_bussMixer) {
2262 rv = m_bussMixer->tryLock();
2263 if (rv)
2264 return rv;
2265 }
2266 if (m_instrumentMixer) {
2267 rv = m_instrumentMixer->tryLock();
2268 if (rv) {
2269 if (m_bussMixer) {
2270 m_bussMixer->releaseLock();
2271 }
2272 }
2273 }
2274 if (m_fileReader) {
2275 rv = m_fileReader->tryLock();
2276 if (rv) {
2277 if (m_instrumentMixer) {
2278 m_instrumentMixer->releaseLock();
2279 }
2280 if (m_bussMixer) {
2281 m_bussMixer->releaseLock();
2282 }
2283 }
2284 }
2285 if (m_fileWriter) {
2286 rv = m_fileWriter->tryLock();
2287 if (rv) {
2288 if (m_fileReader) {
2289 m_fileReader->releaseLock();
2290 }
2291 if (m_instrumentMixer) {
2292 m_instrumentMixer->releaseLock();
2293 }
2294 if (m_bussMixer) {
2295 m_bussMixer->releaseLock();
2296 }
2297 }
2298 }
2299 return rv;
2300 }
2301
2302 int
2303 JackDriver::releaseAudioQueueLocks()
2304 {
2305 int rv = 0;
2306 #ifdef DEBUG_JACK_DRIVER
2307 RG_DEBUG << "releaseAudioQueueLocks()";
2308 #endif
2309
2310 if (m_fileWriter)
2311 rv = m_fileWriter->releaseLock();
2312 if (m_fileReader)
2313 rv = m_fileReader->releaseLock();
2314 if (m_instrumentMixer)
2315 rv = m_instrumentMixer->releaseLock();
2316 if (m_bussMixer)
2317 rv = m_bussMixer->releaseLock();
2318 return rv;
2319 }
2320
2321
2322 void
2323 JackDriver::setPluginInstance(InstrumentId id, QString identifier,
2324 int position)
2325 {
2326 if (m_instrumentMixer) {
2327 m_instrumentMixer->setPlugin(id, position, identifier);
2328 }
2329 if (!m_alsaDriver->isPlaying()) {
2330 prebufferAudio(); // to ensure the plugin's ringbuffers are generated
2331 }
2332 }
2333
2334 void
2335 JackDriver::removePluginInstance(InstrumentId id, int position)
2336 {
2337 if (m_instrumentMixer)
2338 m_instrumentMixer->removePlugin(id, position);
2339 }
2340
2341 void
2342 JackDriver::setPluginInstancePortValue(InstrumentId id, int position,
2343 unsigned long portNumber,
2344 float value)
2345 {
2346 if (m_instrumentMixer)
2347 m_instrumentMixer->setPluginPortValue(id, position, portNumber, value);
2348 }
2349
2350 float
2351 JackDriver::getPluginInstancePortValue(InstrumentId id, int position,
2352 unsigned long portNumber)
2353 {
2354 if (m_instrumentMixer)
2355 return m_instrumentMixer->getPluginPortValue(id, position, portNumber);
2356 return 0;
2357 }
2358
2359 void
2360 JackDriver::setPluginInstanceBypass(InstrumentId id, int position, bool value)
2361 {
2362 if (m_instrumentMixer)
2363 m_instrumentMixer->setPluginBypass(id, position, value);
2364 }
2365
2366 QStringList
2367 JackDriver::getPluginInstancePrograms(InstrumentId id, int position)
2368 {
2369 if (m_instrumentMixer)
2370 return m_instrumentMixer->getPluginPrograms(id, position);
2371 return QStringList();
2372 }
2373
2374 QString
2375 JackDriver::getPluginInstanceProgram(InstrumentId id, int position)
2376 {
2377 if (m_instrumentMixer)
2378 return m_instrumentMixer->getPluginProgram(id, position);
2379 return QString();
2380 }
2381
2382 QString
2383 JackDriver::getPluginInstanceProgram(InstrumentId id, int position,
2384 int bank, int program)
2385 {
2386 if (m_instrumentMixer)
2387 return m_instrumentMixer->getPluginProgram(id, position, bank, program);
2388 return QString();
2389 }
2390
2391 unsigned long
2392 JackDriver::getPluginInstanceProgram(InstrumentId id, int position, QString name)
2393 {
2394 if (m_instrumentMixer)
2395 return m_instrumentMixer->getPluginProgram(id, position, name);
2396 return 0;
2397 }
2398
2399 void
2400 JackDriver::setPluginInstanceProgram(InstrumentId id, int position, QString program)
2401 {
2402 if (m_instrumentMixer)
2403 m_instrumentMixer->setPluginProgram(id, position, program);
2404 }
2405
2406 QString
2407 JackDriver::configurePlugin(InstrumentId id, int position, QString key, QString value)
2408 {
2409 if (m_instrumentMixer)
2410 return m_instrumentMixer->configurePlugin(id, position, key, value);
2411 return QString();
2412 }
2413
2414 RunnablePluginInstance *
2415 JackDriver::getSynthPlugin(InstrumentId id)
2416 {
2417 if (m_instrumentMixer)
2418 return m_instrumentMixer->getSynthPlugin(id);
2419 else
2420 return nullptr;
2421 }
2422
2423 void
2424 JackDriver::clearSynthPluginEvents()
2425 {
2426 if (!m_instrumentMixer) return;
2427
2428 #ifdef DEBUG_JACK_DRIVER
2429 RG_DEBUG << "clearSynthPluginEvents()";
2430 #endif
2431
2432 m_instrumentMixer->discardPluginEvents();
2433 }
2434
2435 bool
2436 JackDriver::openRecordFile(InstrumentId id,
2437 const QString &filename)
2438 {
2439 if (m_fileWriter) {
2440 if (!m_fileWriter->running()) {
2441 m_fileWriter->run();
2442 }
2443 return m_fileWriter->openRecordFile(id, filename);
2444 } else {
2445 RG_WARNING << "openRecordFile(): WARNING: No file writer available!";
2446 return false;
2447 }
2448 }
2449
2450 bool
2451 JackDriver::closeRecordFile(InstrumentId id,
2452 AudioFileId &returnedId)
2453 {
2454 if (m_fileWriter) {
2455 return m_fileWriter->closeRecordFile(id, returnedId);
2456 if (m_fileWriter->running() && !m_fileWriter->haveRecordFilesOpen()) {
2457 m_fileWriter->terminate();
2458 }
2459 } else
2460 return false;
2461 }
2462
2463
2464 void
2465 JackDriver::reportFailure(MappedEvent::FailureCode code)
2466 {
2467 if (m_alsaDriver)
2468 m_alsaDriver->reportFailure(code);
2469 }
2470
2471
2472 }
2473
2474 #endif // HAVE_LIBJACK
2475 #endif // HAVE_ALSA
2476