summaryrefslogtreecommitdiff
path: root/muse/muse/audio.cpp
blob: ec8c64632eee114e5f77c0ceb9c388616823b82c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
//=============================================================================
//  MusE
//  Linux Music Editor
//  $Id:$
//
//  Copyright (C) 2002-2006 by Werner Schweer and others
//
//  This program is free software; you can redistribute it and/or modify
//  it under the terms of the GNU General Public License version 2.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program; if not, write to the Free Software
//  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//=============================================================================

#include <fcntl.h>

#include "al/al.h"
#include "muse.h"
#include "globals.h"
#include "song.h"
#include "driver/audiodev.h"
#include "audioprefetch.h"
#include "audiowriteback.h"
#include "audio.h"
#include "midiseq.h"
#include "sync.h"
#include "midi.h"
#include "gconfig.h"
#include "al/sig.h"
#include "al/tempo.h"
#include "widgets/utils.h"
#include "synth.h"

extern double curTime();
extern bool initJackAudio();

Audio* audio;
AudioDriver* audioDriver;   // current audio device in use

const char* seqMsgList[] = {
      "SEQM_ADD_TRACK",
      "SEQM_REMOVE_TRACK",
      "SEQM_MOVE_TRACK",
      "SEQM_ADD_PART",
      "SEQM_REMOVE_PART",
      "SEQM_CHANGE_PART",
      "SEQM_ADD_EVENT",
      "SEQM_REMOVE_EVENT",
      "SEQM_CHANGE_EVENT",
      "SEQM_ADD_TEMPO",
/*10*/"SEQM_SET_TEMPO",
      "SEQM_REMOVE_TEMPO",
      "SEQM_ADD_SIG",
      "SEQM_REMOVE_SIG",
      "SEQM_SET_GLOBAL_TEMPO",
      "SEQM_UNDO",
      "SEQM_REDO",
      "SEQM_RESET_DEVICES",
      "SEQM_INIT_DEVICES",
      "AUDIO_ROUTEADD",
	"AUDIO_ROUTEREMOVE",
/*20*/"AUDIO_ADDPLUGIN",
      "AUDIO_ADDMIDIPLUGIN",
      "AUDIO_SET_SEG_SIZE",
      "AUDIO_SET_CHANNELS",
      "MS_PROCESS",
      "MS_START",
      "MS_STOP",
      "MS_SET_RTC",
      "SEQM_IDLE",
      "SEQM_ADD_CTRL",
      "SEQM_REMOVE_CTRL"
      };

const char* audioStates[] = {
      "STOP", "START_PLAY", "PLAY", "LOOP1", "LOOP2", "SYNC", "PRECOUNT"
      };


//---------------------------------------------------------
//   Audio
//---------------------------------------------------------

Audio::Audio()
      {
      recording     = false;
      idle          = false;
      _freewheel    = false;
      _bounce       = 0;
      loopPassed    = false;

      _pos.setType(AL::FRAMES);
      _pos.setFrame(~0);      // make sure first seek is not optimized away

      _curTickPos   = 0;
      _nextTickPos  = 0;

      midiClick     = 0;
      clickno       = 0;
      clicksMeasure = 0;
      ticksBeat     = 0;

      syncTime      = 0.0;
      syncFrame     = 0;
      frameOffset   = 0;

      state         = STOP;
      lmark         = 0;      // left loop position
      rmark         = 0;      // right loop position
      msg           = 0;

      startRecordPos.setType(AL::TICKS);
      endRecordPos.setType(AL::TICKS);

      //---------------------------------------------------
      //  establish pipes/sockets
      //---------------------------------------------------

      int filedes[2];         // 0 - reading   1 - writing
      if (pipe(filedes) == -1) {
            perror("creating pipe0");
            fatalError("cannot create pipe0");
            }
      fromThreadFdw = filedes[1];   // blocking file descriptor
      fromThreadFdr = filedes[0];   // non blocking file descriptor

      int rv = fcntl(fromThreadFdw, F_SETFL, O_NONBLOCK);
      if (rv == -1)
            perror("set pipe O_NONBLOCK");

      if (pipe(filedes) == -1) {
            perror("creating pipe1");
            fatalError("cannot create pipe1");
            }
      sigFd = filedes[1];
      QSocketNotifier* ss = new QSocketNotifier(filedes[0], QSocketNotifier::Read);
      song->connect(ss, SIGNAL(activated(int)), song, SLOT(seqSignal(int)));
      }

//---------------------------------------------------------
//   start
//    start audio processing
//---------------------------------------------------------

bool Audio::start()
      {
      TrackList* tl = song->tracks();

      _curTickPos   = 0;
      _nextTickPos  = 0;

      midiClick     = 0;
      clickno       = 0;
      clicksMeasure = 0;
      ticksBeat     = 0;

      syncTime      = 0.0;
      syncFrame     = 0;
      frameOffset   = 0;

      msg           = 0;
      _pos.setFrame(~0);      // make sure seek is not optimized away

      //
      // init marker for synchronous loop processing
      //
      lmark = song->lPos().frame();
      rmark = song->rPos().frame();
      state = STOP;
      muse->setHeartBeat();

      if (audioDriver) {
          //
          // allocate ports
          //
          for (iTrack i = tl->begin(); i != tl->end(); ++i)
                (*i)->activate1();
          seek(song->cpos());
          process(segmentSize);   // warm up caches; audio must be stopped
          audioDriver->start(realTimePriority);
          }
      else {

          // if audio device has disappeared it probably
          // means jack has performed a shutdown
          // try to restart and reconnect everything

          if (false == initJackAudio()) {
                //
                // allocate ports, first resetting the old connection
                //
                InputList* itl = song->inputs();
                for (iAudioInput i = itl->begin(); i != itl->end(); ++i) {
//                      printf("reconnecting input %s\n", (*i)->name().toLatin1().data());
                      for (int x=0; x < (*i)->channels();x++)
                          (*i)->setJackPort(x,0); // zero out the old connection
                      (*i)->activate1();
                      }

                OutputList* otl = song->outputs();
                for (iAudioOutput i = otl->begin(); i != otl->end(); ++i) {
//                      printf("reconnecting output %s\n", (*i)->name().toLatin1().data());
                      for (int x=0; x < (*i)->channels();x++)
                          (*i)->setJackPort(x,0);  // zero out the old connection
                      (*i)->activate1();
                      }
               audioDriver->start(realTimePriority);
               }
          else {
               printf("Failed to init audio!\n");
               return false;
               }
          }
      audioDriver->stopTransport();

      //
      // do connections
      //
// done in seqStart
//      for (iTrack i = tl->begin(); i != tl->end(); ++i) {
//            (*i)->activate2();
//      	}
      return true;
      }

//---------------------------------------------------------
//   stop
//    stop audio processing
//---------------------------------------------------------

void Audio::stop(bool)
      {
      if (audioDriver)
          audioDriver->stop();

      MidiOutPortList* opl = song->midiOutPorts();
      for (iMidiOutPort i = opl->begin(); i != opl->end(); ++i)
            (*i)->deactivate();
      MidiInPortList* ipl = song->midiInPorts();
      for (iMidiInPort i = ipl->begin(); i != ipl->end(); ++i)
            (*i)->deactivate();
      }

//---------------------------------------------------------
//   sync
//    return true if sync is completed
//---------------------------------------------------------

bool Audio::sync(int jackState, unsigned frame)
      {
// printf("Audio::sync() state %s jackState %s frame 0x%x\n", audioStates[state], audioStates[jackState], frame);
      bool done = true;
      if (state == LOOP1)
            state = LOOP2;
      else {
            State s = State(jackState);
            //
            //  STOP -> START_PLAY	start rolling
            //  STOP -> STOP		seek in stop state
            //  PLAY -> START_PLAY  seek in play state

            if (state != START_PLAY) {
            	Pos p(frame, AL::FRAMES);
//                  printf("  sync seek\n");
	            seek(p);
      	      if (!_freewheel)
            	      done = audioPrefetch->seekDone();
              	if (s == START_PLAY)
              		state = START_PLAY;
              	}
            else {
            	if (frame != _pos.frame()) {
                  	// seek during seek
		            seek(Pos(frame, AL::FRAMES));
                  	}
            	done = audioPrefetch->seekDone();
                  }
            }
//      printf("  sync %s\n", done ? "done" : "busy");
      return done;
      }

//---------------------------------------------------------
//   setFreewheel
//---------------------------------------------------------

void Audio::setFreewheel(bool val)
      {
// printf("JACK: freewheel callback %d\n", val);
      _freewheel = val;
      }

//---------------------------------------------------------
//   shutdown
//---------------------------------------------------------

void Audio::shutdown()
      {
      audioState = AUDIO_STOP;
printf("JACK: shutdown callback\n");
      sendMsgToGui(MSG_JACK_SHUTDOWN);
      }

//---------------------------------------------------------
//   process
//    process one audio buffer at position "_pos "
//    of size "frames"
//---------------------------------------------------------

void Audio::process(unsigned frames)
      {
// printf("process %d\n", frames);
      extern int watchAudio;
      ++watchAudio;           // make a simple watchdog happy

      if (msg) {
            processMsg();
            msg    = 0;    // dont process again
            int rv = write(fromThreadFdw, "x", 1);
            if (rv != 1) {
                  fprintf(stderr, "audio: write(%d) pipe failed: %s\n",
                     fromThreadFdw, strerror(errno));
                  }
            }

      int jackState = audioDriver->getState();
      if (jackState != state) {
// printf("process %s %s\n", audioStates[state], audioStates[jackState]);
            if (state == START_PLAY && jackState == PLAY) {
                  startRolling();
                  if (_bounce)
                        sendMsgToGui(MSG_START_BOUNCE);
                  }
            else if (state == LOOP2 && jackState == PLAY) {
                  Pos newPos(loopFrame, AL::FRAMES);
                  seek(newPos);
                  startRolling();
                  }
            else if (isPlaying() && jackState == STOP) {
                  stopRolling();
                  }
            else if (state == START_PLAY && jackState == STOP) {
                  state = STOP;
                  updateController = true;
                  if (_bounce) {
                        audioDriver->startTransport();
                        }
                  else {
                        sendMsgToGui(MSG_STOP);
                        }
                  }
            else if (state == STOP && jackState == PLAY) {
                  startRolling();
                  }
            else if (state == LOOP1 && jackState == PLAY)
                  ;     // treat as play
            else if (state == LOOP2 && jackState == START_PLAY)
                  ;     // sync cycle, treat as play
            else
                  printf("JACK: state transition %s -> %s ?\n",
                     audioStates[state], audioStates[jackState]);
            }

      OutputList* ol = song->outputs();
      if (idle || state == START_PLAY) {
            // deliver no audio
            for (iAudioOutput i = ol->begin(); i != ol->end(); ++i)
                  (*i)->silence(frames);
            return;
            }
      unsigned framePos = _pos.frame();

      if (state == PLAY) {
            //
            // clear prefetch FIFO if left/right locators
            // have changed
            //
            unsigned llmark = song->lPos().frame();
            unsigned rrmark = song->rPos().frame();

            if (lmark != llmark || rmark != rrmark) {
                  //
                  // invalidate audio prefetch buffer
                  //
                  audioPrefetch->getFifo()->clear();
                  audioPrefetch->msgSeek(framePos);
                  lmark = llmark;
                  rmark = rrmark;
                  }
            }

      if (isPlaying()) {
            if (_bounce == 1 && _pos >= song->rPos()) {
                  _bounce = 2;
                  sendMsgToGui(MSG_STOP_BOUNCE);
                  }
            //
            //  check for end of song
            //
            if ((_curTickPos >= song->len())
               && !(song->record() || _bounce || song->loop())) {
                  audioDriver->stopTransport();
                  return;
                  }

            //
            //  check for loop end
            //
            if (state == PLAY && song->loop() && !_bounce && !extSyncFlag) {
                  unsigned n = rmark - framePos - (3 * frames);
                  if (n < frames) {
                        // loop end in current cycle
                        // adjust loop start so we get exact loop len
                        if (n > lmark)
                              n = 0;
                        state = LOOP1;
                        loopFrame = lmark - n;
                        audioDriver->seekTransport(loopFrame);
                        }
                  }

            Pos ppp(_pos);
            ppp += frames;
            _nextTickPos = ppp.tick();
            }

      //
      // resync with audio interface
      //    syncFrame - free running JACK frame counter
      //    syncTime  - corresponding wall clock time
      //
      syncFrame   = audioDriver->framePos();
      syncTime    = curTime();
      frameOffset = syncFrame - framePos;

      //
      //  compute current controller values
      //  (automation)
      //
      TrackList* tl = song->tracks();
      if (state == PLAY || updateController) {
            updateController = false;
            for (iTrack it = tl->begin(); it != tl->end(); ++it) {
                  if ((*it)->isMidiTrack())
                        continue;
                  AudioTrack* track = (AudioTrack*)(*it);
                  if (!track->autoRead())
                        continue;
                  CtrlList* cl = track->controller();
                  for (iCtrl i = cl->begin(); i != cl->end(); ++i) {
                        Ctrl* c = i->second;
                        float val = c->value(framePos).f;
                        if (val != c->curVal().f) {
                              c->setCurVal(val);
                              c->setChanged(true);
                              }
                        }
                  }
            }

      processMidi(frames);

      GroupList* gl     = song->groups();
      SynthIList* sl    = song->syntis();
      InputList* il     = song->inputs();
      WaveTrackList* wl = song->waves();

      for (iAudioInput i = il->begin(); i != il->end(); ++i)
            (*i)->process();
      for (iSynthI i = sl->begin(); i != sl->end(); ++i)
            (*i)->process();

      _curReadIndex = -1;
      if (isPlaying() && !wl->empty()) {
   	      Fifo1* fifo = audioPrefetch->getFifo();
// printf("process %3d\n", fifo->count());
      	if (fifo->count() == 0) {
            	printf("MusE::Audio: fifo underflow at 0x%x\n", _curTickPos);
                  audioPrefetch->msgTick();
                  }
            else {
                  bool msg = true;
                  do {
	                  unsigned fifoPos = fifo->readPos();
                  	if (fifoPos == framePos) {
                  		_curReadIndex = fifo->readIndex();
                              break;
                              }
                        else {
                              if (msg) {
	                              printf("Muse::Audio: wrong prefetch data 0x%x, expected 0x%x\n",
      	                     	   fifoPos, framePos);
                              	msg = false;
                                    }
                              if (fifoPos > framePos) {
                                    // discard whole prefetch buffer
                                    seek(_pos + frames);
                                    break;
                                    }
                              fifo->pop();      // discard buffer
                              }
              		} while (fifo->count());
                  }
            }
      for (iWaveTrack i = wl->begin(); i != wl->end(); ++i) {
      	if (song->bounceTrack != *i)
            	(*i)->process();
            }
      for (iAudioGroup i = gl->begin(); i != gl->end(); ++i)
            (*i)->process();
      for (iAudioOutput i = ol->begin(); i != ol->end(); ++i)
            (*i)->process();

      if (_bounce == 1 && song->bounceTrack && song->bounceTrack->type() == Track::WAVE)
            song->bounceTrack->process();

      if (isPlaying()) {
      	if (!freewheel()) {
                  //
                  // consume prefetch buffer
                  //
                  if (_curReadIndex != -1) {
                        audioPrefetch->getFifo()->pop();
			      audioPrefetch->msgTick();  // wakeup prefetch thread
                        }
                  }
            if (recording && (_bounce == 0 || _bounce == 1))
                  audioWriteback->trigger();
            _pos      += frames;
            _curTickPos = _nextTickPos;
            }
      }

//---------------------------------------------------------
//   processMsg
//---------------------------------------------------------

void Audio::processMsg()
      {
// printf("---msg %d\n", msg->id);
      switch(msg->id) {
            case AUDIO_ROUTEADD:
                  addRoute(msg->sroute, msg->droute);
                  break;
            case AUDIO_ROUTEREMOVE:
                  removeRoute(msg->sroute, msg->droute);
                  break;
            case AUDIO_SET_CHANNELS:
                  msg->track->setChannels(msg->ival);
                  break;
            case AUDIO_ADDPLUGIN:
                  ((AudioTrack*)msg->track)->addPlugin(msg->plugin, msg->ival,
                     msg->iival);
                  break;

            case AUDIO_SET_SEG_SIZE:
                  segmentSize = msg->ival;
                  AL::sampleRate  = msg->iival;
#if 0 //TODO
                  audioOutput.segmentSizeChanged();
                  for (int i = 0; i < mixerGroups; ++i)
                        audioGroups[i].segmentSizeChanged();
                  for (iSynthI ii = synthiInstances.begin(); ii != synthiInstances.end();++ii)
                        (*ii)->segmentSizeChanged();
#endif
                  break;

            case SEQM_INIT_DEVICES:
                  initDevices();
                  break;
            case SEQM_ADD_TEMPO:
            case SEQM_REMOVE_TEMPO:
            case SEQM_SET_GLOBAL_TEMPO:
            case SEQM_SET_TEMPO:
                  song->processMsg(msg);
                  if (isPlaying()) {
                        _pos.setTick(_curTickPos);
                        int framePos = _pos.frame();
                        syncFrame     = audioDriver->framePos();
                        syncTime      = curTime();
                        frameOffset   = syncFrame - framePos;
                        }
                  break;

            case SEQM_IDLE:
                  idle = msg->a;
                  // fall through
            default:
                  midiSeq->sendMsg(msg);
                  break;
            }
      }

//---------------------------------------------------------
//   seek
//    - called before start play
//    - initiated from gui
//---------------------------------------------------------

void Audio::seek(const Pos& p)
      {
      _pos.setFrame(p.frame());
      syncFrame        = audioDriver->framePos();
      frameOffset      = syncFrame - _pos.frame();
      _curTickPos      = _pos.tick();
      _nextTickPos     = _curTickPos;
      updateController = true;

      loopPassed = true;      // for record loop mode
      if (state != LOOP2 && !freewheel())
            audioPrefetch->msgSeek(_pos.frame());

      midiBusy = true;
      midiSeq->processSeek(); // handle stuck notes and set
                              // controller for new position
      midiBusy = false;

      sendMsgToGui(MSG_SEEK);
      }

//---------------------------------------------------------
//   startRolling
//---------------------------------------------------------

void Audio::startRolling()
      {
      startRecordPos = _pos;
      if (song->record()) {
            startRecordPos = _pos;
            recording      = true;
            TrackList* tracks = song->tracks();
            for (iTrack i = tracks->begin(); i != tracks->end(); ++i) {
                  if ((*i)->isMidiTrack())
                        continue;
                  if ((*i)->type() == Track::WAVE)
                        ((WaveTrack*)(*i))->resetMeter();
                  ((AudioTrack*)(*i))->recEvents()->clear();
                  }
            }
      state = PLAY;
      sendMsgToGui(MSG_PLAY);

      midiSeq->msgStart();

      if (precountEnableFlag
         && song->click()
         && !extSyncFlag
         && song->record()) {
#if 0
            state = PRECOUNT;
            int z, n;
            if (precountFromMastertrackFlag)
                  AL::sigmap.timesig(playTickPos, z, n);
            else {
                  z = precountSigZ;
                  n = precountSigN;
                  }
            clickno       = z * preMeasures;
            clicksMeasure = z;
            ticksBeat     = (division * 4)/n;
#endif
            }
      else {
            //
            // compute next midi metronome click position
            //
            int bar, beat;
            unsigned tick;
            AL::sigmap.tickValues(_curTickPos, &bar, &beat, &tick);
            if (tick)
                  beat += 1;
            midiClick = AL::sigmap.bar2tick(bar, beat, 0);
            }
      }

//---------------------------------------------------------
//   stopRolling
//	execution environment: realtime thread
//---------------------------------------------------------

void Audio::stopRolling()
      {
      state = STOP;
      midiSeq->msgStop();
	recording    = false;
      endRecordPos = _pos;
      _bounce = 0;
      sendMsgToGui(MSG_STOP);
      seek(_pos);
      }

//---------------------------------------------------------
//   curFrame
//    extrapolates current play frame on syncTime/syncFrame
//---------------------------------------------------------

unsigned int Audio::curFrame() const
      {
//      return lrint((curTime() - syncTime) * AL::sampleRate) + syncFrame;
      //
      // this should be the same:
      //
      return audioDriver->framePos();
      }

//---------------------------------------------------------
//   timestamp
//    timestamp has only meaning when rolling
//---------------------------------------------------------

int Audio::timestamp() const
      {
      return (state == PLAY) ? (audioDriver->framePos() - frameOffset) : 0;
      }

//---------------------------------------------------------
//   sendMsgToGui
//---------------------------------------------------------

void Audio::sendMsgToGui(char c)
      {
      write(sigFd, &c, 1);
      }