1 //=========================================================
2 //  MusE
3 //  Linux Music Editor
4 //  $Id: audio.cpp,v 1.59.2.30 2009/12/20 05:00:35 terminator356 Exp $
5 //
6 //  (C) Copyright 2001-2004 Werner Schweer (ws@seh.de)
7 //  (C) Copyright 2011 Tim E. Real (terminator356 on users dot sourceforge dot net)
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
11 //  as published by the Free Software Foundation; version 2 of
12 //  the License, or (at your option) any later version.
13 //
14 //  This program is distributed in the hope that it will be useful,
15 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
16 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 //  GNU General Public License for more details.
18 //
19 //  You should have received a copy of the GNU General Public License
20 //  along with this program; if not, write to the Free Software
21 //  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
22 //
23 //=========================================================
24 
25 #include "muse_math.h"
26 #include <set>
27 #include <errno.h>
28 #include <fcntl.h>
29 
30 #include "app.h"
31 #include "song.h"
32 #include "mididev.h"
33 #include "alsamidi.h"
34 #include "audioprefetch.h"
35 #include "audio.h"
36 #include "tempo.h"
37 #include "wave.h"
38 #include "midictrl.h"
39 #include "midiseq.h"
40 #include "midi.h"
41 #include "gconfig.h"
42 #include "ticksynth.h"
43 #include "globals.h"
44 #include "large_int.h"
45 
46 // Forwards from header:
47 #include "audiodev.h"
48 #include "sync.h"
49 #include "mididev.h"
50 #include "midiport.h"
51 #include "minstrument.h"
52 #include "track.h"
53 #include "part.h"
54 #include "event.h"
55 #include "mpevent.h"
56 #include "plugin.h"
57 #include "synth.h"
58 #include "undo.h"
59 #include "operations.h"
60 
61 #ifdef _WIN32
62 #define pipe(fds) _pipe(fds, 4096, _O_BINARY)
63 #endif
64 
65 // Experimental for now - allow other Jack timebase masters to control our midi engine.
66 // TODO: Be friendly to other apps and ask them to be kind to us by using jack_transport_reposition.
67 //       It is actually required IF we want the extra position info to show up
68 //        in the sync callback, otherwise we get just the frame only.
69 //       This information is shared on the server, it is directly passed around.
70 //       jack_transport_locate blanks the info from sync until the timebase callback reads
71 //        it again right after, from some timebase master.
72 //       Sadly not many of us use jack_transport_reposition. So we need to work around it !
73 //#define _JACK_TIMEBASE_DRIVES_MIDI_
74 
75 #ifdef _JACK_TIMEBASE_DRIVES_MIDI_
76 #include "jackaudio.h"
77 #endif
78 
79 // Undefine if and when multiple output routes are added to midi tracks.
80 #define _USE_MIDI_TRACK_SINGLE_OUT_PORT_CHAN_
81 
82 // For debugging metronome and precount output: Uncomment the fprintf section.
83 #define DEBUG_MIDI_METRONOME(dev, format, args...) // fprintf(dev, format, ##args);
84 // For debugging midi timing: Uncomment the fprintf section.
85 #define DEBUG_TRANSPORT_SYNC(dev, format, args...) // fprintf(dev, format, ##args);
86 
87 namespace MusEGlobal {
88 MusECore::Audio* audio = NULL;
89 MusECore::AudioDevice* audioDevice = NULL;   // current audio device in use
90 extern unsigned int volatile midiExtSyncTicks;
91 }
92 
93 namespace MusECore {
94 
initAudio()95 void initAudio()
96 {
97       MusEGlobal::audio = new Audio();
98 }
99 
100 extern uint64_t curTimeUS();
101 
102 const char* seqMsgList[] = {
103       "SEQM_REVERT_OPERATION_GROUP", "SEQM_EXECUTE_OPERATION_GROUP",
104       "SEQM_EXECUTE_PENDING_OPERATIONS",
105       "SEQM_RESET_DEVICES", "SEQM_INIT_DEVICES", "SEQM_PANIC",
106       "SEQM_MIDI_LOCAL_OFF",
107       "SEQM_PLAY_MIDI_EVENT",
108       "SEQM_SET_HW_CTRL_STATE",
109       "SEQM_SET_HW_CTRL_STATES",
110       "SEQM_SET_TRACK_AUTO_TYPE",
111       "SEQM_SET_AUX",
112       "SEQM_UPDATE_SOLO_STATES",
113       "AUDIO_ROUTEADD", "AUDIO_ROUTEREMOVE", "AUDIO_REMOVEROUTES",
114       "AUDIO_ADDPLUGIN",
115       "AUDIO_SET_PREFADER", "AUDIO_SET_CHANNELS",
116       "AUDIO_SWAP_CONTROLLER_IDX",
117       "AUDIO_CLEAR_CONTROLLER_EVENTS",
118       "AUDIO_SEEK_PREV_AC_EVENT",
119       "AUDIO_SEEK_NEXT_AC_EVENT",
120       "AUDIO_ERASE_AC_EVENT",
121       "AUDIO_ERASE_RANGE_AC_EVENTS",
122       "AUDIO_ADD_AC_EVENT",
123       "AUDIO_CHANGE_AC_EVENT",
124       "AUDIO_SET_SEND_METRONOME",
125       "AUDIO_START_MIDI_LEARN",
126       "MS_PROCESS", "MS_STOP", "MS_SET_RTC", "MS_UPDATE_POLL_FD",
127       "SEQM_IDLE", "SEQM_SEEK",
128       "AUDIO_WAIT"
129       };
130 
131 const char* audioStates[] = {
132       "STOP", "START_PLAY", "PLAY", "LOOP1", "LOOP2", "SYNC", "PRECOUNT"
133       };
134 
135 
136 //---------------------------------------------------------
137 //   Audio
138 //---------------------------------------------------------
139 
140 const int Audio::_extClockHistoryCapacity = 8192;
141 const unsigned int Audio::_clockOutputQueueCapacity = 8192;
142 
Audio()143 Audio::Audio()
144       {
145       _running      = false;
146       recording     = false;
147       idle          = false;
148       _freewheel    = false;
149       _bounceState  = BounceOff;
150       _loopFrame    = 0;
151       _loopCount    = 0;
152       m_Xruns       = 0;
153 
154       _pos.setType(Pos::FRAMES);
155       _pos.setFrame(0);
156       _curCycleFrames = 0;
157       nextTickPos = curTickPos = 0;
158       _precountFramePos = 0;
159       framesBeat = 0;
160       framesBeatDivisor = 0;
161       framesBeatRemainder = 0;
162       precountMidiClickFrame = 0;
163       precountMidiClickFrameRemainder = 0;
164       precountTotalFrames = 0;
165       _syncPlayStarting = false;
166       // Set for way beyond the end of the expected count.
167       _antiSeekFloodCounter = 100000.0;
168       _syncReady = true;
169 
170       midiClick     = 0;
171       audioClick    = 0;
172       clickno       = 0;
173       clicksMeasure = 0;
174 
175       _extClockHistory = new ExtMidiClock[_extClockHistoryCapacity];
176       _extClockHistorySize = 0;
177 
178       _clockOutputQueue = new unsigned int[_clockOutputQueueCapacity];
179       _clockOutputQueueSize = 0;
180       _clockOutputCounter = 0;
181       _clockOutputCounterRemainder = 0;
182 
183       syncTimeUS    = 0;
184       syncFrame     = 0;
185 
186       state         = STOP;
187       msg           = 0;
188 
189       startRecordPos.setType(Pos::FRAMES);  // Tim
190       endRecordPos.setType(Pos::FRAMES);
191       startExternalRecTick = 0;
192       endExternalRecTick = 0;
193 
194       //---------------------------------------------------
195       //  establish pipes/sockets
196       //---------------------------------------------------
197 
198       int filedes[2];         // 0 - reading   1 - writing
199       if (pipe(filedes) == -1) {
200             perror("creating pipe0");
201             exit(-1);
202             }
203       fromThreadFdw = filedes[1];
204       fromThreadFdr = filedes[0];
205 #ifndef _WIN32
206       int rv = fcntl(fromThreadFdw, F_SETFL, O_NONBLOCK);
207       if (rv == -1)
208             perror("set pipe O_NONBLOCK");
209 #endif
210       if (pipe(filedes) == -1) {
211             perror("creating pipe1");
212             exit(-1);
213             }
214       sigFd = filedes[1];
215       sigFdr = filedes[0];
216       }
217 
~Audio()218 Audio::~Audio()
219 {
220   if(_clockOutputQueue)
221     delete[] _clockOutputQueue;
222   if(_extClockHistory)
223     delete[] _extClockHistory;
224 }
225 
226 //---------------------------------------------------------
227 //   start
228 //    start audio processing
229 //---------------------------------------------------------
230 
231 extern bool initJackAudio();
232 
start()233 bool Audio::start()
234       {
235       state = STOP;
236       _loopCount = 0;
237 
238       //MusEGlobal::muse->setHeartBeat();  // Moved below
239 
240       if (!MusEGlobal::audioDevice) {
241           if(initJackAudio() == false) {
242                 InputList* itl = MusEGlobal::song->inputs();
243                 for (iAudioInput i = itl->begin(); i != itl->end(); ++i) {
244                       if (MusEGlobal::debugMsg) fprintf(stderr, "reconnecting input %s\n", (*i)->name().toLatin1().data());
245                       for (int x=0; x < (*i)->channels();x++)
246                           (*i)->setJackPort(x,0);
247                       (*i)->registerPorts();
248                       }
249 
250                 OutputList* otl = MusEGlobal::song->outputs();
251                 for (iAudioOutput i = otl->begin(); i != otl->end(); ++i) {
252                       if (MusEGlobal::debugMsg) fprintf(stderr, "reconnecting output %s\n", (*i)->name().toLatin1().data());
253                       for (int x=0; x < (*i)->channels();x++)
254                           (*i)->setJackPort(x,0);
255                       if (MusEGlobal::debugMsg) fprintf(stderr, "name=%s\n",(*i)->name().toLatin1().data());
256                       (*i)->registerPorts();
257                       }
258                }
259           else {
260                fprintf(stderr, "Failed to init audio!\n");
261                return false;
262                }
263           }
264 
265       _running = true;  // Set before we start to avoid error messages in process.
266       if(!MusEGlobal::audioDevice->start(MusEGlobal::realTimePriority))
267       {
268         fprintf(stderr, "Failed to start audio!\n");
269         _running = false;
270         return false;
271       }
272 
273       // shall we really stop JACK transport and locate to
274       // saved position?
275 
276       MusEGlobal::audioDevice->stopTransport();
277 
278       MusEGlobal::audioDevice->seekTransport(MusEGlobal::song->cPos());
279 
280       // Should be OK to start this 'leisurely' timer only after everything
281       //  else has been started.
282       MusEGlobal::muse->setHeartBeat();
283 
284       return true;
285       }
286 
287 //---------------------------------------------------------
288 //   stop
289 //    stop audio processing
290 //---------------------------------------------------------
291 
stop(bool)292 void Audio::stop(bool)
293       {
294       // Stop timer. Possible random crashes closing a song and loading another song -
295       //  observed a few times in mixer strip timer handlers (updatexxx). Not sure how
296       //  (we're in the graphics thread), but in case something during loading runs
297       //  the event loop or something, this should at least not hurt. 2019/01/24 Tim.
298       MusEGlobal::muse->stopHeartBeat();
299 
300       if (MusEGlobal::audioDevice)
301             MusEGlobal::audioDevice->stop();
302       _running = false;
303       }
304 
305 //---------------------------------------------------------
306 //   sync
307 //    return true if sync is completed
308 //---------------------------------------------------------
309 
sync(int jackState,unsigned frame)310 bool Audio::sync(int jackState, unsigned frame)
311 {
312   DEBUG_TRANSPORT_SYNC(stderr, "Audio::sync() begin: state:%d jackState:%d frame:%u pos frame:%u\n", state, jackState, frame, _pos.frame());
313 
314   bool done = true;
315   if (state == PRECOUNT)
316   {
317       DEBUG_TRANSPORT_SYNC(stderr, "Audio::sync: PRECOUNT: _precountFramePos:%u precountTotalFrames:%u\n",
318       _precountFramePos, precountTotalFrames);
319 
320     // Is it requesting a different frame (seek during sync)?
321     // Don't interrupt freewheel mode.
322     if (frame != _pos.frame() && !_freewheel)
323     {
324       DEBUG_TRANSPORT_SYNC(stderr, "   state == PRECOUNT, pos frame:%u req frame:%u calling seek...\n", _pos.frame(), frame);
325       seek(Pos(frame, false));
326 
327       done = MusEGlobal::audioPrefetch->seekDone();
328 
329       // We're in precount state, so it must have started from stop state. Set to true.
330       _syncPlayStarting = true;
331 
332       // Is the audio prefetch already done?
333       if(done)
334       {
335         // Reset the flag now.
336         _syncPlayStarting = false;
337         // Does the precount start over again? Return false if so, to continue holding up the transport.
338         // This will start the precount if necessary and set the state to PRECOUNT.
339         if(startPreCount())
340         {
341           _syncReady = false;
342           return _syncReady;
343         }
344       }
345 
346       state = START_PLAY;
347       _syncReady = done;
348       return _syncReady;
349     }
350 
351     _syncReady = _precountFramePos >= precountTotalFrames;
352     return _syncReady;
353   }
354 
355   if (state == LOOP1)
356   {
357     state = LOOP2;
358   }
359   else
360   {
361     State s = State(jackState);
362 
363     //  STOP -> START_PLAY      start rolling
364     //  STOP -> STOP            seek in stop state
365     //  PLAY -> START_PLAY  seek in play state
366 
367     if (state != START_PLAY)
368     {
369       // Is this the first of possibly multiple sync calls?
370       if(_syncReady)
371       {
372         Pos p(frame, false);
373         DEBUG_TRANSPORT_SYNC(stderr, "   state != START_PLAY, req frame:%u calling seek...\n", frame);
374         seek(p);
375       }
376 
377       if (!_freewheel)
378         done = MusEGlobal::audioPrefetch->seekDone();
379 
380       if (s == START_PLAY)
381       {
382         _syncPlayStarting = (state == STOP);
383 
384         DEBUG_TRANSPORT_SYNC(stderr, "state != START_PLAY: done:%d\n", done);
385 
386         // Is this a STOP to START_PLAY transition?
387         if(_syncPlayStarting)
388         {
389           // Stop the timer.
390           _antiSeekFloodCounter = 100000.0;
391 
392           // Is the audio prefetch already done?
393           if(done)
394           {
395             // Reset the flag now.
396             _syncPlayStarting = false;
397             // Does the precount start? Return false if so, to begin holding up the transport.
398             // This will start the precount if necessary and set the state to PRECOUNT.
399             if(startPreCount())
400             {
401               _syncReady = false;
402               return _syncReady;
403             }
404           }
405         }
406         else
407         {
408           // Start the timer.
409           _antiSeekFloodCounter = 0.0;
410         }
411 
412         state = START_PLAY;
413       }
414     }
415     else
416     {
417       // Is it requesting a different frame (seek during seek)?
418       // Don't interrupt freewheel mode.
419       if (frame != _pos.frame() && !_freewheel)
420       {
421         DEBUG_TRANSPORT_SYNC(stderr, "   state == START_PLAY, pos frame:%u req frame:%u calling seek...\n", _pos.frame(), frame);
422         seek(Pos(frame, false));
423 
424         // Reset timer to start it.
425         _antiSeekFloodCounter = 0.0;
426       }
427 
428       done = MusEGlobal::audioPrefetch->seekDone();
429 
430       if(_antiSeekFloodCounter < 0.4)
431       {
432         done = false;
433         _antiSeekFloodCounter += (float)MusEGlobal::segmentSize / (float)MusEGlobal::sampleRate;
434       }
435 
436       DEBUG_TRANSPORT_SYNC(stderr, "state == START_PLAY: done:%d\n", done);
437 
438       // Was this a STOP to START_PLAY transition?
439       if(_syncPlayStarting)
440       {
441         // Are the audio prefetch done and anti-flood timer done?
442         if(done)
443         {
444           // Reset the flag now.
445           _syncPlayStarting = false;
446           // Does the precount start? Return false if so, to continue (or begin) holding up the transport.
447           // This will start the precount if necessary and set the state to PRECOUNT.
448           if(startPreCount())
449           {
450             _syncReady = false;
451             return _syncReady;
452           }
453         }
454       }
455     }
456   }
457 
458   //fprintf(stderr, "Audio::sync() end: state:%d pos frame:%u\n", state, _pos.frame());
459   _syncReady = done;
460   return _syncReady;
461 }
462 
463 //---------------------------------------------------------
464 //   startPreCount
465 //    During sync(), starts count-in state if necessary and returns whether
466 //     count-in state has been started.
467 //---------------------------------------------------------
468 
startPreCount()469 bool Audio::startPreCount()
470 {
471   MusECore::MetronomeSettings* metro_settings =
472     MusEGlobal::metroUseSongSettings ? &MusEGlobal::metroSongSettings : &MusEGlobal::metroGlobalSettings;
473 
474   // Since other Jack clients might also set the sync timeout at any time,
475   //  we need to be constantly enforcing our desired limit!
476   // Since setSyncTimeout() may not be realtime friendly (Jack driver),
477   //  we set the driver's sync timeout in the gui thread.
478   // Sadly, we likely cannot get away with setting it here via the audio sync callback.
479   // So whenever stop, start or seek occurs, we'll try to casually enforce the timeout in Song::seqSignal().
480   // It's casual, unfortunately we can't set the EXACT timeout amount here when we really need to.
481 
482   if (metro_settings->precountEnableFlag
483     && MusEGlobal::song->click()
484     && !MusEGlobal::extSyncFlag
485     && ((!MusEGlobal::song->record() && metro_settings->precountOnPlay) || MusEGlobal::song->record()))
486   {
487         DEBUG_MIDI_METRONOME(stderr, "state = PRECOUNT!\n");
488         state = PRECOUNT;
489 
490         int bar, beat;
491         unsigned tick;
492         MusEGlobal::sigmap.tickValues(curTickPos, &bar, &beat, &tick);
493 
494         int z, n;
495         if (metro_settings->precountFromMastertrackFlag)
496               MusEGlobal::sigmap.timesig(curTickPos, z, n);
497         else {
498               z = metro_settings->precountSigZ;
499               n = metro_settings->precountSigN;
500               }
501         clickno       = 0;
502         int clicks_total = z * metro_settings->preMeasures;
503         clicksMeasure = z;
504         int ticks_beat     = (MusEGlobal::config.division * 4)/n;
505         // The number of frames per beat in precount state.
506 //         framesBeat    = MusEGlobal::tempomap.ticks2frames((MusEGlobal::config.division * 4) / n, curTickPos);
507 
508 
509 
510         // The number of frames per beat in precount state.
511         // Tick resolution is less than frame resolution.
512         // Round up so that the reciprocal function (frame to tick) matches value for value.
513         //framesBeat = muse_multiply_64_div_64_to_64(
514         //  (uint64_t)MusEGlobal::sampleRate * (uint64_t)MusEGlobal::tempomap.tempo(curTickPos), (MusEGlobal::config.division * 4) / n,
515         //  (uint64_t)MusEGlobal::config.division * (uint64_t)MusEGlobal::tempomap.globalTempo() * 10000UL, true);
516         //framesBeat =
517         //  (4UL * (uint64_t)MusEGlobal::sampleRate * (uint64_t)MusEGlobal::tempomap.tempo(curTickPos)) /
518         //  ((uint64_t)n * (uint64_t)MusEGlobal::tempomap.globalTempo() * 10000UL);
519         const uint64_t framesBeatDividend = (uint64_t)MusEGlobal::sampleRate * (uint64_t)MusEGlobal::tempomap.tempo(curTickPos) * 4;
520         framesBeatDivisor = n * MusEGlobal::tempomap.globalTempo() * 10000;
521         framesBeat = framesBeatDividend / framesBeatDivisor;
522         framesBeatRemainder = framesBeatDividend % framesBeatDivisor;
523 
524         // Reset to zero.
525         _precountFramePos = 0;
526 
527         // How many ticks are required for the precount?
528         const unsigned int precount_ticks = clicks_total * ticks_beat;
529         // How many extra precount ticks are required to 'fill in' for a mid-bar curTickPos?
530         const unsigned int extra_precount_ticks = beat * ticks_beat + tick;
531         // What is the current tick's frame (not the more accurate device frame)?
532         const unsigned int cur_tick_frame = Pos(curTickPos, true).frame();
533         // How many total frames are required for the precount?
534         precountTotalFrames =
535           MusEGlobal::tempomap.ticks2frames(precount_ticks + extra_precount_ticks, curTickPos);
536         // How many more (or less) frames are required, in case the cursor is on a frame in-between ticks?
537         // If lrint() rounding is used in our tempo routines, the difference between current tick's frame
538         //  and current device frame can actually be negative!
539         if(_pos.frame() > cur_tick_frame)
540         {
541           precountTotalFrames += (_pos.frame() - cur_tick_frame);
542         }
543         else
544         {
545           // Basic protection from underflow.
546           if(precountTotalFrames < (cur_tick_frame - _pos.frame()))
547             precountTotalFrames = 0;
548           else
549             precountTotalFrames -= cur_tick_frame - _pos.frame();
550         }
551 
552         // What is the remainder of the total frames divided by the segment size?
553         // This is the value that the precount frame times should be shifted backwards so that
554         //  the very last precount frame + 1 lines up exactly with the first metronome frame.
555         // But since we cannot schedule before the current time, we trick it by shifting
556         //  forward and sacrificing one cycle. Therefore this value is referenced to the
557         //  start of a cycle buffer, not the end.
558         // The offset ranges from 1 to segmentSize inclusive.
559         unsigned int precount_frame_offset = MusEGlobal::segmentSize - (precountTotalFrames % MusEGlobal::segmentSize);
560         // Start the precount at this frame.
561         precountMidiClickFrame = precount_frame_offset;
562         precountMidiClickFrameRemainder = 0;
563         // Make room in the total frames for the offset as well.
564         precountTotalFrames += precount_frame_offset;
565 
566         DEBUG_MIDI_METRONOME(stderr, "Audio::startPreCount: _pos.tick():%u _pos.frame():%u "
567           "curTickPos:%u cur_tick_frame:%u extra_precount_frames:%d "
568           "clicks_total:%d framesBeat:%u precount_ticks:%u extra_precount_ticks:%u\n"
569           "precountTotalFrames:%u precount_frame_offset:%u precountMidiClickFrame:%u\n",
570           _pos.tick(), _pos.frame(), curTickPos, cur_tick_frame, _pos.frame() - cur_tick_frame, clicks_total, framesBeat,
571           precount_ticks, extra_precount_ticks, precountTotalFrames, precount_frame_offset, precountMidiClickFrame);
572 
573         return true;
574   }
575 
576   return false;
577 }
578 
579 //---------------------------------------------------------
580 //   reSyncAudio
581 //    To be called from audio thread only.
582 //---------------------------------------------------------
583 
reSyncAudio()584 void Audio::reSyncAudio()
585 {
586   if (isPlaying())
587   {
588     if (!MusEGlobal::checkAudioDevice()) return;
589     // NOTE: Comment added by Tim: This line is crucial if the tempo is changed during playback,
590     //  either via changes to tempo map or the static tempo value. The actual transport frame is allowed
591     //  to continue progressing naturally but our representation of it (_pos) jumps to a new value
592     //  so that the relation between ticks and frames in all our tempo routines remains correct.
593     // But the relation betweeen actual transport frame and current tick will still be incorrect
594     //  for the given new tempo value, that is why this adjustment to our _pos is needed.
595     // Another solution would be to actually seek the transport to the correct frame.
596     // In either solution any waves will jump to a new position but midi will continue on.
597     // A third solution is not jump at all. Instead curTickPos is incremented with a 'delta' rather
598     //  than by incrementing _pos and converting to tick. Both midi and audio progress naturally.
599     // But this has a problem in that we cannot use fractional remainder techniques because the
600     //  tempo is part of the denominator and changes with every tempo change, so adding incremental
601     //  fractions with different denominators together would be tough (cross multiply etc.).
602     // Seems the only way for a delta then is to express it as say microticks (1/1,000,000 of a tick).
603     // But even microticks may not be enough, calculations show nanoticks would be better.
604     // The issue is that the resolution must be very high so that the slight error in the
605     //  increment value does not build up over time and cause drift between frame and tick.
606     _pos.setTick(curTickPos);
607     syncFrame     = MusEGlobal::audioDevice->framesAtCycleStart();
608     syncTimeUS    = curTimeUS();
609   }
610 }
611 
612 //---------------------------------------------------------
613 //   setFreewheel
614 //---------------------------------------------------------
615 
setFreewheel(bool val)616 void Audio::setFreewheel(bool val)
617       {
618       _freewheel = val;
619       }
620 
621 //---------------------------------------------------------
622 //   shutdown
623 //---------------------------------------------------------
624 
shutdown()625 void Audio::shutdown()
626       {
627       _running = false;
628       fprintf(stderr, "Audio::shutdown()\n");
629       write(sigFd, "S", 1);
630       }
631 
632 //---------------------------------------------------------
633 //   process
634 //    process one audio buffer at position "_pos "
635 //    of size "frames"
636 //---------------------------------------------------------
637 
process(unsigned frames)638 void Audio::process(unsigned frames)
639       {
640       _curCycleFrames = frames;
641       if (!MusEGlobal::checkAudioDevice()) return;
642       if (msg) {
643             processMsg(msg);
644             int sn = msg->serialNo;
645             msg    = 0;    // don't process again
646             int rv = write(fromThreadFdw, &sn, sizeof(int));
647             if (rv != sizeof(int)) {
648                   fprintf(stderr, "audio: write(%d) pipe failed: %s\n",
649                      fromThreadFdw, strerror(errno));
650                   }
651             }
652 
653       OutputList* ol = MusEGlobal::song->outputs();
654       if (idle) {
655             // deliver no audio
656             for (iAudioOutput i = ol->begin(); i != ol->end(); ++i)
657                   (*i)->silence(frames);
658             return;
659             }
660 
661       //
662       // resync with audio interface
663       //
664       syncFrame   = MusEGlobal::audioDevice->framesAtCycleStart();
665       syncTimeUS  = curTimeUS();
666 
667       int jackState = MusEGlobal::audioDevice->getState();
668 
669       //DEBUG_MIDI_TIMING(stderr, "Audio::process Current state:%s jackState:%s sync frame:%u pos frame:%u current transport frame:%u\n",
670       //        audioStates[state], audioStates[jackState], syncFrame, _pos.frame(), MusEGlobal::audioDevice->curTransportFrame());
671 
672       if ((state == START_PLAY || state == PRECOUNT) && jackState == PLAY) {
673             _loopCount = 0;
674             MusEGlobal::song->reenableTouchedControllers();
675             startRolling();
676 
677 // REMOVE Tim. latency. Removed. This is way too late to start freewheel mode.
678 // It will be a cycle or two before it even takes effect.
679 // So we do this in MusE::bounceToFile() and MusE::bounceToTrack(), BEFORE the transport is started.
680 //             if (_bounce)
681 //                   write(sigFd, "f", 1);
682             }
683       else if (state == LOOP2 && jackState == PLAY) {
684             ++_loopCount;                  // Number of times we have looped so far
685             Pos newPos(_loopFrame, false);
686             seek(newPos);
687             startRolling();
688             }
689       else if ((isPlaying() || state == PRECOUNT) && jackState == STOP) {
690             stopRolling();
691             }
692       else if (state == START_PLAY && jackState == STOP) {
693             abortRolling();
694             }
695       else if (state == STOP && jackState == PLAY) {
696             _loopCount = 0;
697             MusEGlobal::song->reenableTouchedControllers();
698             startRolling();
699             }
700       else if (state == LOOP1 && jackState == PLAY)
701             ;     // treat as play
702       else if (state == LOOP2 && jackState == START_PLAY) {
703             ;     // sync cycle
704             }
705       else if (state == PRECOUNT && jackState == START_PLAY) {
706             ;     // sync cycle
707             }
708       else if (state != jackState)
709             fprintf(stderr, "JACK: state transition %s -> %s ?\n",
710                audioStates[state], audioStates[jackState]);
711 
712       // fprintf(stderr, "p %s %s %d\n", audioStates[jackState], audioStates[state], _pos.frame());
713 
714       //
715       // clear aux send buffers
716       //
717       AuxList* al = MusEGlobal::song->auxs();
718       for (unsigned i = 0; i < al->size(); ++i) {
719             AudioAux* a = (AudioAux*)((*al)[i]);
720             float** dst = a->sendBuffer();
721             for (int ch = 0; ch < a->channels(); ++ch)
722                   memset(dst[ch], 0, sizeof(float) * MusEGlobal::segmentSize);
723             }
724 
725       for (iAudioOutput i = ol->begin(); i != ol->end(); ++i)
726             (*i)->processInit(frames);
727       int samplePos = _pos.frame();
728       int offset    = 0;      // buffer offset in audio buffers
729 #ifdef _JACK_TIMEBASE_DRIVES_MIDI_
730       bool use_jack_timebase = false;
731 #endif
732 
733       for(iMidiDevice id = MusEGlobal::midiDevices.begin(); id != MusEGlobal::midiDevices.end(); ++id)
734       {
735         MidiDevice* md = (*id);
736         const int port = md->midiPort();
737 
738         // Gather midi input from devices that need collecting, such as Jack midi.
739         md->collectMidiEvents();
740 
741         // Process the selected device's external clock history fifo ring buffer.
742         // Quickly transfer the items to a list for easier processing later.
743         // It is possible for the timestamps to be out of order. Deal with it.
744         // Sort all the timestamps. Do not miss a clock, better that it is at least
745         //  included in the count.
746         if(port >= 0 && port < MusECore::MIDI_PORTS && port == MusEGlobal::config.curMidiSyncInPort)
747         {
748           // False = don't use the size snapshot.
749           const int clk_fifo_sz = md->extClockHistory()->getSize(false);
750           if(clk_fifo_sz != 0)
751           {
752             for(int i = 0; i < clk_fifo_sz; ++i)
753             {
754               if(_extClockHistorySize >= _extClockHistoryCapacity)
755               {
756                 fprintf(stderr, "Audio::process: _extClockHistory overrun!\n");
757                 break;
758               }
759               _extClockHistory[_extClockHistorySize] = md->extClockHistory()->get();
760               ++_extClockHistorySize;
761             }
762           }
763         }
764         else
765           // Otherwise flush and discard the device's unused ring buffer data.
766           md->extClockHistory()->clearRead();
767       }
768 
769       //if(MusEGlobal::extSyncFlag && (MusEGlobal::midiSyncContainer.isRunning() || isPlaying()))
770       //  fprintf(stderr, "extSyncFlag:%d  externalPlayState:%d isPlaying:%d\n",
771       //    MusEGlobal::extSyncFlag, MusEGlobal::midiSyncContainer.externalPlayState(), isPlaying());
772 
773       if (isPlaying()) {
774             if (!freewheel())
775                   MusEGlobal::audioPrefetch->msgTick(isRecording(), true);
776 
777             if (bounce() && _pos >= MusEGlobal::song->rPos()) {
778                   // Need to let the resulting stopRolling take care of resetting bounce.
779                   //_bounceState = BounceOff;
780                   // This is safe in both Jack 1 and 2.
781                   MusEGlobal::audioDevice->stopTransport();
782                   return;
783                   }
784 
785 #ifdef _JACK_TIMEBASE_DRIVES_MIDI_
786             unsigned curr_jt_tick, next_jt_ticks;
787             use_jack_timebase =
788                 MusEGlobal::audioDevice->deviceType() == AudioDevice::JACK_AUDIO &&
789                 !MusEGlobal::config.timebaseMaster &&
790                 !MusEGlobal::tempomap.masterFlag() &&
791                 !MusEGlobal::extSyncFlag &&
792                 static_cast<MusECore::JackAudioDevice*>(MusEGlobal::audioDevice)->timebaseQuery(
793                   frames, NULL, NULL, NULL, &curr_jt_tick, &next_jt_ticks);
794             // NOTE: I would rather trust the reported current tick than rely solely on the stream of
795             // tempos to correctly advance to the next position (which did actually test OK anyway).
796             if(use_jack_timebase)
797               curTickPos = curr_jt_tick;
798 #endif
799 
800             //
801             //  check for end of song
802             //
803             if ((curTickPos >= MusEGlobal::song->len())
804                && !(MusEGlobal::song->record()
805                 || bounce()
806                 || MusEGlobal::song->loop())) {
807 
808                   if(MusEGlobal::debugMsg)
809                     fprintf(stderr, "Audio::process curTickPos >= MusEGlobal::song->len\n");
810 
811                   MusEGlobal::audioDevice->stopTransport();
812                   return;
813                   }
814 
815             //
816             //  check for loop end
817             //
818             if (state == PLAY && MusEGlobal::song->loop() && !bounce() && !MusEGlobal::extSyncFlag) {
819                   const Pos& loop = MusEGlobal::song->rPos();
820                   // The extra 'frames' worth is because we are calling the relocation from here within the process routine,
821                   //  so there will be a one cycle (extra) delay before the next sync call (sync is called just before process).
822                   unsigned n = loop.frame() - samplePos - MusEGlobal::audioDevice->transportRelocateOrPlayDelay() - frames;
823                   if (n < frames) {
824                         // loop end in current cycle
825                         unsigned lpos = MusEGlobal::song->lPos().frame();
826                         // adjust loop start so we get exact loop len
827                         if (n > lpos)
828                               n = 0;
829                         state = LOOP1;
830                         _loopFrame = lpos - n;
831                         Pos lp(_loopFrame, false);
832                         // Seek the transport. Note that temporary clearing of sustain
833                         //  controllers is done by the seek handlers and then startRolling().
834                         MusEGlobal::audioDevice->seekTransport(lp);
835                         }
836                   }
837 
838             if(MusEGlobal::extSyncFlag)        // p3.3.25
839             {
840               // Advance the tick position by the number of clock events times the division.
841               const int div = MusEGlobal::config.division / 24;
842               int tcks = 0;
843               for(int i = 0; i < _extClockHistorySize; ++i)
844               {
845                 if(_extClockHistory[i].isPlaying())
846                   ++tcks;
847               }
848               nextTickPos = curTickPos + tcks * div;
849             }
850             else
851             {
852 
853 #ifdef _JACK_TIMEBASE_DRIVES_MIDI_
854               if(use_jack_timebase)
855                 // With jack timebase this might not be accurate -
856                 //  we are relying on the tempo to figure out the next tick.
857                 nextTickPos = curTickPos + next_jt_ticks;
858               else
859 #endif
860               {
861                 Pos ppp(_pos);
862                 ppp += frames;
863                 nextTickPos = ppp.tick();
864               }
865             }
866           }
867 
868       process1(samplePos, offset, frames);
869       for (iAudioOutput i = ol->begin(); i != ol->end(); ++i)
870       {
871             (*i)->processWrite();
872             // Special for audio outputs tracks: Now that processWrite() is
873             //  finished using 'buffer', apply output channel latency compensation
874             //  to the buffer so that the correct signals appear at the final destination.
875             // Note that 'buffer' should be in phase by now.
876             (*i)->applyOutputLatencyComp(frames);
877       }
878 
879 // REMOVE Tim. latency. Changed. Hm, doesn't work. Position takes a long time to start moving.
880       if (isPlaying()) {
881       //if(isPlaying() || (MusEGlobal::extSyncFlag && MusEGlobal::midiSyncContainer.isPlaying())) {
882             _pos += frames;
883             // With jack timebase this might not be accurate if we
884             //  set curTickPos (above) from the reported current tick.
885             curTickPos = nextTickPos;
886             }
887 
888       // If external sync has started but the transport has not started yet,
889       //  don't reset the clock history yet, just let it pile up until the transport starts.
890       // It's because curTickPos does not advance yet until transport is running, so we
891       //  can't rely on curTickPos as a base just yet...
892       if(!MusEGlobal::extSyncFlag || !MusEGlobal::midiSyncContainer.isPlaying() || isPlaying())
893         _extClockHistorySize = 0;
894       }
895 
896 //---------------------------------------------------------
897 //   process1
898 //---------------------------------------------------------
899 
process1(unsigned samplePos,unsigned offset,unsigned frames)900 void Audio::process1(unsigned samplePos, unsigned offset, unsigned frames)
901       {
902       //
903       // process not connected tracks
904       // to animate meter display
905       //
906       const TrackList& tl = *MusEGlobal::song->tracks();
907       const TrackList::size_type tl_sz = tl.size();
908       const AuxList& aux_tl = *MusEGlobal::song->auxs();
909       const AuxList::size_type aux_tl_sz = aux_tl.size();
910       const OutputList& out_tl = *MusEGlobal::song->outputs();
911       const OutputList::size_type out_tl_sz = out_tl.size();
912       const MidiDeviceList& mdl = MusEGlobal::midiDevices;
913       Track* track;
914       AudioTrack* atrack;
915       int channels;
916       bool want_record_side;
917 
918       MusECore::MetronomeSettings* metro_settings =
919         MusEGlobal::metroUseSongSettings ? &MusEGlobal::metroSongSettings : &MusEGlobal::metroGlobalSettings;
920 
921       // This includes synthesizers.
922       for(TrackList::size_type it = 0; it < tl_sz; ++it)
923       {
924         track = tl[it];
925 
926         // For track types, synths etc. which need some kind of non-audio
927         //  (but possibly audio-affecting) processing always, even if their output path
928         //  is ultimately unconnected.
929         // Example: A fluidsynth instance whose output path ultimately led to nowhere
930         //  would not allow us to load a font. Since process() was driven by audio output,
931         //  in this case there was nothing driving the process() function which responds to
932         //  such gui commands. So I separated the events processing from process(), into this.
933         // It should be used for things like midi events, gui events etc. - things which need to
934         //  be done BEFORE all the AudioOutput::process() are called below. That does NOT include
935         //  audio processing, because THAT is done at the very end of this routine.
936         // This will also reset the track's processed flag.         Tim.
937         track->preProcessAlways();
938 
939         // Reset some latency info to prepare for (re)computation.
940         track->prepareLatencyScan();
941       }
942 
943       // This includes synthesizers.
944       for(ciMidiDevice imd = mdl.cbegin(); imd != mdl.cend(); ++imd)
945       {
946         MidiDevice* md = *imd;
947         // Device not in use?
948         if(md->midiPort() < 0 || md->midiPort() >= MusECore::MIDI_PORTS)
949           continue;
950 
951         // Reset some latency info to prepare for (re)computation.
952         md->prepareLatencyScan();
953       }
954 
955       // Pre-process the metronome.
956       metronome->preProcessAlways();
957       // Reset some latency info to prepare for (re)computation.
958       static_cast<AudioTrack*>(metronome)->prepareLatencyScan();
959       static_cast<MidiDevice*>(metronome)->prepareLatencyScan();
960 
961       //---------------------------------------------
962       // BEGIN Latency correction/compensation processing
963       // TODO: Instead of doing this blindly every cycle, do it only when
964       //        a latency controller changes or a connection is made etc,
965       //        ie only when something changes.
966       //---------------------------------------------
967 
968       if(MusEGlobal::config.enableLatencyCorrection)
969       {
970         float song_worst_latency = 0.0f;
971 
972         //---------------------------------------------
973         // PASS 1: Find any dominant branches:
974         //---------------------------------------------
975 
976         for(TrackList::size_type it = 0; it < tl_sz; ++it)
977         {
978           track = tl[it];
979 
980           // If the track is for example a Wave Track, we must consider up to two contributing paths,
981           //  the output (playback) side and the input (record) side which can pass through via monitoring.
982           want_record_side = track->isMidiTrack() || track->type() == Track::WAVE;
983 
984           //---------------------------------------------
985           // We are looking for the end points of branches.
986           // This includes Audio Outputs, and open-ended branches
987           //  that go nowhere or are effectively disconnected from
988           //  their destination(s).
989           // This caches its result in the track's _latencyInfo structure
990           //  so it can be used faster in the correction pass or final pass.
991           //---------------------------------------------
992 
993           // Examine any recording path, if desired.
994           if(want_record_side && track->isLatencyInputTerminal())
995             track->getDominanceInfo(true);
996 
997           // Examine any playback path.
998           if(track->isLatencyOutputTerminal())
999             track->getDominanceInfo(false);
1000         }
1001 
1002   #if 1
1003         // This includes synthesizers.
1004         for(ciMidiDevice imd = mdl.cbegin(); imd != mdl.cend(); ++imd)
1005         {
1006           MidiDevice* md = *imd;
1007           // Device not in use?
1008           if(md->midiPort() < 0 || md->midiPort() >= MusECore::MIDI_PORTS)
1009             continue;
1010 
1011           // Examine any playback path on capture devices.
1012           if(md->isLatencyOutputTerminalMidi(true /*capture*/))
1013             md->getDominanceInfoMidi(true /*capture*/, false);
1014 
1015           // Examine any playback path on playback devices.
1016           if(md->isLatencyOutputTerminalMidi(false /*playback*/))
1017             md->getDominanceInfoMidi(false /*playback*/, false);
1018         }
1019   #endif
1020 
1021         //---------------------------------------------
1022         // Throughout this latency code, we will examine the metronome
1023         //  enable/disable settings rather than the metronome on/off button(s),
1024         //  so that the metronome button(s) can be 'ready for action' when clicked,
1025         //  without affecting the sound.
1026         // Otherwise a glitch would occur every time the metronome is simply
1027         //  turned on or off via the gui toolbars, while latency is recomputed.
1028         //---------------------------------------------
1029 
1030         //if(MusEGlobal::song->click())
1031         if(metro_settings->audioClickFlag)
1032         {
1033           // Examine any playback path.
1034           if(metronome->isLatencyOutputTerminal())
1035             metronome->getDominanceInfo(false);
1036         }
1037         if(metro_settings->midiClickFlag)
1038         {
1039           // Examine any playback path.
1040           if(metronome->isLatencyOutputTerminalMidi(false /*playback*/))
1041             metronome->getDominanceInfoMidi(false /*playback*/, false);
1042         }
1043 
1044 
1045         //---------------------------------------------
1046         // PASS 2: Set correction values:
1047         //---------------------------------------------
1048 
1049         // Now that we know the worst case latency,
1050         //  set all the branch correction values.
1051         for(TrackList::size_type it = 0; it < tl_sz; ++it)
1052         {
1053           track = tl[it];
1054 
1055           // If the track is for example a Wave Track, we must consider up to two contributing paths,
1056           //  the output (playback) side and the input (record) side which can pass through via monitoring.
1057           want_record_side = track->isMidiTrack() || track->type() == Track::WAVE;
1058 
1059           // Set branch correction values, for any tracks which support it.
1060           // If this branch can dominate latency, ie. is fed from an Audio Input Track,
1061           //  then we cannot apply correction to the branch.
1062           // For example:
1063           //
1064           //  Input(512) -> Wave1(monitor on) -> Output(3072)
1065           //                                  -> Wave2
1066           //
1067           // Wave1 wants to set a correction of -3072 but it cannot because
1068           //  the input has 512 latency. Any wave1 playback material would be
1069           //  misaligned with the monitored input material.
1070           //
1071 
1072           // Examine any recording path, if desired.
1073           if(want_record_side && track->isLatencyInputTerminal())
1074           {
1075             const TrackLatencyInfo& li = track->getDominanceInfo(true);
1076             if(!li._canDominateOutputLatency)
1077               track->setCorrectionLatencyInfo(true, song_worst_latency);
1078           }
1079 
1080           // Examine any playback path.
1081           if(track->isLatencyOutputTerminal())
1082           {
1083             const TrackLatencyInfo& li = track->getDominanceInfo(false);
1084             if(!li._canDominateOutputLatency)
1085               track->setCorrectionLatencyInfo(false, song_worst_latency);
1086           }
1087         }
1088 
1089   #if 1
1090         // This includes synthesizers.
1091         for(ciMidiDevice imd = mdl.cbegin(); imd != mdl.cend(); ++imd)
1092         {
1093           MidiDevice* md = *imd;
1094           // Device not in use?
1095           if(md->midiPort() < 0 || md->midiPort() >= MusECore::MIDI_PORTS)
1096             continue;
1097 
1098           if(md->isLatencyOutputTerminalMidi(true /*capture*/))
1099           {
1100             // Grab the capture device's branch's dominance latency info.
1101             // This should already be cached from the dominance pass.
1102             const TrackLatencyInfo& li = md->getDominanceInfoMidi(true /*capture*/, false);
1103             if(!li._canDominateOutputLatency)
1104               md->setCorrectionLatencyInfoMidi(true /*capture*/, false, song_worst_latency);
1105           }
1106 
1107           if(md->isLatencyOutputTerminalMidi(false /*playback*/))
1108           {
1109             // Grab the playback device's branch's dominance latency info.
1110             // This should already be cached from the dominance pass.
1111             const TrackLatencyInfo& li = md->getDominanceInfoMidi(false /*playback*/, false);
1112             if(!li._canDominateOutputLatency)
1113               md->setCorrectionLatencyInfoMidi(false /*playback*/, false, song_worst_latency);
1114           }
1115         }
1116   #endif
1117 
1118         //if(MusEGlobal::song->click())
1119         if(metro_settings->audioClickFlag)
1120         {
1121           if(metronome->isLatencyOutputTerminal())
1122           {
1123             // Grab the branch's dominance latency info.
1124             // This should already be cached from the dominance pass.
1125             const TrackLatencyInfo& li = metronome->getDominanceInfo(false);
1126             if(!li._canDominateOutputLatency)
1127               metronome->setCorrectionLatencyInfo(false, song_worst_latency);
1128           }
1129         }
1130         if(metro_settings->midiClickFlag)
1131         {
1132           if(metronome->isLatencyOutputTerminalMidi(false /*playback*/))
1133           {
1134             // Grab the branch's dominance latency info.
1135             // This should already be cached from the dominance pass.
1136             const TrackLatencyInfo& li = metronome->getDominanceInfoMidi(false /*playback*/, false);
1137             if(!li._canDominateOutputLatency)
1138               metronome->setCorrectionLatencyInfoMidi(false /*playback*/, false, song_worst_latency);
1139           }
1140         }
1141 
1142 
1143         //---------------------------------------------
1144         // PASS 3: Set initial output latencies:
1145         //---------------------------------------------
1146 
1147         for(TrackList::size_type it = 0; it < tl_sz; ++it)
1148         {
1149           track = tl[it];
1150 
1151           // If the track is for example a Wave Track, we must consider up to two contributing paths,
1152           //  the output (playback) side and the input (record) side which can pass through via monitoring.
1153           want_record_side = track->isMidiTrack() || track->type() == Track::WAVE;
1154 
1155           //---------------------------------------------
1156           // We are looking for the end points of branches.
1157           // This includes Audio Outputs, and open-ended branches
1158           //  that go nowhere or are effectively disconnected from
1159           //  their destination(s).
1160           // This caches its result in the track's _latencyInfo structure
1161           //  in the _isLatencyOutputTerminal member so it can be used
1162           //  faster in the correction pass or final pass.
1163           //---------------------------------------------
1164 
1165           // Examine any recording path, if desired.
1166           if(want_record_side && track->isLatencyInputTerminal())
1167           {
1168             // Gather the branch's dominance latency info.
1169             const TrackLatencyInfo& li = track->getDominanceLatencyInfo(true);
1170 
1171             // If the branch can dominate, and this end-point allows it, and its latency value
1172             //  is greater than the current worst, overwrite the worst.
1173             if(track->canDominateEndPointLatency() &&
1174               li._canDominateInputLatency &&
1175               li._inputLatency > song_worst_latency)
1176                 song_worst_latency = li._inputLatency;
1177           }
1178 
1179           // Examine any playback path.
1180           if(track->isLatencyOutputTerminal())
1181           {
1182             // Gather the branch's dominance latency info.
1183             const TrackLatencyInfo& li = track->getDominanceLatencyInfo(false);
1184 
1185             // If the branch can dominate, and this end-point allows it, and its latency value
1186             //  is greater than the current worst, overwrite the worst.
1187             if(track->canDominateEndPointLatency() &&
1188               li._canDominateOutputLatency &&
1189               li._outputLatency > song_worst_latency)
1190                 song_worst_latency = li._outputLatency;
1191           }
1192         }
1193 
1194   #if 1
1195         // This includes synthesizers.
1196         for(ciMidiDevice imd = mdl.cbegin(); imd != mdl.cend(); ++imd)
1197         {
1198           MidiDevice* md = *imd;
1199           // Device not in use?
1200           if(md->midiPort() < 0 || md->midiPort() >= MusECore::MIDI_PORTS)
1201             continue;
1202 
1203           //---------------------------------------------
1204           // We are looking for the end points of branches.
1205           // This includes Audio Outputs, and open-ended branches
1206           //  that go nowhere or are effectively disconnected from
1207           //  their destination(s).
1208           // This caches its result in the track's _latencyInfo structure
1209           //  in the _isLatencyOutputTerminal member so it can be used
1210           //  faster in the correction pass or final pass.
1211           //---------------------------------------------
1212 
1213           // Examine any playback path on capture devices.
1214           if(md->isLatencyOutputTerminalMidi(true /*capture*/))
1215           {
1216             // Gather the branch's dominance latency info.
1217             const TrackLatencyInfo& li = md->getDominanceLatencyInfoMidi(true /*capture*/, false);
1218             // If the branch can dominate, and this end-point allows it, and its latency value
1219             //  is greater than the current worst, overwrite the worst.
1220             if(md->canDominateEndPointLatencyMidi(true /*capture*/) &&
1221               li._canDominateOutputLatency &&
1222               li._outputLatency > song_worst_latency)
1223                 song_worst_latency = li._outputLatency;
1224           }
1225 
1226           // Examine any playback path on playback devices.
1227           if(md->isLatencyOutputTerminalMidi(false /*playback*/))
1228           {
1229             // Gather the branch's dominance latency info.
1230             const TrackLatencyInfo& li = md->getDominanceLatencyInfoMidi(false /*playback*/, false);
1231             // If the branch can dominate, and this end-point allows it, and its latency value
1232             //  is greater than the current worst, overwrite the worst.
1233             if(md->canDominateEndPointLatencyMidi(false /*playback*/) &&
1234               li._canDominateOutputLatency &&
1235               li._outputLatency > song_worst_latency)
1236                 song_worst_latency = li._outputLatency;
1237           }
1238         }
1239   #endif
1240 
1241         //if(MusEGlobal::song->click())
1242         if(metro_settings->audioClickFlag)
1243         {
1244           // Examine any playback path.
1245           if(metronome->isLatencyOutputTerminal())
1246           {
1247             // Gather the branch's dominance latency info.
1248             const TrackLatencyInfo& li = metronome->getDominanceLatencyInfo(false);
1249 
1250             // If the branch can dominate, and this end-point allows it, and its latency value
1251             //  is greater than the current worst, overwrite the worst.
1252             if(metronome->canDominateEndPointLatency() &&
1253               li._canDominateOutputLatency &&
1254               li._outputLatency > song_worst_latency)
1255                 song_worst_latency = li._outputLatency;
1256           }
1257         }
1258         if(metro_settings->midiClickFlag)
1259         {
1260           // Examine any playback path.
1261           if(metronome->isLatencyOutputTerminalMidi(false /*playback*/))
1262           {
1263             // Gather the branch's dominance latency info.
1264             const TrackLatencyInfo& li = metronome->getDominanceLatencyInfoMidi(false /*playback*/, false);
1265 
1266             // If the branch can dominate, and this end-point allows it, and its latency value
1267             //  is greater than the current worst, overwrite the worst.
1268             if(metronome->canDominateEndPointLatencyMidi(false /*playback*/) &&
1269               li._canDominateOutputLatency &&
1270               li._outputLatency > song_worst_latency)
1271                 song_worst_latency = li._outputLatency;
1272           }
1273         }
1274 
1275         //----------------------------------------------------------
1276         // PASS 4: Gather final latency values and set compensators:
1277         //----------------------------------------------------------
1278 
1279         // Now that all branch correction values have been set,
1280         //  gather all final latency info.
1281         for(TrackList::size_type it = 0; it < tl_sz; ++it)
1282         {
1283           track = tl[it];
1284 
1285           // If the track is for example a Wave Track, we must consider up to two contributing paths,
1286           //  the output (playback) side and the input (record) side which can pass through via monitoring.
1287           want_record_side = track->isMidiTrack() || track->type() == Track::WAVE;
1288 
1289           // Examine any recording path, if desired.
1290           // We are looking for the end points of branches.
1291           if(want_record_side && track->isLatencyInputTerminal())
1292           {
1293             // Gather the branch's final latency info, which also sets the
1294             //  latency compensators.
1295             track->getLatencyInfo(true);
1296             // Set this end point's latency compensator write offset.
1297             track->setLatencyCompWriteOffset(song_worst_latency);
1298           }
1299 
1300           // Examine any playback path.
1301           // We are looking for the end points of branches.
1302           if(track->isLatencyOutputTerminal())
1303           {
1304             // Gather the branch's final latency info, which also sets the
1305             //  latency compensators.
1306             track->getLatencyInfo(false);
1307             // Set this end point's latency compensator write offset.
1308             track->setLatencyCompWriteOffset(song_worst_latency);
1309           }
1310         }
1311 
1312   #if 1
1313         // This includes synthesizers.
1314         for(ciMidiDevice imd = mdl.cbegin(); imd != mdl.cend(); ++imd)
1315         {
1316           MidiDevice* md = *imd;
1317           // Device not in use?
1318           if(md->midiPort() < 0 || md->midiPort() >= MusECore::MIDI_PORTS)
1319             continue;
1320 
1321           // We are looking for the end points of branches.
1322           if(md->isLatencyOutputTerminalMidi(true /*capture*/))
1323           {
1324             // Examine any playback path of the capture device.
1325             // Gather the branch's final latency info, which also sets the
1326             //  latency compensators.
1327             md->getLatencyInfoMidi(true /*capture*/, false);
1328             // Set this end point's latency compensator write offset.
1329             md->setLatencyCompWriteOffsetMidi(song_worst_latency, true /*capture*/);
1330           }
1331 
1332           // We are looking for the end points of branches.
1333           if(md->isLatencyOutputTerminalMidi(false /*playback*/))
1334           {
1335             // Examine any playback path of the playback device.
1336             // Gather the branch's final latency info, which also sets the
1337             //  latency compensators.
1338             md->getLatencyInfoMidi(false /*playback*/, false);
1339             // Set this end point's latency compensator write offset.
1340             md->setLatencyCompWriteOffsetMidi(song_worst_latency, false /*playback*/);
1341           }
1342         }
1343   #endif
1344 
1345         //if(MusEGlobal::song->click())
1346         if(metro_settings->audioClickFlag)
1347         {
1348           // We are looking for the end points of branches.
1349           if(metronome->isLatencyOutputTerminal())
1350           {
1351             // Gather the branch's final latency info, which also sets the
1352             //  latency compensators.
1353             metronome->getLatencyInfo(false);
1354             // Set this end point's latency compensator write offset.
1355             metronome->setLatencyCompWriteOffset(song_worst_latency);
1356           }
1357         }
1358         if(metro_settings->midiClickFlag)
1359         {
1360           // We are looking for the end points of branches.
1361           if(metronome->isLatencyOutputTerminalMidi(false /*playback*/))
1362           {
1363             // Gather the branch's final latency info, which also sets the
1364             //  latency compensators.
1365             metronome->getLatencyInfoMidi(false /*playback*/, false);
1366             // Set this end point's latency compensator write offset.
1367             metronome->setLatencyCompWriteOffsetMidi(song_worst_latency, false /*playback*/);
1368           }
1369         }
1370       }
1371       //---------------------------------------------
1372       // END Latency correction/compensation processing
1373       //---------------------------------------------
1374 
1375       //---------------------------------------------
1376       // Midi processing
1377       //---------------------------------------------
1378 
1379       processMidi(frames);
1380 
1381       //---------------------------------------------
1382       // Audio processing
1383       //---------------------------------------------
1384 
1385       // Process Aux tracks first.
1386       for(AuxList::size_type it = 0; it < aux_tl_sz; ++it)
1387       {
1388         atrack = static_cast<AudioTrack*>(aux_tl[it]);
1389         if(!atrack->processed())
1390         {
1391           channels = atrack->channels();
1392           // Just a dummy buffer.
1393           float* buffer[channels];
1394           float data[frames * channels];
1395           for (int i = 0; i < channels; ++i)
1396                 buffer[i] = data + i * frames;
1397 
1398           atrack->copyData(samplePos, -1, channels, channels, -1, -1, frames, buffer);
1399         }
1400       }
1401 
1402       for(OutputList::size_type it = 0; it < out_tl_sz; ++it)
1403         static_cast<AudioOutput*>(out_tl[it])->process(samplePos, offset, frames);
1404 
1405       // Were ANY tracks unprocessed as a result of processing all the AudioOutputs, above?
1406       // Not just unconnected ones, as previously done, but ones whose output path ultimately leads nowhere.
1407       // Those tracks were missed, until this fix.
1408       // Do them now. This will animate meters, and 'quietly' process some audio which needs to be done -
1409       //  for example synths really need to be processed, 'quietly' or not, otherwise the next time processing
1410       //  is 'turned on', if there was a backlog of events while it was off, then they all happen at once.  Tim.
1411       for(TrackList::size_type it = 0; it < tl_sz; ++it)
1412       {
1413         atrack = static_cast<AudioTrack*>(tl[it]);
1414         if(atrack->isMidiTrack())
1415           continue;
1416         if(!atrack->processed() && (atrack->type() != Track::AUDIO_OUTPUT))
1417         {
1418           channels = atrack->channels();
1419           // Just a dummy buffer.
1420           float* buffer[channels];
1421           float data[frames * channels];
1422           for (int i = 0; i < channels; ++i)
1423                 buffer[i] = data + i * frames;
1424 
1425           atrack->copyData(samplePos, -1, channels, channels, -1, -1, frames, buffer);
1426         }
1427       }
1428     }
1429 
1430 //---------------------------------------------------------
1431 //   processMsg
1432 //---------------------------------------------------------
1433 
processMsg(AudioMsg * msg)1434 void Audio::processMsg(AudioMsg* msg)
1435       {
1436       switch(msg->id) {
1437             case AUDIO_ROUTEADD:
1438                   addRoute(msg->sroute, msg->droute);
1439                   break;
1440             case AUDIO_ROUTEREMOVE:
1441                   removeRoute(msg->sroute, msg->droute);
1442                   break;
1443             case AUDIO_REMOVEROUTES:
1444                   removeAllRoutes(msg->sroute, msg->droute);
1445                   break;
1446             case SEQM_SET_AUX:
1447                   msg->snode->setAuxSend(msg->ival, msg->dval);
1448                   break;
1449             case AUDIO_SET_PREFADER:
1450                   msg->snode->setPrefader(msg->ival);
1451                   break;
1452             case AUDIO_SET_CHANNELS:
1453                   msg->snode->setChannels(msg->ival);
1454                   break;
1455             case AUDIO_ADDPLUGIN:
1456                   msg->snode->addPlugin(msg->plugin, msg->ival);
1457                   break;
1458             case AUDIO_SWAP_CONTROLLER_IDX:
1459                   msg->snode->swapControllerIDX(msg->a, msg->b);
1460                   break;
1461             case AUDIO_CLEAR_CONTROLLER_EVENTS:
1462                   msg->snode->clearControllerEvents(msg->ival);
1463                   break;
1464             case AUDIO_SEEK_PREV_AC_EVENT:
1465                   msg->snode->seekPrevACEvent(msg->ival);
1466                   break;
1467             case AUDIO_SEEK_NEXT_AC_EVENT:
1468                   msg->snode->seekNextACEvent(msg->ival);
1469                   break;
1470             case AUDIO_ERASE_AC_EVENT:
1471                   msg->snode->eraseACEvent(msg->ival, msg->a);
1472                   break;
1473             case AUDIO_ERASE_RANGE_AC_EVENTS:
1474                   msg->snode->eraseRangeACEvents(msg->ival, msg->a, msg->b);
1475                   break;
1476             case AUDIO_ADD_AC_EVENT:
1477                   msg->snode->addACEvent(msg->ival, msg->a, msg->dval);
1478                   break;
1479             case AUDIO_CHANGE_AC_EVENT:
1480                   msg->snode->changeACEvent(msg->ival, msg->a, msg->b, msg->dval);
1481                   break;
1482 
1483             case AUDIO_SET_SEND_METRONOME:
1484                   msg->snode->setSendMetronome((bool)msg->ival);
1485                   break;
1486 
1487             case AUDIO_START_MIDI_LEARN:
1488                   // Reset the values. The engine will fill these from driver events.
1489                   MusEGlobal::midiLearnPort = -1;
1490                   MusEGlobal::midiLearnChan = -1;
1491                   MusEGlobal::midiLearnCtrl = -1;
1492                   break;
1493 
1494             case SEQM_RESET_DEVICES:
1495                   for (int i = 0; i < MusECore::MIDI_PORTS; ++i)
1496                   {
1497                     if(MusEGlobal::midiPorts[i].device())
1498                       MusEGlobal::midiPorts[i].instrument()->reset(i);
1499                   }
1500                   break;
1501             case SEQM_INIT_DEVICES:
1502                   initDevices(msg->a);
1503                   break;
1504             case SEQM_MIDI_LOCAL_OFF:
1505                   sendLocalOff();
1506                   break;
1507             case SEQM_PANIC:
1508                   panic();
1509                   break;
1510             case SEQM_PLAY_MIDI_EVENT:
1511                   {
1512                   const MidiPlayEvent ev = *((MidiPlayEvent*)(msg->p1));
1513                   const int port = ev.port();
1514                   if(port < 0 || port >= MusECore::MIDI_PORTS)
1515                     break;
1516 
1517                   // This is the audio thread. Just set directly.
1518                   MusEGlobal::midiPorts[port].setHwCtrlState(ev);
1519                   // Send to the device.
1520                   if(MidiDevice* md = MusEGlobal::midiPorts[port].device())
1521                     md->putEvent(ev, MidiDevice::NotLate);
1522                   // Record??
1523                   }
1524                   break;
1525             case SEQM_SET_HW_CTRL_STATE:
1526                   {
1527                   MidiPort* port = (MidiPort*)(msg->p1);
1528                   port->setHwCtrlState(msg->a, msg->b, msg->c);
1529                   }
1530                   break;
1531             case SEQM_SET_HW_CTRL_STATES:
1532                   {
1533                   MidiPort* port = (MidiPort*)(msg->p1);
1534                   port->setHwCtrlStates(msg->a, msg->b, msg->c, msg->ival);
1535                   }
1536                   break;
1537 
1538             case SEQM_SET_TRACK_AUTO_TYPE:
1539                   msg->track->setAutomationType(AutomationType(msg->ival));
1540                   break;
1541 
1542             case SEQM_IDLE:
1543                   idle = msg->a;
1544                   if(MusEGlobal::midiSeq)
1545                     MusEGlobal::midiSeq->sendMsg(msg);
1546                   break;
1547 
1548             case AUDIO_WAIT:
1549                   // Do nothing.
1550                   break;
1551 
1552             default:
1553                   MusEGlobal::song->processMsg(msg);
1554                   break;
1555             }
1556       }
1557 
1558 //---------------------------------------------------------
1559 //   seek
1560 //    - called before start play
1561 //    - initiated from gui
1562 //    To be called from audio thread only.
1563 //---------------------------------------------------------
1564 
seek(const Pos & p)1565 void Audio::seek(const Pos& p)
1566       {
1567       // The transport (and user) must NOT be allowed to influence the position during bounce mode.
1568       if(!bounce())
1569       {
1570         // This is expected and required sometimes, for example to
1571         //  sync the prefetch system to a position we are ALREADY at.
1572         // But being fairly costly, not too frequently. So we warn just in case.
1573         if (_pos == p) {
1574               if(MusEGlobal::debugMsg)
1575                 fprintf(stderr, "Audio::seek already at frame:%u\n", p.frame());
1576               }
1577 
1578         if (MusEGlobal::heavyDebugMsg)
1579           fprintf(stderr, "Audio::seek frame:%d\n", p.frame());
1580 
1581         _pos        = p;
1582         if (!MusEGlobal::checkAudioDevice()) return;
1583         syncFrame   = MusEGlobal::audioDevice->framesAtCycleStart();
1584 
1585   #ifdef _JACK_TIMEBASE_DRIVES_MIDI_
1586         unsigned curr_jt_tick;
1587         if(MusEGlobal::audioDevice->deviceType() == AudioDevice::JACK_AUDIO &&
1588           !MusEGlobal::config.timebaseMaster &&
1589           !MusEGlobal::tempomap.masterFlag() &&
1590           !MusEGlobal::extSyncFlag &&
1591           static_cast<MusECore::JackAudioDevice*>(MusEGlobal::audioDevice)->timebaseQuery(
1592               MusEGlobal::segmentSize, NULL, NULL, NULL, &curr_jt_tick, NULL))
1593           curTickPos = curr_jt_tick;
1594         else
1595   #endif
1596         curTickPos  = _pos.tick();
1597 
1598         // Now that curTickPos is set, set the correct initial metronome midiClick.
1599         updateMidiClick();
1600 
1601         //
1602         // Handle stuck notes and set controllers for new position:
1603         //
1604 
1605         seekMidi();
1606 
1607         if (state != LOOP2 && !freewheel())
1608         {
1609           // We need to force prefetch to update, to ensure the most recent data.
1610           // Things can happen to a part before play is pressed - such as part muting,
1611           //  part moving etc. Without a force, the wrong data was being played.  Tim 08/17/08
1612           // This does not wait.
1613           // FIXME: Actually it WILL until the the message is sent, but which is usually right away.
1614           MusEGlobal::audioPrefetch->msgSeek(_pos.frame(), true);
1615         }
1616 
1617         write(sigFd, "G", 1);   // signal seek to gui
1618       }
1619       }
1620 
1621 //---------------------------------------------------------
1622 //   writeTick
1623 //    called from audio prefetch thread context
1624 //    write another buffer to soundfile
1625 //---------------------------------------------------------
1626 
writeTick()1627 void Audio::writeTick()
1628       {
1629       AudioOutput* ao = MusEGlobal::song->bounceOutput;
1630       if(ao && MusEGlobal::song->outputs()->find(ao) != MusEGlobal::song->outputs()->end())
1631       {
1632         if(ao->recordFlag())
1633           ao->record();
1634       }
1635       WaveTrackList* tl = MusEGlobal::song->waves();
1636       for (iWaveTrack t = tl->begin(); t != tl->end(); ++t) {
1637             WaveTrack* track = *t;
1638             if (track->recordFlag())
1639                   track->record();
1640             }
1641       }
1642 
1643 //---------------------------------------------------------
1644 //   startRolling
1645 //---------------------------------------------------------
1646 
startRolling()1647 void Audio::startRolling()
1648       {
1649       if (MusEGlobal::debugMsg)
1650         fprintf(stderr, "startRolling - loopCount=%d, _pos=%d\n", _loopCount, _pos.tick());
1651 
1652       // The transport (and user) must NOT be allowed
1653       //  to influence the position during bounce mode.
1654       if(_bounceState != BounceOn)
1655       {
1656         if(_loopCount == 0) {
1657           startRecordPos = _pos;
1658           startExternalRecTick = curTickPos;
1659         }
1660         if (MusEGlobal::song->record()) {
1661               recording      = true;
1662               WaveTrackList* tracks = MusEGlobal::song->waves();
1663               for (iWaveTrack i = tracks->begin(); i != tracks->end(); ++i) {
1664                           WaveTrack* track = *i;
1665                           track->resetMeter();
1666                           // If we are in freewheel mode, directly seek the wave files.
1667                           // Since the audio converter support was added, the wave files MUST be allowed to
1668                           //  progress naturally during play, pulled in a stream manner by the particular converter.
1669                           // Therefore we no longer seek with EVERY data fetch, so do it here, directly.
1670                           // We CANNOT do this in Audio::seek in response to a transport relocation, because
1671                           //  the transport (and user) must not be allowed to influence the position during freewheel.
1672                           // Note that when freewheeling, prefetch is essentially UNUSED. We can ignore it here.
1673                           if(freewheel() /*&& bounce()*/)
1674                           {
1675                             // Might as well do this. Not costly. Prepare for next 'real' non-freewheel seek?
1676                             track->clearPrefetchFifo();
1677                             track->setPrefetchWritePos(_pos.frame());
1678 
1679                             track->seekData(_pos.frame());
1680                           }
1681                     }
1682               }
1683       }
1684 
1685       state = PLAY;
1686 
1687       if(_bounceState != BounceOn)
1688       {
1689         write(sigFd, "1", 1);   // Play
1690 
1691         // Don't send if external sync is on. The master, and our sync routing system will take care of that.
1692         if(!MusEGlobal::extSyncFlag)
1693         {
1694           for(int port = 0; port < MusECore::MIDI_PORTS; ++port)
1695           {
1696             MidiPort* mp = &MusEGlobal::midiPorts[port];
1697             MidiDevice* dev = mp->device();
1698             if(!dev)
1699               continue;
1700 
1701             MidiSyncInfo& si = mp->syncInfo();
1702 
1703             if(si.MMCOut())
1704               mp->sendMMCDeferredPlay();
1705 
1706             if(si.MRTOut())
1707             {
1708               if(curTickPos)
1709                 mp->sendContinue();
1710               else
1711                 mp->sendStart();
1712             }
1713           }
1714         }
1715 
1716         // Set the correct initial metronome midiClick.
1717         // Theoretically shouldn't have to do this here, in seek() should be enough.
1718         // But just in case, no harm.
1719         updateMidiClick();
1720 
1721         // re-enable sustain
1722         for (int i = 0; i < MusECore::MIDI_PORTS; ++i) {
1723             MidiPort* mp = &MusEGlobal::midiPorts[i];
1724             if(!mp->device())
1725               continue;
1726             for (int ch = 0; ch < MusECore::MUSE_MIDI_CHANNELS; ++ch) {
1727                 if (mp->hwCtrlState(ch, CTRL_SUSTAIN) == 127) {
1728                           const MidiPlayEvent ev(0, i, ch, ME_CONTROLLER, CTRL_SUSTAIN, 127);
1729                           mp->device()->putEvent(ev, MidiDevice::NotLate);
1730                     }
1731                 }
1732             }
1733       }
1734 
1735       if(_bounceState == BounceStart)
1736         _bounceState = BounceOn;
1737      }
1738 
1739 //---------------------------------------------------------
1740 //   abortRolling
1741 //---------------------------------------------------------
1742 
abortRolling()1743 void Audio::abortRolling()
1744 {
1745       if (MusEGlobal::debugMsg)
1746         fprintf(stderr, "Audio::abortRolling state %s\n", audioStates[state]);
1747 
1748       state = STOP;
1749 
1750       //
1751       // Clear midi device notes and stop stuck notes:
1752       //
1753 
1754       // Clear the special sync play state (separate from audio play state).
1755       MusEGlobal::midiSyncContainer.setExternalPlayState(ExtMidiClock::ExternStopped); // Not playing.   Moved here from MidiSeq::processStop()
1756 
1757       // Stop the ALSA devices...
1758       if(MusEGlobal::midiSeq)
1759         MusEGlobal::midiSeq->msgStop();  // FIXME: This waits!
1760 
1761       // Stop any non-ALSA devices...
1762       for(iMidiDevice id = MusEGlobal::midiDevices.begin(); id != MusEGlobal::midiDevices.end(); ++id)
1763       {
1764         MidiDevice* md = *id;
1765         const MidiDevice::MidiDeviceType type = md->deviceType();
1766         // Only for non-ALSA devices.
1767         switch(type)
1768         {
1769           case MidiDevice::ALSA_MIDI:
1770           break;
1771 
1772           case MidiDevice::JACK_MIDI:
1773           case MidiDevice::SYNTH_MIDI:
1774             md->handleStop();
1775           break;
1776         }
1777       }
1778 
1779       // There may be disk read/write fifo buffers waiting to be emptied. Send one last tick to the disk thread.
1780       if(!freewheel())
1781         MusEGlobal::audioPrefetch->msgTick(recording, false); // This does not wait.
1782 
1783       WaveTrackList* tracks = MusEGlobal::song->waves();
1784       for (iWaveTrack i = tracks->begin(); i != tracks->end(); ++i) {
1785             (*i)->resetMeter();
1786             }
1787       recording    = false;
1788       if(_bounceState == BounceOff)
1789       {
1790         write(sigFd, "3", 1);   // abort rolling
1791       }
1792       else
1793       {
1794         _bounceState = BounceOff;
1795         write(sigFd, "A", 1);   // abort rolling + Special stop bounce (offline) mode
1796       }
1797       }
1798 
1799 //---------------------------------------------------------
1800 //   stopRolling
1801 //---------------------------------------------------------
1802 
stopRolling()1803 void Audio::stopRolling()
1804 {
1805       if (MusEGlobal::debugMsg)
1806         fprintf(stderr, "Audio::stopRolling state %s\n", audioStates[state]);
1807 
1808       state = STOP;
1809 
1810       //
1811       // Clear midi device notes and stop stuck notes:
1812       //
1813 
1814       // Clear the special sync play state (separate from audio play state).
1815       MusEGlobal::midiSyncContainer.setExternalPlayState(ExtMidiClock::ExternStopped); // Not playing.   Moved here from MidiSeq::processStop()
1816 
1817       // Stop the ALSA devices...
1818       if(MusEGlobal::midiSeq)
1819         MusEGlobal::midiSeq->msgStop();  // FIXME: This waits!
1820 
1821       // Stop any non-ALSA devices...
1822       for(iMidiDevice id = MusEGlobal::midiDevices.begin(); id != MusEGlobal::midiDevices.end(); ++id)
1823       {
1824         MidiDevice* md = *id;
1825         const MidiDevice::MidiDeviceType type = md->deviceType();
1826         // Only for non-ALSA devices.
1827         switch(type)
1828         {
1829           case MidiDevice::ALSA_MIDI:
1830           break;
1831 
1832           case MidiDevice::JACK_MIDI:
1833           case MidiDevice::SYNTH_MIDI:
1834             md->handleStop();
1835           break;
1836         }
1837       }
1838 
1839       // There may be disk read/write fifo buffers waiting to be emptied. Send one last tick to the disk thread.
1840       if(!freewheel())
1841         MusEGlobal::audioPrefetch->msgTick(recording, false); // This does not wait.
1842 
1843       WaveTrackList* tracks = MusEGlobal::song->waves();
1844       for (iWaveTrack i = tracks->begin(); i != tracks->end(); ++i) {
1845             (*i)->resetMeter();
1846             }
1847       recording    = false;
1848       endRecordPos = _pos;
1849       endExternalRecTick = curTickPos;
1850       if(_bounceState == BounceOff)
1851       {
1852         write(sigFd, "0", 1);   // STOP
1853       }
1854       else
1855       {
1856         _bounceState = BounceOff;
1857         write(sigFd, "B", 1);   // STOP + Special stop bounce (offline) mode
1858       }
1859       }
1860 
1861 //---------------------------------------------------------
1862 //   recordStop
1863 //    execution environment: gui thread
1864 //---------------------------------------------------------
1865 
recordStop(bool restart,Undo * ops)1866 void Audio::recordStop(bool restart, Undo* ops)
1867       {
1868       MusEGlobal::song->processMasterRec();
1869 
1870       if (MusEGlobal::debugMsg)
1871         fprintf(stderr, "recordStop - startRecordPos=%d\n", MusEGlobal::extSyncFlag ? startExternalRecTick : startRecordPos.tick());
1872 
1873       Undo loc_ops;
1874       Undo& operations = ops ? (*ops) : loc_ops;
1875 
1876       WaveTrackList* wl = MusEGlobal::song->waves();
1877 
1878       for (iWaveTrack it = wl->begin(); it != wl->end(); ++it) {
1879             WaveTrack* track = *it;
1880             if (track->recordFlag() || MusEGlobal::song->bounceTrack == track) {
1881                   MusEGlobal::song->cmdAddRecordedWave(track, startRecordPos, restart ? _pos : endRecordPos, operations);
1882                   if(!restart)
1883                     operations.push_back(UndoOp(UndoOp::SetTrackRecord, track, false, true)); // True = non-undoable.
1884                   }
1885             }
1886       MidiTrackList* ml = MusEGlobal::song->midis();
1887       for (iMidiTrack it = ml->begin(); it != ml->end(); ++it) {
1888             MidiTrack* mt     = *it;
1889 
1890             //---------------------------------------------------
1891             //    resolve NoteOff events, Controller etc.
1892             //---------------------------------------------------
1893 
1894             // Do SysexMeta. Do loops.
1895             buildMidiEventList(&mt->events, mt->mpevents, mt, MusEGlobal::config.division, true, true);
1896             MusEGlobal::song->cmdAddRecordedEvents(mt, mt->events,
1897                  MusEGlobal::extSyncFlag ? startExternalRecTick : startRecordPos.tick(),
1898                  operations);
1899             mt->events.clear();    // ** Driver should not be touching this right now.
1900             mt->mpevents.clear();  // ** Driver should not be touching this right now.
1901             }
1902 
1903       //
1904       // bounce to file operates on the only
1905       // selected output port
1906       //
1907 
1908       AudioOutput* ao = MusEGlobal::song->bounceOutput;
1909       if(ao && MusEGlobal::song->outputs()->find(ao) != MusEGlobal::song->outputs()->end())
1910       {
1911         if(ao->recordFlag())
1912         {
1913           MusEGlobal::song->bounceOutput = nullptr;
1914           ao->setRecFile(nullptr); // if necessary, this automatically deletes _recFile
1915           operations.push_back(UndoOp(UndoOp::SetTrackRecord, ao, false, true));  // True = non-undoable.
1916         }
1917       }
1918       MusEGlobal::song->bounceTrack = nullptr;
1919 
1920       // Operate on a local list if none was given.
1921       if(!ops)
1922         MusEGlobal::song->applyOperationGroup(loc_ops);
1923 
1924       if(!restart)
1925          MusEGlobal::song->setRecord(false);
1926       }
1927 
1928 //---------------------------------------------------------
1929 //   framesAtCycleStart
1930 //    Frame count at the start of current cycle.
1931 //    This is meant to be called from inside process thread only.
1932 //---------------------------------------------------------
1933 
framesAtCycleStart() const1934 unsigned Audio::framesAtCycleStart() const
1935 {
1936       return MusEGlobal::audioDevice->framesAtCycleStart();
1937 }
1938 
1939 //---------------------------------------------------------
1940 //   framesSinceCycleStart
1941 //    Estimated frames since the last process cycle began
1942 //    This can be called from outside process thread.
1943 //---------------------------------------------------------
1944 
framesSinceCycleStart() const1945 unsigned Audio::framesSinceCycleStart() const
1946 {
1947   // Do not round up here since time resolution is higher than (audio) frame resolution.
1948   unsigned f = muse_multiply_64_div_64_to_64(curTimeUS() - syncTimeUS, MusEGlobal::sampleRate, 1000000UL);
1949 
1950   // Safety due to inaccuracies. It cannot be after the segment, right?
1951   if(f >= MusEGlobal::segmentSize)
1952     f = MusEGlobal::segmentSize - 1;
1953   return f;
1954 
1955   // REMOVE Tim. Or keep? (During midi_engine_fixes.)
1956   // Can't use this since for the Jack driver, jack_frames_since_cycle_start is designed to be called ONLY from inside process.
1957   // return MusEGlobal::audioDevice->framesSinceCycleStart();
1958 }
1959 
1960 //---------------------------------------------------------
1961 //   curFramePos()
1962 //    Current play position frame. Estimated to single-frame resolution while in play mode.
1963 //    This can be called from outside process thread.
1964 //---------------------------------------------------------
1965 
curFramePos() const1966 unsigned Audio::curFramePos() const
1967 {
1968   return _pos.frame() + (isPlaying() ? framesSinceCycleStart() : 0);
1969 }
1970 
1971 //---------------------------------------------------------
1972 //   curFrame
1973 //    Extrapolates current play frame on syncTime/syncFrame
1974 //    Estimated to single-frame resolution.
1975 //    This is an always-increasing number. Good for timestamps, and
1976 //     handling them during process when referenced to syncFrame.
1977 //    This is meant to be called from threads other than the process thread.
1978 //---------------------------------------------------------
1979 
curFrame() const1980 unsigned int Audio::curFrame() const
1981       {
1982       return MusEGlobal::audioDevice->framePos();
1983 
1984       // REMOVE Tim. Or keep? (During midi_engine_fixes.)
1985       // Can't use this since for the Jack driver, jack_frames_since_cycle_start is designed to be called ONLY from inside process.
1986       //return framesAtCycleStart() + framesSinceCycleStart();
1987       }
1988 
1989 //---------------------------------------------------------
1990 //   updateMidiClick
1991 //   Updates the metronome tick.
1992 //   Useful for after seek(), even startRolling() etc.
1993 //   To be called from audio thread only.
1994 //---------------------------------------------------------
1995 
updateMidiClick()1996 void Audio::updateMidiClick()
1997 {
1998   // Set the correct initial metronome midiClick.
1999   int bar, beat;
2000   unsigned tick;
2001   MusEGlobal::sigmap.tickValues(curTickPos, &bar, &beat, &tick);
2002   if(tick)
2003     beat += 1;
2004   midiClick = MusEGlobal::sigmap.bar2tick(bar, beat, 0);
2005   // REMOVE Tim. latency. Added. TODO: Account for latency, in both the midiClick above and audioClick below !
2006   audioClick = midiClick;
2007 }
2008 
2009 //---------------------------------------------------------
2010 //   sendMsgToGui
2011 //---------------------------------------------------------
2012 
sendMsgToGui(char c)2013 void Audio::sendMsgToGui(char c)
2014       {
2015       write(sigFd, &c, 1);
2016       }
2017 
2018 } // namespace MusECore
2019