Audacity  2.2.2
AudioIO.cpp
Go to the documentation of this file.
1 /**********************************************************************
2 
3  Audacity: A Digital Audio Editor
4 
5  AudioIO.cpp
6 
7  Copyright 2000-2004:
8  Dominic Mazzoni
9  Joshua Haberman
10  Markus Meyer
11  Matt Brubeck
12 
13  This program is free software; you can redistribute it and/or modify it
14  under the terms of the GNU General Public License as published by the Free
15  Software Foundation; either version 2 of the License, or (at your option)
16  any later version.
17 
18 ********************************************************************//****************************************************************//****************************************************************//****************************************************************//*******************************************************************/
406 
407 #include "Audacity.h"
408 #include "Experimental.h"
409 #include "AudioIO.h"
410 #include "float_cast.h"
411 
412 #include <cfloat>
413 #include <math.h>
414 #include <stdlib.h>
415 #include <algorithm>
416 
417 #ifdef __WXMSW__
418 #include <malloc.h>
419 #endif
420 
421 #ifdef HAVE_ALLOCA_H
422 #include <alloca.h>
423 #endif
424 
425 #if USE_PORTMIXER
426 #include "portmixer.h"
427 #endif
428 
429 #include <wx/log.h>
430 #include <wx/textctrl.h>
431 #include <wx/timer.h>
432 #include <wx/intl.h>
433 #include <wx/debug.h>
434 #include <wx/sstream.h>
435 #include <wx/txtstrm.h>
436 
437 #include "AudacityApp.h"
438 #include "AudacityException.h"
439 #include "Mix.h"
440 #include "MixerBoard.h"
441 #include "Resample.h"
442 #include "RingBuffer.h"
443 #include "prefs/GUISettings.h"
444 #include "Prefs.h"
445 #include "Project.h"
446 #include "TimeTrack.h"
447 #include "WaveTrack.h"
448 #include "AutoRecovery.h"
449 
450 #include "prefs/QualityPrefs.h"
451 #include "toolbars/ControlToolBar.h"
452 #include "widgets/Meter.h"
453 #include "widgets/ErrorDialog.h"
454 #include "widgets/Warning.h"
455 
456 #ifdef EXPERIMENTAL_MIDI_OUT
457  #define MIDI_SLEEP 10 /* milliseconds */
458  // how long do we think the thread that fills MIDI buffers,
459  // if it is separate from the portaudio thread,
460  // might be delayed due to other threads?
461  #ifdef USE_MIDI_THREAD
462  #define THREAD_LATENCY 10 /* milliseconds */
463  #else
464  #define THREAD_LATENCY 0 /* milliseconds */
465  #endif
466  #define ROUND(x) (int) ((x)+0.5)
467  //#include <string.h>
468  #include "../lib-src/portmidi/pm_common/portmidi.h"
469  #include "../lib-src/portaudio-v19/src/common/pa_util.h"
470  #include "NoteTrack.h"
471 #endif
472 
473 #ifdef EXPERIMENTAL_AUTOMATED_INPUT_LEVEL_ADJUSTMENT
474  #define LOWER_BOUND 0.0
475  #define UPPER_BOUND 1.0
476 #endif
477 
478 using std::max;
479 using std::min;
480 
481 std::unique_ptr<AudioIO> ugAudioIO;
483 
484 wxDEFINE_EVENT(EVT_AUDIOIO_PLAYBACK, wxCommandEvent);
485 wxDEFINE_EVENT(EVT_AUDIOIO_CAPTURE, wxCommandEvent);
486 wxDEFINE_EVENT(EVT_AUDIOIO_MONITOR, wxCommandEvent);
487 
488 // static
491 std::vector<long> AudioIO::mCachedPlaybackRates;
493 std::vector<long> AudioIO::mCachedCaptureRates;
494 std::vector<long> AudioIO::mCachedSampleRates;
495 double AudioIO::mCachedBestRateIn = 0.0;
497 
498 enum {
499  // This is the least positive latency we can
500  // specify to Pm_OpenOutput, 1 ms, which prevents immediate
501  // scheduling of events:
503 };
504 
505 #ifdef EXPERIMENTAL_SCRUBBING_SUPPORT
506 
507 #include "tracks/ui/Scrubbing.h"
508 
509 #ifdef __WXGTK__
510  // Might #define this for a useful thing on Linux
511  #undef REALTIME_ALSA_THREAD
512 #else
513  // never on the other operating systems
514  #undef REALTIME_ALSA_THREAD
515 #endif
516 
517 #ifdef REALTIME_ALSA_THREAD
518 #include "pa_linux_alsa.h"
519 #endif
520 
521 
522 /*
523 This work queue class, with the aid of the playback ring
524 buffers, coordinates three threads during scrub play:
525 
526 The UI thread which specifies scrubbing intervals to play,
527 
528 The Audio thread which consumes those specifications a first time
529 and fills the ring buffers with samples for play,
530 
531 The PortAudio thread which consumes from the ring buffers, then
532 also consumes a second time from this queue,
533 to figure out how to update mTime
534 
535 -- which the UI thread, in turn, uses to redraw the play head indicator
536 in the right place.
537 
538 Audio produces samples for PortAudio, which consumes them, both in
539 approximate real time. The UI thread might go idle and so the others
540 might catch up, emptying the queue and causing scrub to go silent.
541 The UI thread will not normally outrun the others -- because InitEntry()
542 limits the real time duration over which each enqueued interval will play.
543 So a small, fixed queue size should be adequate.
544 */
546 {
547  ScrubQueue(double t0, double t1, wxLongLong startClockMillis,
548  double rate, long maxDebt,
549  const ScrubbingOptions &options)
550  : mTrailingIdx(0)
551  , mMiddleIdx(1)
552  , mLeadingIdx(1)
553  , mRate(rate)
554  , mLastScrubTimeMillis(startClockMillis)
555  , mMaxDebt { maxDebt }
556  , mUpdating()
557  {
558  const auto s0 = std::max(options.minSample, std::min(options.maxSample,
559  sampleCount(lrint(t0 * mRate))
560  ));
561  const auto s1 = sampleCount(lrint(t1 * mRate));
562  Duration dd { *this };
563  auto actualDuration = std::max(sampleCount{1}, dd.duration);
564  auto success = mEntries[mMiddleIdx].Init(nullptr,
565  s0, s1, actualDuration, options);
566  if (success)
567  ++mLeadingIdx;
568  else {
569  // If not, we can wait to enqueue again later
570  dd.Cancel();
571  }
572 
573  // So the play indicator starts out unconfused:
574  {
575  Entry &entry = mEntries[mTrailingIdx];
576  entry.mS0 = entry.mS1 = s0;
577  entry.mPlayed = entry.mDuration = 1;
578  }
579  }
581 
582  double LastTimeInQueue() const
583  {
584  // Needed by the main thread sometimes
585  wxMutexLocker locker(mUpdating);
586  const Entry &previous = mEntries[(mLeadingIdx + Size - 1) % Size];
587  return previous.mS1.as_double() / mRate;
588  }
589 
590  // This is for avoiding deadlocks while starting a scrub:
591  // Audio stream needs to be unblocked
592  void Nudge()
593  {
594  wxMutexLocker locker(mUpdating);
595  mNudged = true;
596  mAvailable.Signal();
597  }
598 
599  bool Producer(double end, const ScrubbingOptions &options)
600  {
601  // Main thread indicates a scrubbing interval
602 
603  // MAY ADVANCE mLeadingIdx, BUT IT NEVER CATCHES UP TO mTrailingIdx.
604 
605  wxMutexLocker locker(mUpdating);
606  bool result = true;
607  unsigned next = (mLeadingIdx + 1) % Size;
608  if (next != mTrailingIdx)
609  {
610  auto current = &mEntries[mLeadingIdx];
611  auto previous = &mEntries[(mLeadingIdx + Size - 1) % Size];
612 
613  // Use the previous end as NEW start.
614  const auto s0 = previous->mS1;
615  Duration dd { *this };
616  const auto &origDuration = dd.duration;
617  if (origDuration <= 0)
618  return false;
619 
620  auto actualDuration = origDuration;
621  const sampleCount s1 ( options.enqueueBySpeed
622  ? s0.as_double() +
623  lrint(origDuration.as_double() * end) // end is a speed
624  : lrint(end * mRate) // end is a time
625  );
626  auto success =
627  current->Init(previous, s0, s1, actualDuration, options);
628  if (success)
629  mLeadingIdx = next;
630  else {
631  dd.Cancel();
632  return false;
633  }
634 
635  // Fill up the queue with some silence if there was trimming
636  wxASSERT(actualDuration <= origDuration);
637  if (actualDuration < origDuration) {
638  next = (mLeadingIdx + 1) % Size;
639  if (next != mTrailingIdx) {
640  previous = &mEntries[(mLeadingIdx + Size - 1) % Size];
641  current = &mEntries[mLeadingIdx];
642  current->InitSilent(*previous, origDuration - actualDuration);
643  mLeadingIdx = next;
644  }
645  else
646  // Oops, can't enqueue the silence -- so do what?
647  ;
648  }
649 
650  mAvailable.Signal();
651  return result;
652  }
653  else
654  {
655  // ??
656  // Queue wasn't long enough. Write side (UI thread)
657  // has overtaken the trailing read side (PortAudio thread), despite
658  // my comments above! We lose some work requests then.
659  // wxASSERT(false);
660  return false;
661  }
662  }
663 
664  void Transformer(sampleCount &startSample, sampleCount &endSample,
665  sampleCount &duration,
666  Maybe<wxMutexLocker> &cleanup)
667  {
668  // Audio thread is ready for the next interval.
669 
670  // MAY ADVANCE mMiddleIdx, WHICH MAY EQUAL mLeadingIdx, BUT DOES NOT PASS IT.
671 
672  bool checkDebt = false;
673  if (!cleanup) {
674  cleanup.create(mUpdating);
675 
676  // Check for cancellation of work only when re-enetering the cricial section
677  checkDebt = true;
678  }
679  while(!mNudged && mMiddleIdx == mLeadingIdx)
680  mAvailable.Wait();
681 
682  mNudged = false;
683 
684  auto now = ::wxGetLocalTimeMillis();
685 
686  if (checkDebt &&
687  mLastTransformerTimeMillis >= 0 && // Not the first time for this scrub
688  mMiddleIdx != mLeadingIdx) {
689  // There is work in the queue, but if Producer is outrunning us, discard some,
690  // which may make a skip yet keep playback better synchronized with user gestures.
691  const auto interval = (now - mLastTransformerTimeMillis).ToDouble() / 1000.0;
692  //const Entry &previous = mEntries[(mMiddleIdx + Size - 1) % Size];
693  const auto deficit =
694  static_cast<long>(interval * mRate) - // Samples needed in the last time interval
695  mCredit; // Samples done in the last time interval
696  mCredit = 0;
697  mDebt += deficit;
698  auto toDiscard = mDebt - mMaxDebt;
699  while (toDiscard > 0 && mMiddleIdx != mLeadingIdx) {
700  // Cancel some debt (discard some NEW work)
701  auto &entry = mEntries[mMiddleIdx];
702  auto &dur = entry.mDuration;
703  if (toDiscard >= dur) {
704  // Discard entire queue entry
705  mDebt -= dur;
706  toDiscard -= dur;
707  dur = 0; // So Consumer() will handle abandoned entry correctly
708  mMiddleIdx = (mMiddleIdx + 1) % Size;
709  }
710  else {
711  // Adjust the start time
712  auto &start = entry.mS0;
713  const auto end = entry.mS1;
714  const auto ratio = toDiscard.as_double() / dur.as_double();
715  const sampleCount adjustment(
716  std::abs((end - start).as_long_long()) * ratio
717  );
718  if (start <= end)
719  start += adjustment;
720  else
721  start -= adjustment;
722 
723  mDebt -= toDiscard;
724  dur -= toDiscard;
725  toDiscard = 0;
726  }
727  }
728  }
729 
730  if (mMiddleIdx != mLeadingIdx) {
731  // There is still work in the queue, after cancelling debt
732  Entry &entry = mEntries[mMiddleIdx];
733  startSample = entry.mS0;
734  endSample = entry.mS1;
735  duration = entry.mDuration;
736  mMiddleIdx = (mMiddleIdx + 1) % Size;
737  mCredit += duration;
738  }
739  else {
740  // We got the shut-down signal, or we got nudged, or we discarded all the work.
741  startSample = endSample = duration = -1L;
742  }
743 
744  if (checkDebt)
746  }
747 
748  double Consumer(unsigned long frames)
749  {
750  // Portaudio thread consumes samples and must update
751  // the time for the indicator. This finds the time value.
752 
753  // MAY ADVANCE mTrailingIdx, BUT IT NEVER CATCHES UP TO mMiddleIdx.
754 
755  wxMutexLocker locker(mUpdating);
756 
757  // Mark entries as partly or fully "consumed" for
758  // purposes of mTime update. It should not happen that
759  // frames exceed the total of samples to be consumed,
760  // but in that case we just use the t1 of the latest entry.
761  while (1)
762  {
763  Entry *pEntry = &mEntries[mTrailingIdx];
764  auto remaining = pEntry->mDuration - pEntry->mPlayed;
765  if (frames >= remaining)
766  {
767  // remaining is not more than frames
768  frames -= remaining.as_size_t();
769  pEntry->mPlayed = pEntry->mDuration;
770  }
771  else
772  {
773  pEntry->mPlayed += frames;
774  break;
775  }
776  const unsigned next = (mTrailingIdx + 1) % Size;
777  if (next == mMiddleIdx)
778  break;
779  mTrailingIdx = next;
780  }
782  }
783 
784 private:
785  struct Entry
786  {
788  : mS0(0)
789  , mS1(0)
790  , mGoal(0)
791  , mDuration(0)
792  , mPlayed(0)
793  {}
794 
795  bool Init(Entry *previous, sampleCount s0, sampleCount s1,
796  sampleCount &duration /* in/out */,
797  const ScrubbingOptions &options)
798  {
799  const bool &adjustStart = options.adjustStart;
800 
801  wxASSERT(duration > 0);
802  double speed =
803  (std::abs((s1 - s0).as_long_long())) / duration.as_double();
804  bool adjustedSpeed = false;
805 
806  auto minSpeed = std::min(options.minSpeed, options.maxSpeed);
807  wxASSERT(minSpeed == options.minSpeed);
808 
809  // May change the requested speed and duration
810  if (!adjustStart && speed > options.maxSpeed)
811  {
812  // Reduce speed to the maximum selected in the user interface.
813  speed = options.maxSpeed;
814  mGoal = s1;
815  adjustedSpeed = true;
816  }
817  else if (!adjustStart &&
818  previous &&
819  previous->mGoal >= 0 &&
820  previous->mGoal == s1)
821  {
822  // In case the mouse has not moved, and playback
823  // is catching up to the mouse at maximum speed,
824  // continue at no less than maximum. (Without this
825  // the final catch-up can make a slow scrub interval
826  // that drops the pitch and sounds wrong.)
827  minSpeed = options.maxSpeed;
828  mGoal = s1;
829  adjustedSpeed = true;
830  }
831  else
832  mGoal = -1;
833 
834  if (speed < minSpeed) {
835  // Trim the duration.
836  duration = std::max(0L, lrint(speed * duration.as_double() / minSpeed));
837  speed = minSpeed;
838  adjustedSpeed = true;
839  }
840 
842  // Mixers were set up to go only so slowly, not slower.
843  // This will put a request for some silence in the work queue.
844  adjustedSpeed = true;
845  speed = 0.0;
846  }
847 
848  // May change s1 or s0 to match speed change or stay in bounds of the project
849 
850  if (adjustedSpeed && !adjustStart)
851  {
852  // adjust s1
853  const sampleCount diff = lrint(speed * duration.as_double());
854  if (s0 < s1)
855  s1 = s0 + diff;
856  else
857  s1 = s0 - diff;
858  }
859 
860  bool silent = false;
861 
862  // Adjust s1 (again), and duration, if s1 is out of bounds,
863  // or abandon if a stutter is too short.
864  // (Assume s0 is in bounds, because it equals the last scrub's s1 which was checked.)
865  if (s1 != s0)
866  {
867  auto newDuration = duration;
868  const auto newS1 = std::max(options.minSample, std::min(options.maxSample, s1));
869  if(s1 != newS1)
870  newDuration = std::max( sampleCount{ 0 },
871  sampleCount(
872  duration.as_double() * (newS1 - s0).as_double() /
873  (s1 - s0).as_double()
874  )
875  );
876  // When playback follows a fast mouse movement by "stuttering"
877  // at maximum playback, don't make stutters too short to be useful.
878  if (options.adjustStart && newDuration < options.minStutter)
879  return false;
880  else if (newDuration == 0) {
881  // Enqueue a silent scrub with s0 == s1
882  silent = true;
883  s1 = s0;
884  }
885  else if (s1 != newS1) {
886  // Shorten
887  duration = newDuration;
888  s1 = newS1;
889  }
890  }
891 
892  if (adjustStart && !silent)
893  {
894  // Limit diff because this is seeking.
895  const sampleCount diff =
896  lrint(std::min(options.maxSpeed, speed) * duration.as_double());
897  if (s0 < s1)
898  s0 = s1 - diff;
899  else
900  s0 = s1 + diff;
901  }
902 
903  mS0 = s0;
904  mS1 = s1;
905  mPlayed = 0;
906  mDuration = duration;
907  return true;
908  }
909 
910  void InitSilent(const Entry &previous, sampleCount duration)
911  {
912  mGoal = previous.mGoal;
913  mS0 = mS1 = previous.mS1;
914  mPlayed = 0;
915  mDuration = duration;
916  }
917 
918  double GetTime(double rate) const
919  {
920  return
921  (mS0.as_double() +
922  (mS1 - mS0).as_double() * mPlayed.as_double() / mDuration.as_double())
923  / rate;
924  }
925 
926  // These sample counts are initialized in the UI, producer, thread:
930  // This field is initialized in the UI thread too, and
931  // this work queue item corresponds to exactly this many samples of
932  // playback output:
934 
935  // The middleman Audio thread does not change these entries, but only
936  // changes indices in the queue structure.
937 
938  // This increases from 0 to mDuration as the PortAudio, consumer,
939  // thread catches up. When they are equal, this entry can be discarded:
941  };
942 
943  struct Duration {
944  Duration (ScrubQueue &queue_) : queue(queue_) {}
946  {
947  if(!cancelled)
949  }
950 
951  void Cancel() { cancelled = true; }
952 
954  const wxLongLong clockTime { ::wxGetLocalTimeMillis() };
955  const sampleCount duration { static_cast<long long>
956  (queue.mRate * (clockTime - queue.mLastScrubTimeMillis).ToDouble() / 1000.0)
957  };
958  bool cancelled { false };
959  };
960 
961  enum { Size = 10 };
963  unsigned mTrailingIdx;
964  unsigned mMiddleIdx;
965  unsigned mLeadingIdx;
966  const double mRate;
968 
969  wxLongLong mLastTransformerTimeMillis { -1LL };
972  const long mMaxDebt;
973 
974  mutable wxMutex mUpdating;
975  mutable wxCondition mAvailable { mUpdating };
976  bool mNudged { false };
977 };
978 #endif
979 
980 #ifdef EXPERIMENTAL_MIDI_OUT
981 // return the system time as a double
982 static double streamStartTime = 0; // bias system time to small number
983 
984 static double SystemTime(bool usingAlsa)
985 {
986 #ifdef __WXGTK__
987  if (usingAlsa) {
988  struct timespec now;
989  // CLOCK_MONOTONIC_RAW is unaffected by NTP or adj-time
990  clock_gettime(CLOCK_MONOTONIC_RAW, &now);
991  //return now.tv_sec + now.tv_nsec * 0.000000001;
992  return (now.tv_sec + now.tv_nsec * 0.000000001) - streamStartTime;
993  }
994 #else
995  static_cast<void>(usingAlsa);//compiler food.
996 #endif
997 
998  return PaUtil_GetTime() - streamStartTime;
999 }
1000 #endif
1001 
1002 const int AudioIO::StandardRates[] = {
1003  8000,
1004  11025,
1005  16000,
1006  22050,
1007  32000,
1008  44100,
1009  48000,
1010  88200,
1011  96000,
1012  176400,
1013  192000,
1014  352800,
1015  384000
1016 };
1018  sizeof(AudioIO::StandardRates[0]);
1019 const int AudioIO::RatesToTry[] = {
1020  8000,
1021  9600,
1022  11025,
1023  12000,
1024  15000,
1025  16000,
1026  22050,
1027  24000,
1028  32000,
1029  44100,
1030  48000,
1031  88200,
1032  96000,
1033  176400,
1034  192000,
1035  352800,
1036  384000
1037 };
1038 const int AudioIO::NumRatesToTry = sizeof(AudioIO::RatesToTry) /
1039  sizeof(AudioIO::RatesToTry[0]);
1040 
1041 int audacityAudioCallback(const void *inputBuffer, void *outputBuffer,
1042  unsigned long framesPerBuffer,
1043  const PaStreamCallbackTimeInfo *timeInfo,
1044  PaStreamCallbackFlags statusFlags, void *userData );
1045 
1047 //
1048 // class AudioThread - declaration and glue code
1049 //
1051 
1052 #ifdef __WXMAC__
1053 
1054 // On Mac OS X, it's better not to use the wxThread class.
1055 // We use our own implementation based on pthreads instead.
1056 
1057 #include <pthread.h>
1058 #include <time.h>
1059 
1060 class AudioThread {
1061  public:
1062  typedef int ExitCode;
1063  AudioThread() { mDestroy = false; mThread = NULL; }
1064  virtual ExitCode Entry();
1065  void Create() {}
1066  void Delete() {
1067  mDestroy = true;
1068  pthread_join(mThread, NULL);
1069  }
1070  bool TestDestroy() { return mDestroy; }
1071  void Sleep(int ms) {
1072  struct timespec spec;
1073  spec.tv_sec = 0;
1074  spec.tv_nsec = ms * 1000 * 1000;
1075  nanosleep(&spec, NULL);
1076  }
1077  static void *callback(void *p) {
1078  AudioThread *th = (AudioThread *)p;
1079  return (void *)th->Entry();
1080  }
1081  void Run() {
1082  pthread_create(&mThread, NULL, callback, this);
1083  }
1084  private:
1085  bool mDestroy;
1086  pthread_t mThread;
1087 
1088 };
1089 
1090 #else
1091 
1092 // The normal wxThread-derived AudioThread class for all other
1093 // platforms:
1094 class AudioThread /* not final */ : public wxThread {
1095  public:
1096  AudioThread():wxThread(wxTHREAD_JOINABLE) {}
1097  ExitCode Entry() override;
1098 };
1099 
1100 #endif
1101 
1102 #ifdef EXPERIMENTAL_MIDI_OUT
1103 class MidiThread final : public AudioThread {
1104  public:
1105  ExitCode Entry() override;
1106 };
1107 #endif
1108 
1109 
1111 //
1112 // UI Thread Context
1113 //
1115 
1117 {
1118  ugAudioIO.reset(safenew AudioIO());
1119  gAudioIO = ugAudioIO.get();
1120  gAudioIO->mThread->Run();
1121 #ifdef EXPERIMENTAL_MIDI_OUT
1122 #ifdef USE_MIDI_THREAD
1123  gAudioIO->mMidiThread->Run();
1124 #endif
1125 #endif
1126 
1127  // Make sure device prefs are initialized
1128  if (gPrefs->Read(wxT("AudioIO/RecordingDevice"), wxT("")) == wxT("")) {
1129  int i = AudioIO::getRecordDevIndex();
1130  const PaDeviceInfo *info = Pa_GetDeviceInfo(i);
1131  if (info) {
1132  gPrefs->Write(wxT("/AudioIO/RecordingDevice"), DeviceName(info));
1133  gPrefs->Write(wxT("/AudioIO/Host"), HostName(info));
1134  }
1135  }
1136 
1137  if (gPrefs->Read(wxT("AudioIO/PlaybackDevice"), wxT("")) == wxT("")) {
1138  int i = AudioIO::getPlayDevIndex();
1139  const PaDeviceInfo *info = Pa_GetDeviceInfo(i);
1140  if (info) {
1141  gPrefs->Write(wxT("/AudioIO/PlaybackDevice"), DeviceName(info));
1142  gPrefs->Write(wxT("/AudioIO/Host"), HostName(info));
1143  }
1144  }
1145 
1146  gPrefs->Flush();
1147 }
1148 
1150 {
1151  ugAudioIO.reset();
1152 }
1153 
1154 wxString DeviceName(const PaDeviceInfo* info)
1155 {
1156  wxString infoName = wxSafeConvertMB2WX(info->name);
1157 
1158  return infoName;
1159 }
1160 
1161 wxString HostName(const PaDeviceInfo* info)
1162 {
1163  wxString hostapiName = wxSafeConvertMB2WX(Pa_GetHostApiInfo(info->hostApi)->name);
1164 
1165  return hostapiName;
1166 }
1167 
1168 bool AudioIO::ValidateDeviceNames(const wxString &play, const wxString &rec)
1169 {
1170  const PaDeviceInfo *pInfo = Pa_GetDeviceInfo(AudioIO::getPlayDevIndex(play));
1171  const PaDeviceInfo *rInfo = Pa_GetDeviceInfo(AudioIO::getRecordDevIndex(rec));
1172 
1173  if (!pInfo || !rInfo || pInfo->hostApi != rInfo->hostApi) {
1174  return false;
1175  }
1176 
1177  return true;
1178 }
1179 
1181 {
1185  mPortStreamV19 = NULL;
1186 
1187 #ifdef EXPERIMENTAL_MIDI_OUT
1188  mMidiStream = NULL;
1189  mMidiThreadFillBuffersLoopRunning = false;
1190  mMidiThreadFillBuffersLoopActive = false;
1191  mMidiStreamActive = false;
1192  mSendMidiState = false;
1193  mIterator = NULL;
1194 
1195  mNumFrames = 0;
1196  mNumPauseFrames = 0;
1197 #endif
1198 
1199 #ifdef EXPERIMENTAL_AUTOMATED_INPUT_LEVEL_ADJUSTMENT
1200  mAILAActive = false;
1201 #endif
1202  mStreamToken = 0;
1203 
1204  mLastPaError = paNoError;
1205 
1206  mLastRecordingOffset = 0.0;
1207  mNumCaptureChannels = 0;
1208  mPaused = false;
1210 
1211  mListener = NULL;
1212  mUpdateMeters = false;
1213  mUpdatingMeters = false;
1214 
1215  mOwningProject = NULL;
1216  mOutputMeter = NULL;
1217 
1218  PaError err = Pa_Initialize();
1219 
1220  if (err != paNoError) {
1221  wxString errStr = _("Could not find any audio devices.\n");
1222  errStr += _("You will not be able to play or record audio.\n\n");
1223  wxString paErrStr = LAT1CTOWX(Pa_GetErrorText(err));
1224  if (!paErrStr.IsEmpty())
1225  errStr += _("Error: ")+paErrStr;
1226  // XXX: we are in libaudacity, popping up dialogs not allowed! A
1227  // long-term solution will probably involve exceptions
1228  AudacityMessageBox(errStr, _("Error Initializing Audio"), wxICON_ERROR|wxOK);
1229 
1230  // Since PortAudio is not initialized, all calls to PortAudio
1231  // functions will fail. This will give reasonable behavior, since
1232  // the user will be able to do things not relating to audio i/o,
1233  // but any attempt to play or record will simply fail.
1234  }
1235 
1236 #ifdef EXPERIMENTAL_MIDI_OUT
1237  PmError pmErr = Pm_Initialize();
1238 
1239  if (pmErr != pmNoError) {
1240  wxString errStr =
1241  _("There was an error initializing the midi i/o layer.\n");
1242  errStr += _("You will not be able to play midi.\n\n");
1243  wxString pmErrStr = LAT1CTOWX(Pm_GetErrorText(pmErr));
1244  if (!pmErrStr.empty())
1245  errStr += _("Error: ") + pmErrStr;
1246  // XXX: we are in libaudacity, popping up dialogs not allowed! A
1247  // long-term solution will probably involve exceptions
1248  AudacityMessageBox(errStr, _("Error Initializing Midi"), wxICON_ERROR|wxOK);
1249 
1250  // Same logic for PortMidi as described above for PortAudio
1251  }
1252 
1253 #ifdef USE_MIDI_THREAD
1254  mMidiThread = std::make_unique<MidiThread>();
1255  mMidiThread->Create();
1256 #endif
1257 
1258 #endif
1259 
1260  // Start thread
1261  mThread = std::make_unique<AudioThread>();
1262  mThread->Create();
1263 
1264 #if defined(USE_PORTMIXER)
1265  mPortMixer = NULL;
1266  mPreviousHWPlaythrough = -1.0;
1268 #else
1269  mEmulateMixerOutputVol = true;
1270  mMixerOutputVol = 1.0;
1271  mInputMixerWorks = false;
1272 #endif
1273 
1275 
1276 #ifdef EXPERIMENTAL_SCRUBBING_SUPPORT
1277  mScrubQueue = NULL;
1278  mScrubDuration = 0;
1279  mSilentScrub = false;
1280 #endif
1281 }
1282 
1284 {
1285 #if defined(USE_PORTMIXER)
1286  if (mPortMixer) {
1287  #if __WXMAC__
1288  if (Px_SupportsPlaythrough(mPortMixer) && mPreviousHWPlaythrough >= 0.0)
1289  Px_SetPlaythrough(mPortMixer, mPreviousHWPlaythrough);
1290  mPreviousHWPlaythrough = -1.0;
1291  #endif
1292  Px_CloseMixer(mPortMixer);
1293  mPortMixer = NULL;
1294  }
1295 #endif
1296 
1297  // FIXME: ? TRAP_ERR. Pa_Terminate probably OK if err without reporting.
1298  Pa_Terminate();
1299 
1300 #ifdef EXPERIMENTAL_MIDI_OUT
1301  Pm_Terminate();
1302 
1303  /* Delete is a "graceful" way to stop the thread.
1304  (Kill is the not-graceful way.) */
1305 
1306 #ifdef USE_MIDI_THREAD
1307  mMidiThread->Delete();
1308  mMidiThread.reset();
1309 #endif
1310 
1311 #endif
1312 
1313  /* Delete is a "graceful" way to stop the thread.
1314  (Kill is the not-graceful way.) */
1315 
1316  // This causes reentrancy issues during application shutdown
1317  // wxTheApp->Yield();
1318 
1319  mThread->Delete();
1320  mThread.reset();
1321 
1322  gAudioIO = nullptr;
1323 }
1324 
1325 void AudioIO::SetMixer(int inputSource)
1326 {
1327 #if defined(USE_PORTMIXER)
1328  int oldRecordSource = Px_GetCurrentInputSource(mPortMixer);
1329  if ( inputSource != oldRecordSource )
1330  Px_SetCurrentInputSource(mPortMixer, inputSource);
1331 #endif
1332 }
1333 void AudioIO::SetMixer(int inputSource, float recordVolume,
1334  float playbackVolume)
1335 {
1336  mMixerOutputVol = playbackVolume;
1337 
1338 #if defined(USE_PORTMIXER)
1339  PxMixer *mixer = mPortMixer;
1340 
1341  if( mixer )
1342  {
1343  float oldRecordVolume = Px_GetInputVolume(mixer);
1344  float oldPlaybackVolume = Px_GetPCMOutputVolume(mixer);
1345 
1346  SetMixer(inputSource);
1347  if( oldRecordVolume != recordVolume )
1348  Px_SetInputVolume(mixer, recordVolume);
1349  if( oldPlaybackVolume != playbackVolume )
1350  Px_SetPCMOutputVolume(mixer, playbackVolume);
1351 
1352  return;
1353  }
1354 #endif
1355 }
1356 
1357 void AudioIO::GetMixer(int *recordDevice, float *recordVolume,
1358  float *playbackVolume)
1359 {
1360 #if defined(USE_PORTMIXER)
1361 
1362  PxMixer *mixer = mPortMixer;
1363 
1364  if( mixer )
1365  {
1366  *recordDevice = Px_GetCurrentInputSource(mixer);
1367 
1368  if (mInputMixerWorks)
1369  *recordVolume = Px_GetInputVolume(mixer);
1370  else
1371  *recordVolume = 1.0f;
1372 
1374  *playbackVolume = mMixerOutputVol;
1375  else
1376  *playbackVolume = Px_GetPCMOutputVolume(mixer);
1377 
1378  return;
1379  }
1380 
1381 #endif
1382 
1383  *recordDevice = 0;
1384  *recordVolume = 1.0f;
1385  *playbackVolume = mMixerOutputVol;
1386 }
1387 
1389 {
1390  return mInputMixerWorks;
1391 }
1392 
1394 {
1395  return mEmulateMixerOutputVol;
1396 }
1397 
1399 {
1400 #if defined(USE_PORTMIXER)
1401 
1402  wxArrayString deviceNames;
1403 
1404  if( mPortMixer )
1405  {
1406  int numSources = Px_GetNumInputSources(mPortMixer);
1407  for( int source = 0; source < numSources; source++ )
1408  deviceNames.Add(wxString(wxSafeConvertMB2WX(Px_GetInputSourceName(mPortMixer, source))));
1409  }
1410  else
1411  {
1412  wxLogDebug(wxT("AudioIO::GetInputSourceNames(): PortMixer not initialised!"));
1413  }
1414 
1415  return deviceNames;
1416 
1417 #else
1418 
1419  wxArrayString blank;
1420 
1421  return blank;
1422 
1423 #endif
1424 }
1425 
1427 {
1428  // This should not happen, but it would screw things up if it did.
1429  // Vaughan, 2010-10-08: But it *did* happen, due to a bug, and nobody
1430  // caught it because this method just returned. Added wxASSERT().
1431  wxASSERT(!IsStreamActive());
1432  if (IsStreamActive())
1433  return;
1434 
1435  // get the selected record and playback devices
1436  const int playDeviceNum = getPlayDevIndex();
1437  const int recDeviceNum = getRecordDevIndex();
1438 
1439  // If no change needed, return
1440  if (mCachedPlaybackIndex == playDeviceNum &&
1441  mCachedCaptureIndex == recDeviceNum)
1442  return;
1443 
1444  // cache playback/capture rates
1447  mCachedSampleRates = GetSupportedSampleRates(playDeviceNum, recDeviceNum);
1448  mCachedPlaybackIndex = playDeviceNum;
1449  mCachedCaptureIndex = recDeviceNum;
1450  mCachedBestRateIn = 0.0;
1451 
1452 #if defined(USE_PORTMIXER)
1453 
1454  // if we have a PortMixer object, close it down
1455  if (mPortMixer) {
1456  #if __WXMAC__
1457  // on the Mac we must make sure that we restore the hardware playthrough
1458  // state of the sound device to what it was before, because there isn't
1459  // a UI for this (!)
1460  if (Px_SupportsPlaythrough(mPortMixer) && mPreviousHWPlaythrough >= 0.0)
1461  Px_SetPlaythrough(mPortMixer, mPreviousHWPlaythrough);
1462  mPreviousHWPlaythrough = -1.0;
1463  #endif
1464  Px_CloseMixer(mPortMixer);
1465  mPortMixer = NULL;
1466  }
1467 
1468  // that might have given us no rates whatsoever, so we have to guess an
1469  // answer to do the next bit
1470  int numrates = mCachedSampleRates.size();
1471  int highestSampleRate;
1472  if (numrates > 0)
1473  {
1474  highestSampleRate = mCachedSampleRates[numrates - 1];
1475  }
1476  else
1477  { // we don't actually have any rates that work for Rec and Play. Guess one
1478  // to use for messing with the mixer, which doesn't actually do either
1479  highestSampleRate = 44100;
1480  // mCachedSampleRates is still empty, but it's not used again, so
1481  // can ignore
1482  }
1483  mInputMixerWorks = false;
1484  mEmulateMixerOutputVol = true;
1485  mMixerOutputVol = 1.0;
1486 
1487  int error;
1488  // This tries to open the device with the samplerate worked out above, which
1489  // will be the highest available for play and record on the device, or
1490  // 44.1kHz if the info cannot be fetched.
1491 
1492  PaStream *stream;
1493 
1494  PaStreamParameters playbackParameters;
1495 
1496  playbackParameters.device = playDeviceNum;
1497  playbackParameters.sampleFormat = paFloat32;
1498  playbackParameters.hostApiSpecificStreamInfo = NULL;
1499  playbackParameters.channelCount = 1;
1500  if (Pa_GetDeviceInfo(playDeviceNum))
1501  playbackParameters.suggestedLatency =
1502  Pa_GetDeviceInfo(playDeviceNum)->defaultLowOutputLatency;
1503  else
1504  playbackParameters.suggestedLatency = DEFAULT_LATENCY_CORRECTION/1000.0;
1505 
1506  PaStreamParameters captureParameters;
1507 
1508  captureParameters.device = recDeviceNum;
1509  captureParameters.sampleFormat = paFloat32;;
1510  captureParameters.hostApiSpecificStreamInfo = NULL;
1511  captureParameters.channelCount = 1;
1512  if (Pa_GetDeviceInfo(recDeviceNum))
1513  captureParameters.suggestedLatency =
1514  Pa_GetDeviceInfo(recDeviceNum)->defaultLowInputLatency;
1515  else
1516  captureParameters.suggestedLatency = DEFAULT_LATENCY_CORRECTION/1000.0;
1517 
1518  // try opening for record and playback
1519  error = Pa_OpenStream(&stream,
1520  &captureParameters, &playbackParameters,
1521  highestSampleRate, paFramesPerBufferUnspecified,
1522  paClipOff | paDitherOff,
1523  audacityAudioCallback, NULL);
1524 
1525  if (!error) {
1526  // Try portmixer for this stream
1527  mPortMixer = Px_OpenMixer(stream, 0);
1528  if (!mPortMixer) {
1529  Pa_CloseStream(stream);
1530  error = true;
1531  }
1532  }
1533 
1534  // if that failed, try just for record
1535  if( error ) {
1536  error = Pa_OpenStream(&stream,
1537  &captureParameters, NULL,
1538  highestSampleRate, paFramesPerBufferUnspecified,
1539  paClipOff | paDitherOff,
1540  audacityAudioCallback, NULL);
1541 
1542  if (!error) {
1543  mPortMixer = Px_OpenMixer(stream, 0);
1544  if (!mPortMixer) {
1545  Pa_CloseStream(stream);
1546  error = true;
1547  }
1548  }
1549  }
1550 
1551  // finally, try just for playback
1552  if ( error ) {
1553  error = Pa_OpenStream(&stream,
1554  NULL, &playbackParameters,
1555  highestSampleRate, paFramesPerBufferUnspecified,
1556  paClipOff | paDitherOff,
1557  audacityAudioCallback, NULL);
1558 
1559  if (!error) {
1560  mPortMixer = Px_OpenMixer(stream, 0);
1561  if (!mPortMixer) {
1562  Pa_CloseStream(stream);
1563  error = true;
1564  }
1565  }
1566  }
1567 
1568  // FIXME: TRAP_ERR errors in HandleDeviceChange not reported.
1569  // if it's still not working, give up
1570  if( error )
1571  return;
1572 
1573  // Set input source
1574 #if USE_PORTMIXER
1575  int sourceIndex;
1576  if (gPrefs->Read(wxT("/AudioIO/RecordingSourceIndex"), &sourceIndex)) {
1577  if (sourceIndex >= 0) {
1578  //the current index of our source may be different because the stream
1579  //is a combination of two devices, so update it.
1580  sourceIndex = getRecordSourceIndex(mPortMixer);
1581  if (sourceIndex >= 0)
1582  SetMixer(sourceIndex);
1583  }
1584  }
1585 #endif
1586 
1587  // Determine mixer capabilities - if it doesn't support control of output
1588  // signal level, we emulate it (by multiplying this value by all outgoing
1589  // samples)
1590 
1591  mMixerOutputVol = Px_GetPCMOutputVolume(mPortMixer);
1592  mEmulateMixerOutputVol = false;
1593  Px_SetPCMOutputVolume(mPortMixer, 0.0);
1594  if (Px_GetPCMOutputVolume(mPortMixer) > 0.1)
1595  mEmulateMixerOutputVol = true;
1596  Px_SetPCMOutputVolume(mPortMixer, 0.2f);
1597  if (Px_GetPCMOutputVolume(mPortMixer) < 0.1 ||
1598  Px_GetPCMOutputVolume(mPortMixer) > 0.3)
1599  mEmulateMixerOutputVol = true;
1600  Px_SetPCMOutputVolume(mPortMixer, mMixerOutputVol);
1601 
1602  float inputVol = Px_GetInputVolume(mPortMixer);
1603  mInputMixerWorks = true; // assume it works unless proved wrong
1604  Px_SetInputVolume(mPortMixer, 0.0);
1605  if (Px_GetInputVolume(mPortMixer) > 0.1)
1606  mInputMixerWorks = false; // can't set to zero
1607  Px_SetInputVolume(mPortMixer, 0.2f);
1608  if (Px_GetInputVolume(mPortMixer) < 0.1 ||
1609  Px_GetInputVolume(mPortMixer) > 0.3)
1610  mInputMixerWorks = false; // can't set level accurately
1611  Px_SetInputVolume(mPortMixer, inputVol);
1612 
1613  Pa_CloseStream(stream);
1614 
1615 
1616  #if 0
1617  wxPrintf("PortMixer: Playback: %s Recording: %s\n",
1618  mEmulateMixerOutputVol? "emulated": "native",
1619  mInputMixerWorks? "hardware": "no control");
1620  #endif
1621 
1622  mMixerOutputVol = 1.0;
1623 
1624 #endif // USE_PORTMIXER
1625 }
1626 
1628 {
1629  switch(format) {
1630  case int16Sample:
1631  return paInt16;
1632  case int24Sample:
1633  return paInt24;
1634  case floatSample:
1635  default:
1636  return paFloat32;
1637  }
1638 }
1639 
1640 bool AudioIO::StartPortAudioStream(double sampleRate,
1641  unsigned int numPlaybackChannels,
1642  unsigned int numCaptureChannels,
1643  sampleFormat captureFormat)
1644 {
1645 #ifdef EXPERIMENTAL_MIDI_OUT
1646  mNumFrames = 0;
1647  mNumPauseFrames = 0;
1648  // we want this initial value to be way high. It should be
1649  // sufficient to assume AudioTime is zero and therefore
1650  // mSystemMinusAudioTime is SystemTime(), but we'll add 1000s
1651  // for good measure. On the first callback, this should be
1652  // reduced to SystemTime() - mT0, and note that mT0 is always
1653  // positive.
1654  mSystemMinusAudioTimePlusLatency =
1655  mSystemMinusAudioTime = SystemTime(mUsingAlsa) + 1000;
1656  mAudioOutLatency = 0.0; // set when stream is opened
1657  mCallbackCount = 0;
1658  mAudioFramesPerBuffer = 0;
1659 #endif
1661 
1662  // PRL: Protection from crash reported by David Bailes, involving starting
1663  // and stopping with frequent changes of active window, hard to reproduce
1664  if (!mOwningProject)
1665  return false;
1666 
1667  mInputMeter.Release();
1668  mOutputMeter = NULL;
1669 
1670  mLastPaError = paNoError;
1671  // pick a rate to do the audio I/O at, from those available. The project
1672  // rate is suggested, but we may get something else if it isn't supported
1673  mRate = GetBestRate(numCaptureChannels > 0, numPlaybackChannels > 0, sampleRate);
1674 
1675  // July 2016 (Carsten and Uwe)
1676  // BUG 193: Tell PortAudio sound card will handle 24 bit (under DirectSound) using
1677  // userData.
1678  int captureFormat_saved = captureFormat;
1679  // Special case: Our 24-bit sample format is different from PortAudio's
1680  // 3-byte packed format. So just make PortAudio return float samples,
1681  // since we need float values anyway to apply the gain.
1682  // ANSWER-ME: So we *never* actually handle 24-bit?! This causes mCapture to
1683  // be set to floatSample below.
1684  // JKC: YES that's right. Internally Audacity uses float, and float has space for
1685  // 24 bits as well as exponent. Actual 24 bit would require packing and
1686  // unpacking unaligned bytes and would be inefficient.
1687  // ANSWER ME: is floatSample 64 bit on 64 bit machines?
1688  if (captureFormat == int24Sample)
1689  captureFormat = floatSample;
1690 
1691  mNumPlaybackChannels = numPlaybackChannels;
1692  mNumCaptureChannels = numCaptureChannels;
1693 
1694  bool usePlayback = false, useCapture = false;
1695  PaStreamParameters playbackParameters{};
1696  PaStreamParameters captureParameters{};
1697 
1698  double latencyDuration = DEFAULT_LATENCY_DURATION;
1699  gPrefs->Read(wxT("/AudioIO/LatencyDuration"), &latencyDuration);
1700 
1701  if( numPlaybackChannels > 0)
1702  {
1703  usePlayback = true;
1704 
1705  // this sets the device index to whatever is "right" based on preferences,
1706  // then defaults
1707  playbackParameters.device = getPlayDevIndex();
1708 
1709  const PaDeviceInfo *playbackDeviceInfo;
1710  playbackDeviceInfo = Pa_GetDeviceInfo( playbackParameters.device );
1711 
1712  if( playbackDeviceInfo == NULL )
1713  return false;
1714 
1715  // regardless of source formats, we always mix to float
1716  playbackParameters.sampleFormat = paFloat32;
1717  playbackParameters.hostApiSpecificStreamInfo = NULL;
1718  playbackParameters.channelCount = mNumPlaybackChannels;
1719 
1721  playbackParameters.suggestedLatency =
1722  playbackDeviceInfo->defaultLowOutputLatency;
1723  else
1724  playbackParameters.suggestedLatency = latencyDuration/1000.0;
1725 
1727  }
1728 
1729  if( numCaptureChannels > 0)
1730  {
1731  useCapture = true;
1732  mCaptureFormat = captureFormat;
1733 
1734  const PaDeviceInfo *captureDeviceInfo;
1735  // retrieve the index of the device set in the prefs, or a sensible
1736  // default if it isn't set/valid
1737  captureParameters.device = getRecordDevIndex();
1738 
1739  captureDeviceInfo = Pa_GetDeviceInfo( captureParameters.device );
1740 
1741  if( captureDeviceInfo == NULL )
1742  return false;
1743 
1744  captureParameters.sampleFormat =
1746 
1747  captureParameters.hostApiSpecificStreamInfo = NULL;
1748  captureParameters.channelCount = mNumCaptureChannels;
1749 
1751  captureParameters.suggestedLatency =
1752  captureDeviceInfo->defaultHighInputLatency;
1753  else
1754  captureParameters.suggestedLatency = latencyDuration/1000.0;
1755 
1757  }
1758 
1759  SetMeters();
1760 
1761 #ifdef USE_PORTMIXER
1762 #ifdef __WXMSW__
1763  //mchinen nov 30 2010. For some reason Pa_OpenStream resets the input volume on windows.
1764  //so cache and restore after it.
1765  //The actual problem is likely in portaudio's pa_win_wmme.c OpenStream().
1766  float oldRecordVolume = Px_GetInputVolume(mPortMixer);
1767 #endif
1768 #endif
1769 
1770  // July 2016 (Carsten and Uwe)
1771  // BUG 193: Possibly tell portAudio to use 24 bit with DirectSound.
1772  int userData = 24;
1773  int* lpUserData = (captureFormat_saved == int24Sample) ? &userData : NULL;
1774 
1775  mLastPaError = Pa_OpenStream( &mPortStreamV19,
1776  useCapture ? &captureParameters : NULL,
1777  usePlayback ? &playbackParameters : NULL,
1778  mRate, paFramesPerBufferUnspecified,
1779  paNoFlag,
1780  audacityAudioCallback, lpUserData );
1781 
1782 
1783 #if USE_PORTMIXER
1784 #ifdef __WXMSW__
1785  Px_SetInputVolume(mPortMixer, oldRecordVolume);
1786 #endif
1787  if (mPortStreamV19 != NULL && mLastPaError == paNoError) {
1788 
1789  #ifdef __WXMAC__
1790  if (mPortMixer) {
1791  if (Px_SupportsPlaythrough(mPortMixer)) {
1792  bool playthrough = false;
1793 
1794  mPreviousHWPlaythrough = Px_GetPlaythrough(mPortMixer);
1795 
1796  // Bug 388. Feature not supported.
1797  //gPrefs->Read(wxT("/AudioIO/Playthrough"), &playthrough, false);
1798  if (playthrough)
1799  Px_SetPlaythrough(mPortMixer, 1.0);
1800  else
1801  Px_SetPlaythrough(mPortMixer, 0.0);
1802  }
1803  }
1804  #endif
1805  }
1806 #endif
1807 
1808 #ifdef EXPERIMENTAL_MIDI_OUT
1809  // We use audio latency to estimate how far ahead of DACS we are writing
1810  if (mPortStreamV19 != NULL && mLastPaError == paNoError) {
1811  const PaStreamInfo* info = Pa_GetStreamInfo(mPortStreamV19);
1812  // this is an initial guess, but for PA/Linux/ALSA it's wrong and will be
1813  // updated with a better value:
1814  mAudioOutLatency = info->outputLatency;
1815  mSystemMinusAudioTimePlusLatency += mAudioOutLatency;
1816  }
1817 #endif
1818 
1819  return (mLastPaError == paNoError);
1820 }
1821 
1822 void AudioIO::StartMonitoring(double sampleRate)
1823 {
1824  if ( mPortStreamV19 || mStreamToken )
1825  return;
1826 
1827  bool success;
1828  long captureChannels;
1829  auto captureFormat = QualityPrefs::SampleFormatChoice();
1830  gPrefs->Read(wxT("/AudioIO/RecordChannels"), &captureChannels, 2L);
1831  gPrefs->Read(wxT("/AudioIO/SWPlaythrough"), &mSoftwarePlaythrough, false);
1832  int playbackChannels = 0;
1833 
1835  playbackChannels = 2;
1836 
1837  // FIXME: TRAP_ERR StartPortAudioStream (a PaError may be present)
1838  // but StartPortAudioStream function only returns true or false.
1839  mUsingAlsa = false;
1840  success = StartPortAudioStream(sampleRate, (unsigned int)playbackChannels,
1841  (unsigned int)captureChannels,
1842  captureFormat);
1843  // TODO: Check return value of success.
1844  (void)success;
1845 
1846  wxCommandEvent e(EVT_AUDIOIO_MONITOR);
1847  e.SetEventObject(mOwningProject);
1848  e.SetInt(true);
1849  wxTheApp->ProcessEvent(e);
1850 
1851  // FIXME: TRAP_ERR PaErrorCode 'noted' but not reported in StartMonitoring.
1852  // Now start the PortAudio stream!
1853  // TODO: ? Factor out and reuse error reporting code from end of
1854  // AudioIO::StartStream?
1855  mLastPaError = Pa_StartStream( mPortStreamV19 );
1856 
1857  // Update UI display only now, after all possibilities for error are past.
1858  if ((mLastPaError == paNoError) && mListener) {
1859  // advertise the chosen I/O sample rate to the UI
1860  mListener->OnAudioIORate((int)mRate);
1861  }
1862 }
1863 
1865  double t0, double t1,
1866  const AudioIOStartStreamOptions &options)
1867 {
1868  mLostSamples = 0;
1869  mLostCaptureIntervals.clear();
1870  mDetectDropouts =
1871  gPrefs->Read( WarningDialogKey(wxT("DropoutDetected")), true ) != 0;
1872  auto cleanup = finally ( [this] { ClearRecordingException(); } );
1873 
1874  if( IsBusy() )
1875  return 0;
1876 
1877  const auto &sampleRate = options.rate;
1878 
1879  // We just want to set mStreamToken to -1 - this way avoids
1880  // an extremely rare but possible race condition, if two functions
1881  // somehow called StartStream at the same time...
1882  mStreamToken--;
1883  if (mStreamToken != -1)
1884  return 0;
1885 
1886  // TODO: we don't really need to close and reopen stream if the
1887  // format matches; however it's kind of tricky to keep it open...
1888  //
1889  // if (sampleRate == mRate &&
1890  // playbackChannels == mNumPlaybackChannels &&
1891  // captureChannels == mNumCaptureChannels &&
1892  // captureFormat == mCaptureFormat) {
1893 
1894  if (mPortStreamV19) {
1895  StopStream();
1896  while(mPortStreamV19)
1897  wxMilliSleep( 50 );
1898  }
1899 
1900 #ifdef __WXGTK__
1901  // Detect whether ALSA is the chosen host, and do the various involved MIDI
1902  // timing compensations only then.
1903  mUsingAlsa = (gPrefs->Read(wxT("/AudioIO/Host"), wxT("")) == "ALSA");
1904 #endif
1905 
1906  gPrefs->Read(wxT("/AudioIO/SWPlaythrough"), &mSoftwarePlaythrough, false);
1907  gPrefs->Read(wxT("/AudioIO/SoundActivatedRecord"), &mPauseRec, false);
1908  int silenceLevelDB;
1909  gPrefs->Read(wxT("/AudioIO/SilenceLevel"), &silenceLevelDB, -50);
1910  int dBRange;
1911  dBRange = gPrefs->Read(ENV_DB_KEY, ENV_DB_RANGE);
1912  if(silenceLevelDB < -dBRange)
1913  {
1914  silenceLevelDB = -dBRange + 3; // meter range was made smaller than SilenceLevel
1915  gPrefs->Write(ENV_DB_KEY, dBRange); // so set SilenceLevel reasonable
1916  gPrefs->Flush();
1917  }
1918  mSilenceLevel = (silenceLevelDB + dBRange)/(double)dBRange; // meter goes -dBRange dB -> 0dB
1919 
1920  if ( !tracks.captureTracks.empty() ) {
1921  // It does not make sense to apply the time warp during overdub recording,
1922  // which defeats the purpose of making the recording synchronized with
1923  // the existing audio. (Unless we figured out the inverse warp of the
1924  // captured samples in real time.)
1925  // So just quietly ignore the time track.
1926  mTimeTrack = nullptr;
1927  }
1928  else {
1929  mTimeTrack = options.timeTrack;
1930  }
1931 
1932  // Clamp pre-roll so we don't play before time 0
1933  const auto preRoll = std::max(0.0, std::min(t0, options.preRoll));
1934  mT0 = t0 - preRoll;
1935  mT1 = t1;
1936  mRecordingSchedule = {};
1937  mRecordingSchedule.mPreRoll = preRoll;
1939  (gPrefs->ReadDouble(wxT("/AudioIO/LatencyCorrection"),
1941  / 1000.0;
1942  mRecordingSchedule.mDuration = t1 - t0;
1943  if (tracks.captureTracks.size() > 0)
1944  // adjust mT1 so that we don't give paComplete too soon to fill up the
1945  // desired length of recording
1947  if (options.pCrossfadeData)
1949 
1950  mListener = options.listener;
1951  mRate = sampleRate;
1952  mTime = mT0;
1953  mSeek = 0;
1955  mCaptureTracks = tracks.captureTracks;
1957 #ifdef EXPERIMENTAL_MIDI_OUT
1958  mMidiPlaybackTracks = tracks.midiTracks;
1959 #endif
1960 
1961  bool commit = false;
1962  auto cleanupTracks = finally([&]{
1963  if (!commit) {
1964  // Don't keep unnecessary shared pointers to tracks
1965  mPlaybackTracks.clear();
1966  mCaptureTracks.clear();
1967 #ifdef EXPERIMENTAL_MIDI_OUT
1968  mMidiPlaybackTracks.clear();
1969 #endif
1970  }
1971  });
1972 
1976 
1977  mPlaybackBuffers.reset();
1978  mPlaybackMixers.reset();
1979  mCaptureBuffers.reset();
1980  mResample.reset();
1981 
1982  double playbackTime = 4.0;
1983 
1984 #ifdef EXPERIMENTAL_MIDI_OUT
1985  streamStartTime = 0;
1986  streamStartTime = SystemTime(mUsingAlsa);
1987 #endif
1988 
1989 #ifdef EXPERIMENTAL_SCRUBBING_SUPPORT
1990  bool scrubbing = (options.pScrubbingOptions != nullptr);
1991 
1992  // Scrubbing is not compatible with looping or recording or a time track!
1993  if (scrubbing)
1994  {
1995  const auto &scrubOptions = *options.pScrubbingOptions;
1996 
1997  if (mCaptureTracks.size() > 0 ||
1998  mPlayMode == PLAY_LOOPED ||
1999  mTimeTrack != NULL ||
2000  scrubOptions.maxSpeed < ScrubbingOptions::MinAllowedScrubSpeed()) {
2001  wxASSERT(false);
2002  scrubbing = false;
2003  }
2004  else {
2005  playbackTime = lrint(scrubOptions.delay * sampleRate) / sampleRate;
2007  }
2008  }
2009 #endif
2010 
2011  // mWarpedTime and mWarpedLength are irrelevant when scrubbing,
2012  // else they are used in updating mTime,
2013  // and when not scrubbing or playing looped, mTime is also used
2014  // in the test for termination of playback.
2015 
2016  // with ComputeWarpedLength, it is now possible the calculate the warped length with 100% accuracy
2017  // (ignoring accumulated rounding errors during playback) which fixes the 'missing sound at the end' bug
2018  mWarpedTime = 0.0;
2019 #ifdef EXPERIMENTAL_SCRUBBING_SUPPORT
2020  if (scrubbing)
2021  mWarpedLength = 0.0;
2022  else
2023 #endif
2024  {
2025  if (mTimeTrack)
2026  // Following gives negative when mT0 > mT1
2028  else
2029  mWarpedLength = mT1 - mT0;
2030  // PRL allow backwards play
2031  mWarpedLength = fabs(mWarpedLength);
2032  }
2033 
2034  //
2035  // The RingBuffer sizes, and the max amount of the buffer to
2036  // fill at a time, both grow linearly with the number of
2037  // tracks. This allows us to scale up to many tracks without
2038  // killing performance.
2039  //
2040 
2041  // (warped) playback time to produce with each filling of the buffers
2042  // by the Audio thread (except at the end of playback):
2043  // usually, make fillings fewer and longer for less CPU usage.
2044  // But for useful scrubbing, we can't run too far ahead without checking
2045  // mouse input, so make fillings more and shorter.
2046  // What Audio thread produces for playback is then consumed by the PortAudio
2047  // thread, in many smaller pieces.
2048  wxASSERT( playbackTime >= 0 );
2049  mPlaybackSamplesToCopy = playbackTime * mRate;
2050 
2051  // Capacity of the playback buffer.
2052  mPlaybackRingBufferSecs = 10.0;
2053 
2054  mCaptureRingBufferSecs = 4.5 + 0.5 * std::min(size_t(16), mCaptureTracks.size());
2055  mMinCaptureSecsToCopy = 0.2 + 0.2 * std::min(size_t(16), mCaptureTracks.size());
2056 
2057  unsigned int playbackChannels = 0;
2058  unsigned int captureChannels = 0;
2059  sampleFormat captureFormat = floatSample;
2060 
2061  if (tracks.playbackTracks.size() > 0
2062 #ifdef EXPERIMENTAL_MIDI_OUT
2063  || tracks.midiTracks.size() > 0
2064 #endif
2065  )
2066  playbackChannels = 2;
2067 
2069  playbackChannels = 2;
2070 
2071  if (tracks.captureTracks.size() > 0)
2072  {
2073  // For capture, every input channel gets its own track
2074  captureChannels = mCaptureTracks.size();
2075  // I don't deal with the possibility of the capture tracks
2076  // having different sample formats, since it will never happen
2077  // with the current code. This code wouldn't *break* if this
2078  // assumption was false, but it would be sub-optimal. For example,
2079  // if the first track was 16-bit and the second track was 24-bit,
2080  // we would set the sound card to capture in 16 bits and the second
2081  // track wouldn't get the benefit of all 24 bits the card is capable
2082  // of.
2083  captureFormat = mCaptureTracks[0]->GetSampleFormat();
2084 
2085  // Tell project that we are about to start recording
2086  if (mListener)
2088  }
2089 
2090  bool successAudio;
2091 
2092  successAudio = StartPortAudioStream(sampleRate, playbackChannels,
2093  captureChannels, captureFormat);
2094 #ifdef EXPERIMENTAL_MIDI_OUT
2095 
2096  // TODO: it may be that midi out will not work unless audio in or out is
2097  // active -- this would be a bug and may require a change in the
2098  // logic here.
2099 
2100  bool successMidi = true;
2101 
2102  if(!mMidiPlaybackTracks.empty()){
2103  successMidi = StartPortMidiStream();
2104  }
2105 
2106  // On the other hand, if MIDI cannot be opened, we will not complain
2107 #endif
2108 
2109  if (!successAudio) {
2110  if (mListener && captureChannels > 0)
2112  mStreamToken = 0;
2113 
2114  // Don't cause a busy wait in the audio thread after stopping scrubbing
2116 
2117  return 0;
2118  }
2119 
2120  //
2121  // The (audio) stream has been opened successfully (assuming we tried
2122  // to open it). We now proceed to
2123  // allocate the memory structures the stream will need.
2124  //
2125 
2126  bool bDone;
2127  do
2128  {
2129  bDone = true; // assume success
2130  try
2131  {
2132  if( mNumPlaybackChannels > 0 ) {
2133  // Allocate output buffers. For every output track we allocate
2134  // a ring buffer of five seconds
2135  auto playbackBufferSize =
2136  (size_t)lrint(mRate * mPlaybackRingBufferSecs);
2137  auto playbackMixBufferSize =
2139 
2142 
2143  const Mixer::WarpOptions &warpOptions =
2144 #ifdef EXPERIMENTAL_SCRUBBING_SUPPORT
2145  scrubbing
2149  :
2150 #endif
2151  Mixer::WarpOptions(mTimeTrack);
2152 
2153  for (unsigned int i = 0; i < mPlaybackTracks.size(); i++)
2154  {
2155  mPlaybackBuffers[i] = std::make_unique<RingBuffer>(floatSample, playbackBufferSize);
2156 
2157  // MB: use normal time for the end time, not warped time!
2158  WaveTrackConstArray mixTracks;
2159  mixTracks.push_back(mPlaybackTracks[i]);
2160 
2161  double endTime;
2162  if (make_iterator_range(tracks.prerollTracks).contains(mPlaybackTracks[i]))
2163  // Stop playing this track after pre-roll
2164  endTime = t0;
2165  else
2166  // Pass t1 -- not mT1 as may have been adjusted for latency
2167  // -- so that overdub recording stops playing back samples
2168  // at the right time, though transport may continue to record
2169  endTime = t1;
2170 
2171  mPlaybackMixers[i] = std::make_unique<Mixer>
2172  (mixTracks,
2173  // Don't throw for read errors, just play silence:
2174  false,
2175  warpOptions,
2176  mT0,
2177  endTime,
2178  1,
2179  playbackMixBufferSize, false,
2180  mRate, floatSample, false);
2181  mPlaybackMixers[i]->ApplyTrackGains(false);
2182  }
2183  }
2184 
2185  if( mNumCaptureChannels > 0 )
2186  {
2187  // Allocate input buffers. For every input track we allocate
2188  // a ring buffer of five seconds
2189  auto captureBufferSize = (size_t)(mRate * mCaptureRingBufferSecs + 0.5);
2190 
2191  // In the extraordinarily rare case that we can't even afford 100 samples, just give up.
2192  if(captureBufferSize < 100)
2193  {
2195  AudacityMessageBox(_("Out of memory!"));
2196  return 0;
2197  }
2198 
2201  mFactor = sampleRate / mRate;
2202 
2203  for( unsigned int i = 0; i < mCaptureTracks.size(); i++ )
2204  {
2205  mCaptureBuffers[i] = std::make_unique<RingBuffer>
2206  ( mCaptureTracks[i]->GetSampleFormat(),
2207  captureBufferSize );
2208  mResample[i] = std::make_unique<Resample>(true, mFactor, mFactor); // constant rate resampling
2209  }
2210  }
2211  }
2212  catch(std::bad_alloc&)
2213  {
2214  // Oops! Ran out of memory. This is pretty rare, so we'll just
2215  // try deleting everything, halving our buffer size, and try again.
2216  StartStreamCleanup(true);
2217  mPlaybackRingBufferSecs *= 0.5;
2219  mCaptureRingBufferSecs *= 0.5;
2220  mMinCaptureSecsToCopy *= 0.5;
2221  bDone = false;
2222 
2223  // In the extraordinarily rare case that we can't even afford 100 samples, just give up.
2224  auto playbackBufferSize = (size_t)lrint(mRate * mPlaybackRingBufferSecs);
2225  auto playbackMixBufferSize = mPlaybackSamplesToCopy;
2226  if(playbackBufferSize < 100 || playbackMixBufferSize < 100)
2227  {
2229  AudacityMessageBox(_("Out of memory!"));
2230  return 0;
2231  }
2232  }
2233  } while(!bDone);
2234 
2235  if (mNumPlaybackChannels > 0)
2236  {
2238  // Setup for realtime playback at the rate of the realtime
2239  // stream, not the rate of the track.
2240  em.RealtimeInitialize(mRate);
2241 
2242  // The following adds a NEW effect processor for each logical track and the
2243  // group determination should mimic what is done in audacityAudioCallback()
2244  // when calling RealtimeProcess().
2245  int group = 0;
2246  for (size_t i = 0, cnt = mPlaybackTracks.size(); i < cnt; i++)
2247  {
2248  const WaveTrack *vt = gAudioIO->mPlaybackTracks[i].get();
2249 
2250  unsigned chanCnt = 1;
2251  if (vt->GetLinked())
2252  {
2253  i++;
2254  chanCnt++;
2255  }
2256 
2257  // Setup for realtime playback at the rate of the realtime
2258  // stream, not the rate of the track.
2259  em.RealtimeAddProcessor(group++, chanCnt, mRate);
2260  }
2261  }
2262 
2263 #ifdef EXPERIMENTAL_AUTOMATED_INPUT_LEVEL_ADJUSTMENT
2264  AILASetStartTime();
2265 #endif
2266 
2267  if (options.pStartTime)
2268  {
2269  // Calculate the NEW time position
2270  mTime = std::max(mT0, std::min(mT1, *options.pStartTime));
2271  // Reset mixer positions for all playback tracks
2272  unsigned numMixers = mPlaybackTracks.size();
2273  for (unsigned ii = 0; ii < numMixers; ++ii)
2274  mPlaybackMixers[ii]->Reposition(mTime);
2275  if(mTimeTrack)
2277  else
2278  mWarpedTime = mTime - mT0;
2279  }
2280 
2281 #ifdef EXPERIMENTAL_SCRUBBING_SUPPORT
2282  if (scrubbing)
2283  {
2284  const auto &scrubOptions = *options.pScrubbingOptions;
2285  mScrubQueue =
2286  std::make_unique<ScrubQueue>(mT0, mT1, scrubOptions.startClockTimeMillis,
2287  sampleRate, 2 * scrubOptions.minStutter,
2288  scrubOptions);
2289  mScrubDuration = 0;
2290  mSilentScrub = false;
2291  }
2292  else
2293  mScrubQueue.reset();
2294 #endif
2295 
2296  // We signal the audio thread to call FillBuffers, to prime the RingBuffers
2297  // so that they will have data in them when the stream starts. Having the
2298  // audio thread call FillBuffers here makes the code more predictable, since
2299  // FillBuffers will ALWAYS get called from the Audio thread.
2301 
2302  while( mAudioThreadShouldCallFillBuffersOnce == true ) {
2303  if (mScrubQueue)
2304  mScrubQueue->Nudge();
2305  wxMilliSleep( 50 );
2306  }
2307 
2308  if(mNumPlaybackChannels > 0 || mNumCaptureChannels > 0) {
2309 
2310 #ifdef REALTIME_ALSA_THREAD
2311  // PRL: Do this in hope of less thread scheduling jitter in calls to
2312  // audacityAudioCallback.
2313  // Not needed to make audio playback work smoothly.
2314  // But needed in case we also play MIDI, so that the variable "offset"
2315  // in AudioIO::MidiTime() is a better approximation of the duration
2316  // between the call of audacityAudioCallback and the actual output of
2317  // the first audio sample.
2318  // (Which we should be able to determine from fields of
2319  // PaStreamCallbackTimeInfo, but that seems not to work as documented with
2320  // ALSA.)
2321  if (mUsingAlsa)
2322  // Perhaps we should do this only if also playing MIDI ?
2323  PaAlsa_EnableRealtimeScheduling( mPortStreamV19, 1 );
2324 #endif
2325 
2326  //
2327  // Generate a unique value each time, to be returned to
2328  // clients accessing the AudioIO API, so they can query if they
2329  // are the ones who have reserved AudioIO or not.
2330  //
2331  // It is important to set this before setting the portaudio stream in
2332  // motion -- otherwise it may play an unspecified number of leading
2333  // zeroes.
2335 
2336  // This affects the AudioThread (not the portaudio callback).
2337  // Probably not needed so urgently before portaudio thread start for usual
2338  // playback, since our ring buffers have been primed already with 4 sec
2339  // of audio, but then we might be scrubbing, so do it.
2341 
2342  // Now start the PortAudio stream!
2343  PaError err;
2344  err = Pa_StartStream( mPortStreamV19 );
2345 
2346  if( err != paNoError )
2347  {
2348  mStreamToken = 0;
2350  if (mListener && mNumCaptureChannels > 0)
2353  AudacityMessageBox(LAT1CTOWX(Pa_GetErrorText(err)));
2354  return 0;
2355  }
2356  }
2357 
2358  // Update UI display only now, after all possibilities for error are past.
2359  if (mListener) {
2360  // advertise the chosen I/O sample rate to the UI
2361  mListener->OnAudioIORate((int)mRate);
2362  }
2363 
2364  if (mNumPlaybackChannels > 0)
2365  {
2366  wxCommandEvent e(EVT_AUDIOIO_PLAYBACK);
2367  e.SetEventObject(mOwningProject);
2368  e.SetInt(true);
2369  wxTheApp->ProcessEvent(e);
2370  }
2371 
2372  if (mNumCaptureChannels > 0)
2373  {
2374  wxCommandEvent e(EVT_AUDIOIO_CAPTURE);
2375  e.SetEventObject(mOwningProject);
2376  e.SetInt(true);
2377  wxTheApp->ProcessEvent(e);
2378  }
2379 
2380  // Enable warning popups for unfound aliased blockfiles.
2382 
2383  commit = true;
2384  return mStreamToken;
2385 }
2386 
2387 void AudioIO::StartStreamCleanup(bool bOnlyBuffers)
2388 {
2389  if (mNumPlaybackChannels > 0)
2390  {
2392  }
2393 
2394  mPlaybackBuffers.reset();
2395  mPlaybackMixers.reset();
2396  mCaptureBuffers.reset();
2397  mResample.reset();
2398 
2399  if(!bOnlyBuffers)
2400  {
2401  Pa_AbortStream( mPortStreamV19 );
2402  Pa_CloseStream( mPortStreamV19 );
2403  mPortStreamV19 = NULL;
2404  mStreamToken = 0;
2405  }
2406 
2407 #ifdef EXPERIMENTAL_SCRUBBING_SUPPORT
2408  mScrubQueue.reset();
2409 #endif
2410 
2411 
2412  // Don't cause a busy wait in the audio thread after stopping scrubbing
2414 }
2415 
2416 #ifdef EXPERIMENTAL_MIDI_OUT
2417 
2418 PmTimestamp MidiTime(void *WXUNUSED(info))
2419 {
2420  return gAudioIO->MidiTime();
2421 }
2422 
2423 // Set up state to iterate NoteTrack events in sequence.
2424 // Sends MIDI control changes up to the starting point mT0
2425 // if send is true. Output is delayed by offset to facilitate
2426 // looping (each iteration is delayed more).
2427 void AudioIO::PrepareMidiIterator(bool send, double offset)
2428 {
2429  int i;
2430  int nTracks = mMidiPlaybackTracks.size();
2431  // instead of initializing with an Alg_seq, we use begin_seq()
2432  // below to add ALL Alg_seq's.
2433  mIterator = std::make_unique<Alg_iterator>(nullptr, false);
2434  // Iterator not yet intialized, must add each track...
2435  for (i = 0; i < nTracks; i++) {
2436  const auto t = mMidiPlaybackTracks[i].get();
2437  Alg_seq_ptr seq = &t->GetSeq();
2438  // mark sequence tracks as "in use" since we're handing this
2439  // off to another thread and want to make sure nothing happens
2440  // to the data until playback finishes. This is just a sanity check.
2441  seq->set_in_use(true);
2442  mIterator->begin_seq(seq,
2443  // casting away const, but allegro just uses the pointer as an opaque "cookie"
2444  (void*)t, t->GetOffset() + offset);
2445  }
2446  GetNextEvent(); // prime the pump for FillMidiBuffers
2447 
2448  // Start MIDI from current cursor position
2449  mSendMidiState = true;
2450  while (mNextEvent &&
2451  mNextEventTime < mT0 + offset) {
2452  if (send) OutputEvent();
2453  GetNextEvent();
2454  }
2455  mSendMidiState = false;
2456 }
2457 
2458 bool AudioIO::StartPortMidiStream()
2459 {
2460  int i;
2461  int nTracks = mMidiPlaybackTracks.size();
2462  // Only start MIDI stream if there is an open track
2463  if (nTracks == 0)
2464  return false;
2465 
2466  //wxPrintf("StartPortMidiStream: mT0 %g mTime %g\n",
2467  // gAudioIO->mT0, gAudioIO->mTime);
2468 
2469  /* get midi playback device */
2470  PmDeviceID playbackDevice = Pm_GetDefaultOutputDeviceID();
2471  wxString playbackDeviceName = gPrefs->Read(wxT("/MidiIO/PlaybackDevice"),
2472  wxT(""));
2473  mSynthLatency = gPrefs->Read(wxT("/MidiIO/SynthLatency"),
2475  if (wxStrcmp(playbackDeviceName, wxT("")) != 0) {
2476  for (i = 0; i < Pm_CountDevices(); i++) {
2477  const PmDeviceInfo *info = Pm_GetDeviceInfo(i);
2478  if (!info) continue;
2479  if (!info->output) continue;
2480  wxString interf = wxSafeConvertMB2WX(info->interf);
2481  wxString name = wxSafeConvertMB2WX(info->name);
2482  interf.Append(wxT(": ")).Append(name);
2483  if (wxStrcmp(interf, playbackDeviceName) == 0) {
2484  playbackDevice = i;
2485  }
2486  }
2487  } // (else playback device has Pm_GetDefaultOuputDeviceID())
2488 
2489  /* open output device */
2490  mLastPmError = Pm_OpenOutput(&mMidiStream,
2491  playbackDevice,
2492  NULL,
2493  0,
2494  &::MidiTime,
2495  NULL,
2497  if (mLastPmError == pmNoError) {
2498  mMidiStreamActive = true;
2499  mMidiPaused = false;
2500  mMidiLoopPasses = 0;
2501  mMidiOutputComplete = false;
2502  mMaxMidiTimestamp = 0;
2503  PrepareMidiIterator();
2504 
2505  // It is ok to call this now, but do not send timestamped midi
2506  // until after the first audio callback, which provides necessary
2507  // data for MidiTime().
2508  Pm_Synchronize(mMidiStream); // start using timestamps
2509  // start midi output flowing (pending first audio callback)
2510  mMidiThreadFillBuffersLoopRunning = true;
2511  }
2512  return (mLastPmError == pmNoError);
2513 }
2514 #endif
2515 
2517 {
2518  return mOwningProject == NULL || mOwningProject == project;
2519 }
2520 
2522 {
2523  if (!mOwningProject || mOwningProject == project)
2524  {
2525  if (meter)
2526  {
2527  mInputMeter = meter;
2528  mInputMeter->Reset(mRate, true);
2529  }
2530  else
2531  mInputMeter.Release();
2532  }
2533 }
2534 
2536 {
2537  if (!mOwningProject || mOwningProject == project)
2538  {
2539  mOutputMeter = meter;
2540  if (mOutputMeter)
2541  {
2542  mOutputMeter->Reset(mRate, true);
2543  }
2544  }
2545 }
2546 
2548 {
2549  if (mInputMeter)
2550  mInputMeter->Reset(mRate, true);
2551  if (mOutputMeter)
2552  mOutputMeter->Reset(mRate, true);
2553 
2554  AudacityProject* pProj = GetActiveProject();
2555  MixerBoard* pMixerBoard = pProj->GetMixerBoard();
2556  if (pMixerBoard)
2557  pMixerBoard->ResetMeters(true);
2558 
2559  mUpdateMeters = true;
2560 }
2561 
2563 {
2564  auto cleanup = finally ( [this] {
2566  mRecordingSchedule = {}; // free arrays
2567  } );
2568 
2569  if( mPortStreamV19 == NULL
2570 #ifdef EXPERIMENTAL_MIDI_OUT
2571  && mMidiStream == NULL
2572 #endif
2573  )
2574  return;
2575 
2576  if( Pa_IsStreamStopped( mPortStreamV19 )
2577 #ifdef EXPERIMENTAL_MIDI_OUT
2578  && !mMidiStreamActive
2579 #endif
2580  )
2581  return;
2582 
2583  wxMutexLocker locker(mSuspendAudioThread);
2584 
2585  // No longer need effects processing
2586  if (mNumPlaybackChannels > 0)
2587  {
2589  }
2590 
2591  //
2592  // We got here in one of two ways:
2593  //
2594  // 1. The user clicked the stop button and we therefore want to stop
2595  // as quickly as possible. So we use AbortStream(). If this is
2596  // the case the portaudio stream is still in the Running state
2597  // (see PortAudio state machine docs).
2598  //
2599  // 2. The callback told PortAudio to stop the stream since it had
2600  // reached the end of the selection. The UI thread discovered
2601  // this by noticing that AudioIO::IsActive() returned false.
2602  // IsActive() (which calls Pa_GetStreamActive()) will not return
2603  // false until all buffers have finished playing, so we can call
2604  // AbortStream without losing any samples. If this is the case
2605  // we are in the "callback finished state" (see PortAudio state
2606  // machine docs).
2607  //
2608  // The moral of the story: We can call AbortStream safely, without
2609  // losing samples.
2610  //
2611  // DMM: This doesn't seem to be true; it seems to be necessary to
2612  // call StopStream if the callback brought us here, and AbortStream
2613  // if the user brought us here.
2614  //
2615 
2617  if (mScrubQueue)
2618  mScrubQueue->Nudge();
2619 
2620  // Audacity can deadlock if it tries to update meters while
2621  // we're stopping PortAudio (because the meter updating code
2622  // tries to grab a UI mutex while PortAudio tries to join a
2623  // pthread). So we tell the callback to stop updating meters,
2624  // and wait until the callback has left this part of the code
2625  // if it was already there.
2626  mUpdateMeters = false;
2627  while(mUpdatingMeters) {
2628  ::wxSafeYield();
2629  wxMilliSleep( 50 );
2630  }
2631 
2632  // Turn off HW playthrough if PortMixer is being used
2633 
2634  #if defined(USE_PORTMIXER)
2635  if( mPortMixer ) {
2636  #if __WXMAC__
2637  if (Px_SupportsPlaythrough(mPortMixer) && mPreviousHWPlaythrough >= 0.0)
2638  Px_SetPlaythrough(mPortMixer, mPreviousHWPlaythrough);
2639  mPreviousHWPlaythrough = -1.0;
2640  #endif
2641  }
2642  #endif
2643 
2644  if (mPortStreamV19) {
2645  Pa_AbortStream( mPortStreamV19 );
2646  Pa_CloseStream( mPortStreamV19 );
2647  mPortStreamV19 = NULL;
2648  }
2649 
2650  if (mNumPlaybackChannels > 0)
2651  {
2652  wxCommandEvent e(EVT_AUDIOIO_PLAYBACK);
2653  e.SetEventObject(mOwningProject);
2654  e.SetInt(false);
2655  wxTheApp->ProcessEvent(e);
2656  }
2657 
2658  if (mNumCaptureChannels > 0)
2659  {
2660  wxCommandEvent e(mStreamToken == 0 ? EVT_AUDIOIO_MONITOR : EVT_AUDIOIO_CAPTURE);
2661  e.SetEventObject(mOwningProject);
2662  e.SetInt(false);
2663  wxTheApp->ProcessEvent(e);
2664  }
2665 
2666 #ifdef EXPERIMENTAL_MIDI_OUT
2667  /* Stop Midi playback */
2668  if ( mMidiStream ) {
2669 
2670  mMidiStreamActive = false;
2671 
2672 #ifdef USE_MIDI_THREAD
2673  mMidiThreadFillBuffersLoopRunning = false; // stop output to stream
2674  // but output is in another thread. Wait for output to stop...
2675  while (mMidiThreadFillBuffersLoopActive) {
2676  wxMilliSleep(1);
2677  }
2678 #endif
2679 
2680  mMidiOutputComplete = true;
2681 
2682  // now we can assume "ownership" of the mMidiStream
2683  // if output in progress, send all off, etc.
2684  AllNotesOff();
2685  // AllNotesOff() should be sufficient to stop everything, but
2686  // in Linux, if you Pm_Close() immediately, it looks like
2687  // messages are dropped. ALSA then seems to send All Sound Off
2688  // and Reset All Controllers messages, but not all synthesizers
2689  // respond to these messages. This is probably a bug in PortMidi
2690  // if the All Off messages do not get out, but for security,
2691  // delay a bit so that messages can be delivered before closing
2692  // the stream. Add 2ms of "padding" to avoid any rounding errors.
2693  while (mMaxMidiTimestamp + 2 > MidiTime()) {
2694  wxMilliSleep(1); // deliver the all-off messages
2695  }
2696  Pm_Close(mMidiStream);
2697  mMidiStream = NULL;
2698  mIterator->end();
2699 
2700  // set in_use flags to false
2701  int nTracks = mMidiPlaybackTracks.size();
2702  for (int i = 0; i < nTracks; i++) {
2703  const auto t = mMidiPlaybackTracks[i].get();
2704  Alg_seq_ptr seq = &t->GetSeq();
2705  seq->set_in_use(false);
2706  }
2707 
2708  mIterator.reset(); // just in case someone tries to reference it
2709  }
2710 #endif
2711 
2712  // If there's no token, we were just monitoring, so we can
2713  // skip this next part...
2714  if (mStreamToken > 0) {
2715  // In either of the above cases, we want to make sure that any
2716  // capture data that made it into the PortAudio callback makes it
2717  // to the target WaveTrack. To do this, we ask the audio thread to
2718  // call FillBuffers one last time (it normally would not do so since
2719  // Pa_GetStreamActive() would now return false
2721 
2722  while( mAudioThreadShouldCallFillBuffersOnce == true )
2723  {
2724  // LLL: Experienced recursive yield here...once.
2725  wxGetApp().Yield(true); // Pass true for onlyIfNeeded to avoid recursive call error.
2726  if (mScrubQueue)
2727  mScrubQueue->Nudge();
2728  wxMilliSleep( 50 );
2729  }
2730 
2731  //
2732  // Everything is taken care of. Now, just free all the resources
2733  // we allocated in StartStream()
2734  //
2735 
2736  if (mPlaybackTracks.size() > 0)
2737  {
2738  mPlaybackBuffers.reset();
2739  mPlaybackMixers.reset();
2740  }
2741 
2742  //
2743  // Offset all recorded tracks to account for latency
2744  //
2745  if (mCaptureTracks.size() > 0)
2746  {
2747  mCaptureBuffers.reset();
2748  mResample.reset();
2749 
2750  //
2751  // We only apply latency correction when we actually played back
2752  // tracks during the recording. If we did not play back tracks,
2753  // there's nothing we could be out of sync with. This also covers the
2754  // case that we do not apply latency correction when recording the
2755  // first track in a project.
2756  //
2757 
2758  for (unsigned int i = 0; i < mCaptureTracks.size(); i++) {
2759  // The calls to Flush
2760  // may cause exceptions because of exhaustion of disk space.
2761  // Stop those exceptions here, or else they propagate through too
2762  // many parts of Audacity that are not effects or editing
2763  // operations. GuardedCall ensures that the user sees a warning.
2764 
2765  // Also be sure to Flush each track, at the top of the guarded call,
2766  // relying on the guarantee that the track will be left in a flushed
2767  // state, though the append buffer may be lost.
2768 
2769  GuardedCall( [&] {
2770  WaveTrack* track = mCaptureTracks[i].get();
2771 
2772  // use NOFAIL-GUARANTEE that track is flushed,
2773  // PARTIAL-GUARANTEE that some initial length of the recording
2774  // is saved.
2775  // See comments in FillBuffers().
2776  track->Flush();
2777  } );
2778  }
2779 
2780  for (auto &interval : mLostCaptureIntervals) {
2781  auto &start = interval.first;
2782  auto duration = interval.second;
2783  for (auto &track : mCaptureTracks) {
2784  GuardedCall([&] {
2785  track->SyncLockAdjust(start, start + duration);
2786  });
2787  }
2788  }
2789 
2791  ControlToolBar *bar = p->GetControlToolBar();
2792  bar->CommitRecording();
2793  }
2794  }
2795 
2796  if (mInputMeter)
2797  mInputMeter->Reset(mRate, false);
2798 
2799  if (mOutputMeter)
2800  mOutputMeter->Reset(mRate, false);
2801 
2802  MixerBoard* pMixerBoard = mOwningProject->GetMixerBoard();
2803  if (pMixerBoard)
2804  pMixerBoard->ResetMeters(false);
2805 
2806  mInputMeter.Release();
2807  mOutputMeter = NULL;
2808  mOwningProject = NULL;
2809 
2810  if (mListener && mNumCaptureChannels > 0)
2812 
2813  //
2814  // Only set token to 0 after we're totally finished with everything
2815  //
2816  mStreamToken = 0;
2817 
2818  mNumCaptureChannels = 0;
2820 
2821  mPlaybackTracks.clear();
2822  mCaptureTracks.clear();
2823 #ifdef HAVE_MIDI
2824  mMidiPlaybackTracks.clear();
2825 #endif
2826 
2827 #ifdef EXPERIMENTAL_SCRUBBING_SUPPORT
2828  mScrubQueue.reset();
2829 #endif
2830 
2831  if (mListener) {
2832  // Tell UI to hide sample rate
2834  }
2835 
2836  // Don't cause a busy wait in the audio thread after stopping scrubbing
2838 }
2839 
2840 void AudioIO::SetPaused(bool state)
2841 {
2842  if (state != mPaused)
2843  {
2844  if (state)
2845  {
2847  }
2848  else
2849  {
2851  }
2852  }
2853 
2854  mPaused = state;
2855 }
2856 
2858 {
2859  return mPaused;
2860 }
2861 
2862 #ifdef EXPERIMENTAL_SCRUBBING_SUPPORT
2864  (double endTimeOrSpeed, const ScrubbingOptions &options)
2865 {
2866  if (mScrubQueue)
2867  return mScrubQueue->Producer(endTimeOrSpeed, options);
2868  else
2869  return false;
2870 }
2871 
2873 {
2874  if (mScrubQueue)
2875  return mScrubQueue->LastTimeInQueue();
2876  else
2877  return -1.0;
2878 }
2879 
2880 #endif
2881 
2883 {
2884  if (mStreamToken != 0)
2885  return true;
2886 
2887  return false;
2888 }
2889 
2891 {
2892  bool isActive = false;
2893  // JKC: Not reporting any Pa error, but that looks OK.
2894  if( mPortStreamV19 )
2895  isActive = (Pa_IsStreamActive( mPortStreamV19 ) > 0);
2896 
2897 #ifdef EXPERIMENTAL_MIDI_OUT
2898  if( mMidiStreamActive && !mMidiOutputComplete )
2899  isActive = true;
2900 #endif
2901  return isActive;
2902 }
2903 
2905 {
2906  return (this->IsStreamActive() && this->IsAudioTokenActive(token));
2907 }
2908 
2910 {
2911  return ( token > 0 && token == mStreamToken );
2912 }
2913 
2915 {
2916  return ( mPortStreamV19 && mStreamToken==0 );
2917 }
2918 
2919 double AudioIO::LimitStreamTime(double absoluteTime) const
2920 {
2921  // Allows for forward or backward play
2922  if (ReversedTime())
2923  return std::max(mT1, std::min(mT0, absoluteTime));
2924  else
2925  return std::max(mT0, std::min(mT1, absoluteTime));
2926 }
2927 
2928 double AudioIO::NormalizeStreamTime(double absoluteTime) const
2929 {
2930  // dmazzoni: This function is needed for two reasons:
2931  // One is for looped-play mode - this function makes sure that the
2932  // position indicator keeps wrapping around. The other reason is
2933  // more subtle - it's because PortAudio can query the hardware for
2934  // the current stream time, and this query is not always accurate.
2935  // Sometimes it's a little behind or ahead, and so this function
2936  // makes sure that at least we clip it to the selection.
2937  //
2938  // msmeyer: There is also the possibility that we are using "cut preview"
2939  // mode. In this case, we should jump over a defined "gap" in the
2940  // audio.
2941 
2942 #ifdef EXPERIMENTAL_SCRUBBING_SUPPORT
2943  // Limit the time between t0 and t1 if not scrubbing.
2944  // Should the limiting be necessary in any play mode if there are no bugs?
2945  if (mPlayMode != PLAY_SCRUB)
2946 #endif
2947  absoluteTime = LimitStreamTime(absoluteTime);
2948 
2949  if (mCutPreviewGapLen > 0)
2950  {
2951  // msmeyer: We're in cut preview mode, so if we are on the right
2952  // side of the gap, we jump over it.
2953  if (absoluteTime > mCutPreviewGapStart)
2954  absoluteTime += mCutPreviewGapLen;
2955  }
2956 
2957  return absoluteTime;
2958 }
2959 
2961 {
2962  if( !IsStreamActive() )
2963  return BAD_STREAM_TIME;
2964 
2965  return NormalizeStreamTime(mTime);
2966 }
2967 
2968 
2969 std::vector<long> AudioIO::GetSupportedPlaybackRates(int devIndex, double rate)
2970 {
2971  if (devIndex == -1)
2972  { // weren't given a device index, get the prefs / default one
2973  devIndex = getPlayDevIndex();
2974  }
2975 
2976  // Check if we can use the cached rates
2977  if (mCachedPlaybackIndex != -1 && devIndex == mCachedPlaybackIndex
2978  && (rate == 0.0 || make_iterator_range(mCachedPlaybackRates).contains(rate)))
2979  {
2980  return mCachedPlaybackRates;
2981  }
2982 
2983  std::vector<long> supported;
2984  int irate = (int)rate;
2985  const PaDeviceInfo* devInfo = NULL;
2986  int i;
2987 
2988  devInfo = Pa_GetDeviceInfo(devIndex);
2989 
2990  if (!devInfo)
2991  {
2992  wxLogDebug(wxT("GetSupportedPlaybackRates() Could not get device info!"));
2993  return supported;
2994  }
2995 
2996  // LLL: Remove when a proper method of determining actual supported
2997  // DirectSound rate is devised.
2998  const PaHostApiInfo* hostInfo = Pa_GetHostApiInfo(devInfo->hostApi);
2999  bool isDirectSound = (hostInfo && hostInfo->type == paDirectSound);
3000 
3001  PaStreamParameters pars;
3002 
3003  pars.device = devIndex;
3004  pars.channelCount = 1;
3005  pars.sampleFormat = paFloat32;
3006  pars.suggestedLatency = devInfo->defaultHighOutputLatency;
3007  pars.hostApiSpecificStreamInfo = NULL;
3008 
3009  // JKC: PortAudio Errors handled OK here. No need to report them
3010  for (i = 0; i < NumRatesToTry; i++)
3011  {
3012  // LLL: Remove when a proper method of determining actual supported
3013  // DirectSound rate is devised.
3014  if (!(isDirectSound && RatesToTry[i] > 200000))
3015  if (Pa_IsFormatSupported(NULL, &pars, RatesToTry[i]) == 0)
3016  supported.push_back(RatesToTry[i]);
3017  }
3018 
3019  if (irate != 0 && !make_iterator_range(supported).contains(irate))
3020  {
3021  // LLL: Remove when a proper method of determining actual supported
3022  // DirectSound rate is devised.
3023  if (!(isDirectSound && RatesToTry[i] > 200000))
3024  if (Pa_IsFormatSupported(NULL, &pars, irate) == 0)
3025  supported.push_back(irate);
3026  }
3027 
3028  return supported;
3029 }
3030 
3031 std::vector<long> AudioIO::GetSupportedCaptureRates(int devIndex, double rate)
3032 {
3033  if (devIndex == -1)
3034  { // not given a device, look up in prefs / default
3035  devIndex = getRecordDevIndex();
3036  }
3037 
3038  // Check if we can use the cached rates
3039  if (mCachedCaptureIndex != -1 && devIndex == mCachedCaptureIndex
3040  && (rate == 0.0 || make_iterator_range(mCachedCaptureRates).contains(rate)))
3041  {
3042  return mCachedCaptureRates;
3043  }
3044 
3045  std::vector<long> supported;
3046  int irate = (int)rate;
3047  const PaDeviceInfo* devInfo = NULL;
3048  int i;
3049 
3050  devInfo = Pa_GetDeviceInfo(devIndex);
3051 
3052  if (!devInfo)
3053  {
3054  wxLogDebug(wxT("GetSupportedCaptureRates() Could not get device info!"));
3055  return supported;
3056  }
3057 
3058  double latencyDuration = DEFAULT_LATENCY_DURATION;
3059  long recordChannels = 1;
3060  gPrefs->Read(wxT("/AudioIO/LatencyDuration"), &latencyDuration);
3061  gPrefs->Read(wxT("/AudioIO/RecordChannels"), &recordChannels);
3062 
3063  // LLL: Remove when a proper method of determining actual supported
3064  // DirectSound rate is devised.
3065  const PaHostApiInfo* hostInfo = Pa_GetHostApiInfo(devInfo->hostApi);
3066  bool isDirectSound = (hostInfo && hostInfo->type == paDirectSound);
3067 
3068  PaStreamParameters pars;
3069 
3070  pars.device = devIndex;
3071  pars.channelCount = recordChannels;
3072  pars.sampleFormat = paFloat32;
3073  pars.suggestedLatency = latencyDuration / 1000.0;
3074  pars.hostApiSpecificStreamInfo = NULL;
3075 
3076  for (i = 0; i < NumRatesToTry; i++)
3077  {
3078  // LLL: Remove when a proper method of determining actual supported
3079  // DirectSound rate is devised.
3080  if (!(isDirectSound && RatesToTry[i] > 200000))
3081  if (Pa_IsFormatSupported(&pars, NULL, RatesToTry[i]) == 0)
3082  supported.push_back(RatesToTry[i]);
3083  }
3084 
3085  if (irate != 0 && !make_iterator_range(supported).contains(irate))
3086  {
3087  // LLL: Remove when a proper method of determining actual supported
3088  // DirectSound rate is devised.
3089  if (!(isDirectSound && RatesToTry[i] > 200000))
3090  if (Pa_IsFormatSupported(&pars, NULL, irate) == 0)
3091  supported.push_back(irate);
3092  }
3093 
3094  return supported;
3095 }
3096 
3097 std::vector<long> AudioIO::GetSupportedSampleRates(int playDevice, int recDevice, double rate)
3098 {
3099  // Not given device indices, look up prefs
3100  if (playDevice == -1) {
3101  playDevice = getPlayDevIndex();
3102  }
3103  if (recDevice == -1) {
3104  recDevice = getRecordDevIndex();
3105  }
3106 
3107  // Check if we can use the cached rates
3108  if (mCachedPlaybackIndex != -1 && mCachedCaptureIndex != -1 &&
3109  playDevice == mCachedPlaybackIndex &&
3110  recDevice == mCachedCaptureIndex &&
3111  (rate == 0.0 || make_iterator_range(mCachedSampleRates).contains(rate)))
3112  {
3113  return mCachedSampleRates;
3114  }
3115 
3116  auto playback = GetSupportedPlaybackRates(playDevice, rate);
3117  auto capture = GetSupportedCaptureRates(recDevice, rate);
3118  int i;
3119 
3120  // Return only sample rates which are in both arrays
3121  std::vector<long> result;
3122 
3123  for (i = 0; i < (int)playback.size(); i++)
3124  if (make_iterator_range(capture).contains(playback[i]))
3125  result.push_back(playback[i]);
3126 
3127  // If this yields no results, use the default sample rates nevertheless
3128 /* if (result.IsEmpty())
3129  {
3130  for (i = 0; i < NumStandardRates; i++)
3131  result.Add(StandardRates[i]);
3132  }*/
3133 
3134  return result;
3135 }
3136 
3142 {
3143  auto rates = GetSupportedSampleRates();
3144 
3145  if (make_iterator_range(rates).contains(44100))
3146  return 44100;
3147 
3148  if (make_iterator_range(rates).contains(48000))
3149  return 48000;
3150 
3151  // if there are no supported rates, the next bit crashes. So check first,
3152  // and give them a "sensible" value if there are no valid values. They
3153  // will still get an error later, but with any luck may have changed
3154  // something by then. It's no worse than having an invalid default rate
3155  // stored in the preferences, which we don't check for
3156  if (rates.empty()) return 44100;
3157 
3158  return rates.back();
3159 }
3160 
3161 double AudioIO::GetBestRate(bool capturing, bool playing, double sampleRate)
3162 {
3163  // Check if we can use the cached value
3164  if (mCachedBestRateIn != 0.0 && mCachedBestRateIn == sampleRate) {
3165  return mCachedBestRateOut;
3166  }
3167 
3168  // In order to cache the value, all early returns should instead set retval
3169  // and jump to finished
3170  double retval;
3171 
3172  std::vector<long> rates;
3173  if (capturing) wxLogDebug(wxT("AudioIO::GetBestRate() for capture"));
3174  if (playing) wxLogDebug(wxT("AudioIO::GetBestRate() for playback"));
3175  wxLogDebug(wxT("GetBestRate() suggested rate %.0lf Hz"), sampleRate);
3176 
3177  if (capturing && !playing) {
3178  rates = GetSupportedCaptureRates(-1, sampleRate);
3179  }
3180  else if (playing && !capturing) {
3181  rates = GetSupportedPlaybackRates(-1, sampleRate);
3182  }
3183  else { // we assume capturing and playing - the alternative would be a
3184  // bit odd
3185  rates = GetSupportedSampleRates(-1, -1, sampleRate);
3186  }
3187  /* rem rates is the array of hardware-supported sample rates (in the current
3188  * configuration), sampleRate is the Project Rate (desired sample rate) */
3189  long rate = (long)sampleRate;
3190 
3191  if (make_iterator_range(rates).contains(rate)) {
3192  wxLogDebug(wxT("GetBestRate() Returning %.0ld Hz"), rate);
3193  retval = rate;
3194  goto finished;
3195  /* the easy case - the suggested rate (project rate) is in the list, and
3196  * we can just accept that and send back to the caller. This should be
3197  * the case for most users most of the time (all of the time on
3198  * Win MME as the OS does resampling) */
3199  }
3200 
3201  /* if we get here, there is a problem - the project rate isn't supported
3202  * on our hardware, so we can't us it. Need to come up with an alternative
3203  * rate to use. The process goes like this:
3204  * * If there are no rates to pick from, we're stuck and return 0 (error)
3205  * * If there are some rates, we pick the next one higher than the requested
3206  * rate to use.
3207  * * If there aren't any higher, we use the highest available rate */
3208 
3209  if (rates.empty()) {
3210  /* we're stuck - there are no supported rates with this hardware. Error */
3211  wxLogDebug(wxT("GetBestRate() Error - no supported sample rates"));
3212  retval = 0.0;
3213  goto finished;
3214  }
3215  int i;
3216  for (i = 0; i < (int)rates.size(); i++) // for each supported rate
3217  {
3218  if (rates[i] > rate) {
3219  // supported rate is greater than requested rate
3220  wxLogDebug(wxT("GetBestRate() Returning next higher rate - %.0ld Hz"), rates[i]);
3221  retval = rates[i];
3222  goto finished;
3223  }
3224  }
3225 
3226  wxLogDebug(wxT("GetBestRate() Returning highest rate - %.0ld Hz"), rates.back());
3227  retval = rates.back(); // the highest available rate
3228  goto finished;
3229 
3230 finished:
3231  mCachedBestRateIn = sampleRate;
3232  mCachedBestRateOut = retval;
3233  return retval;
3234 }
3235 
3236 
3238 //
3239 // Audio Thread Context
3240 //
3242 
3243 AudioThread::ExitCode AudioThread::Entry()
3244 {
3245  while( !TestDestroy() )
3246  {
3247  // Set LoopActive outside the tests to avoid race condition
3250  {
3251  gAudioIO->FillBuffers();
3253  }
3255  {
3256  gAudioIO->FillBuffers();
3257  }
3259 
3261  // Rely on the Wait() in ScrubQueue::Transformer()
3262  // This allows the scrubbing update interval to be made very short without
3263  // playback becoming intermittent.
3264  }
3265  else {
3266  // Perhaps this too could use a condition variable, for available space in the
3267  // ring buffer, instead of a polling loop? But no harm in doing it this way.
3268  Sleep(10);
3269  }
3270  }
3271 
3272  return 0;
3273 }
3274 
3275 
3276 #ifdef EXPERIMENTAL_MIDI_OUT
3277 MidiThread::ExitCode MidiThread::Entry()
3278 {
3279  while( !TestDestroy() )
3280  {
3281  // Set LoopActive outside the tests to avoid race condition
3282  gAudioIO->mMidiThreadFillBuffersLoopActive = true;
3283  if( gAudioIO->mMidiThreadFillBuffersLoopRunning &&
3284  // mNumFrames signals at least one callback, needed for MidiTime()
3285  gAudioIO->mNumFrames > 0)
3286  {
3287  gAudioIO->FillMidiBuffers();
3288  }
3289  gAudioIO->mMidiThreadFillBuffersLoopActive = false;
3290  Sleep(MIDI_SLEEP);
3291  }
3292  return 0;
3293 }
3294 #endif
3295 
3297 {
3298  auto commonlyAvail = mPlaybackBuffers[0]->AvailForPut();
3299  for (unsigned i = 1; i < mPlaybackTracks.size(); ++i)
3300  commonlyAvail = std::min(commonlyAvail,
3301  mPlaybackBuffers[i]->AvailForPut());
3302  return commonlyAvail;
3303 }
3304 
3306 {
3307  auto commonlyAvail = mCaptureBuffers[0]->AvailForGet();
3308  for (unsigned i = 1; i < mCaptureTracks.size(); ++i)
3309  commonlyAvail = std::min(commonlyAvail,
3310  mCaptureBuffers[i]->AvailForGet());
3311  return commonlyAvail;
3312 }
3313 
3314 #if USE_PORTMIXER
3315 int AudioIO::getRecordSourceIndex(PxMixer *portMixer)
3316 {
3317  int i;
3318  wxString sourceName = gPrefs->Read(wxT("/AudioIO/RecordingSource"), wxT(""));
3319  int numSources = Px_GetNumInputSources(portMixer);
3320  for (i = 0; i < numSources; i++) {
3321  if (sourceName == wxString(wxSafeConvertMB2WX(Px_GetInputSourceName(portMixer, i))))
3322  return i;
3323  }
3324  return -1;
3325 }
3326 #endif
3327 
3328 int AudioIO::getPlayDevIndex(const wxString &devNameArg)
3329 {
3330  wxString devName(devNameArg);
3331  // if we don't get given a device, look up the preferences
3332  if (devName.IsEmpty())
3333  {
3334  devName = gPrefs->Read(wxT("/AudioIO/PlaybackDevice"), wxT(""));
3335  }
3336 
3337  wxString hostName = gPrefs->Read(wxT("/AudioIO/Host"), wxT(""));
3338  PaHostApiIndex hostCnt = Pa_GetHostApiCount();
3339  PaHostApiIndex hostNum;
3340  for (hostNum = 0; hostNum < hostCnt; hostNum++)
3341  {
3342  const PaHostApiInfo *hinfo = Pa_GetHostApiInfo(hostNum);
3343  if (hinfo && wxString(wxSafeConvertMB2WX(hinfo->name)) == hostName)
3344  {
3345  for (PaDeviceIndex hostDevice = 0; hostDevice < hinfo->deviceCount; hostDevice++)
3346  {
3347  PaDeviceIndex deviceNum = Pa_HostApiDeviceIndexToDeviceIndex(hostNum, hostDevice);
3348 
3349  const PaDeviceInfo *dinfo = Pa_GetDeviceInfo(deviceNum);
3350  if (dinfo && DeviceName(dinfo) == devName && dinfo->maxOutputChannels > 0 )
3351  {
3352  // this device name matches the stored one, and works.
3353  // So we say this is the answer and return it
3354  return deviceNum;
3355  }
3356  }
3357 
3358  // The device wasn't found so use the default for this host.
3359  // LL: At this point, preferences and active no longer match.
3360  return hinfo->defaultOutputDevice;
3361  }
3362  }
3363 
3364  // The host wasn't found, so use the default output device.
3365  // FIXME: TRAP_ERR PaErrorCode not handled well (this code is similar to input code
3366  // and the input side has more comments.)
3367 
3368  PaDeviceIndex deviceNum = Pa_GetDefaultOutputDevice();
3369 
3370  // Sometimes PortAudio returns -1 if it cannot find a suitable default
3371  // device, so we just use the first one available
3372  //
3373  // LL: At this point, preferences and active no longer match
3374  //
3375  // And I can't imagine how far we'll get specifying an "invalid" index later
3376  // on...are we certain "0" even exists?
3377  if (deviceNum < 0) {
3378  wxASSERT(false);
3379  deviceNum = 0;
3380  }
3381 
3382  return deviceNum;
3383 }
3384 
3385 int AudioIO::getRecordDevIndex(const wxString &devNameArg)
3386 {
3387  wxString devName(devNameArg);
3388  // if we don't get given a device, look up the preferences
3389  if (devName.IsEmpty())
3390  {
3391  devName = gPrefs->Read(wxT("/AudioIO/RecordingDevice"), wxT(""));
3392  }
3393 
3394  wxString hostName = gPrefs->Read(wxT("/AudioIO/Host"), wxT(""));
3395  PaHostApiIndex hostCnt = Pa_GetHostApiCount();
3396  PaHostApiIndex hostNum;
3397  for (hostNum = 0; hostNum < hostCnt; hostNum++)
3398  {
3399  const PaHostApiInfo *hinfo = Pa_GetHostApiInfo(hostNum);
3400  if (hinfo && wxString(wxSafeConvertMB2WX(hinfo->name)) == hostName)
3401  {
3402  for (PaDeviceIndex hostDevice = 0; hostDevice < hinfo->deviceCount; hostDevice++)
3403  {
3404  PaDeviceIndex deviceNum = Pa_HostApiDeviceIndexToDeviceIndex(hostNum, hostDevice);
3405 
3406  const PaDeviceInfo *dinfo = Pa_GetDeviceInfo(deviceNum);
3407  if (dinfo && DeviceName(dinfo) == devName && dinfo->maxInputChannels > 0 )
3408  {
3409  // this device name matches the stored one, and works.
3410  // So we say this is the answer and return it
3411  return deviceNum;
3412  }
3413  }
3414 
3415  // The device wasn't found so use the default for this host.
3416  // LL: At this point, preferences and active no longer match.
3417  return hinfo->defaultInputDevice;
3418  }
3419  }
3420 
3421  // The host wasn't found, so use the default input device.
3422  // FIXME: TRAP_ERR PaErrorCode not handled well in getRecordDevIndex()
3423  PaDeviceIndex deviceNum = Pa_GetDefaultInputDevice();
3424 
3425  // Sometimes PortAudio returns -1 if it cannot find a suitable default
3426  // device, so we just use the first one available
3427  // PortAudio has an error reporting function. We should log/report the error?
3428  //
3429  // LL: At this point, preferences and active no longer match
3430  //
3431  // And I can't imagine how far we'll get specifying an "invalid" index later
3432  // on...are we certain "0" even exists?
3433  if (deviceNum < 0) {
3434  // JKC: This ASSERT will happen if you run with no config file
3435  // This happens once. Config file will exist on the next run.
3436  // TODO: Look into this a bit more. Could be relevant to blank Device Toolbar.
3437  wxASSERT(false);
3438  deviceNum = 0;
3439  }
3440 
3441  return deviceNum;
3442 }
3443 
3445 {
3446  wxStringOutputStream o;
3447  wxTextOutputStream s(o, wxEOL_UNIX);
3448  wxString e(wxT("\n"));
3449 
3450  if (IsStreamActive()) {
3451  return wxT("Stream is active ... unable to gather information.");
3452  }
3453 
3454 
3455  // FIXME: TRAP_ERR PaErrorCode not handled. 3 instances in GetDeviceInfo().
3456  int recDeviceNum = Pa_GetDefaultInputDevice();
3457  int playDeviceNum = Pa_GetDefaultOutputDevice();
3458  int cnt = Pa_GetDeviceCount();
3459 
3460  wxLogDebug(wxT("Portaudio reports %d audio devices"),cnt);
3461 
3462  s << wxT("==============================") << e;
3463  s << wxT("Default recording device number: ") << recDeviceNum << e;
3464  s << wxT("Default playback device number: ") << playDeviceNum << e;
3465 
3466  wxString recDevice = gPrefs->Read(wxT("/AudioIO/RecordingDevice"), wxT(""));
3467  wxString playDevice = gPrefs->Read(wxT("/AudioIO/PlaybackDevice"), wxT(""));
3468  int j;
3469 
3470  // This gets info on all available audio devices (input and output)
3471  if (cnt <= 0) {
3472  s << wxT("No devices found\n");
3473  return o.GetString();
3474  }
3475 
3476  const PaDeviceInfo* info;
3477 
3478  for (j = 0; j < cnt; j++) {
3479  s << wxT("==============================") << e;
3480 
3481  info = Pa_GetDeviceInfo(j);
3482  if (!info) {
3483  s << wxT("Device info unavailable for: ") << j << wxT("\n");
3484  continue;
3485  }
3486 
3487  wxString name = DeviceName(info);
3488  s << wxT("Device ID: ") << j << e;
3489  s << wxT("Device name: ") << name << e;
3490  s << wxT("Host name: ") << HostName(info) << e;
3491  s << wxT("Recording channels: ") << info->maxInputChannels << e;
3492  s << wxT("Playback channels: ") << info->maxOutputChannels << e;
3493  s << wxT("Low Recording Latency: ") << info->defaultLowInputLatency << e;
3494  s << wxT("Low Playback Latency: ") << info->defaultLowOutputLatency << e;
3495  s << wxT("High Recording Latency: ") << info->defaultHighInputLatency << e;
3496  s << wxT("High Playback Latency: ") << info->defaultHighOutputLatency << e;
3497 
3498  auto rates = GetSupportedPlaybackRates(j, 0.0);
3499 
3500  s << wxT("Supported Rates:") << e;
3501  for (int k = 0; k < (int) rates.size(); k++) {
3502  s << wxT(" ") << (int)rates[k] << e;
3503  }
3504 
3505  if (name == playDevice && info->maxOutputChannels > 0)
3506  playDeviceNum = j;
3507 
3508  if (name == recDevice && info->maxInputChannels > 0)
3509  recDeviceNum = j;
3510 
3511  // Sometimes PortAudio returns -1 if it cannot find a suitable default
3512  // device, so we just use the first one available
3513  if (recDeviceNum < 0 && info->maxInputChannels > 0){
3514  recDeviceNum = j;
3515  }
3516  if (playDeviceNum < 0 && info->maxOutputChannels > 0){
3517  playDeviceNum = j;
3518  }
3519  }
3520 
3521  bool haveRecDevice = (recDeviceNum >= 0);
3522  bool havePlayDevice = (playDeviceNum >= 0);
3523 
3524  s << wxT("==============================") << e;
3525  if(haveRecDevice){
3526  s << wxT("Selected recording device: ") << recDeviceNum << wxT(" - ") << recDevice << e;
3527  }else{
3528  s << wxT("No recording device found for '") << recDevice << wxT("'.") << e;
3529  }
3530  if(havePlayDevice){
3531  s << wxT("Selected playback device: ") << playDeviceNum << wxT(" - ") << playDevice << e;
3532  }else{
3533  s << wxT("No playback device found for '") << playDevice << wxT("'.") << e;
3534  }
3535 
3536  std::vector<long> supportedSampleRates;
3537 
3538  if(havePlayDevice && haveRecDevice){
3539  supportedSampleRates = GetSupportedSampleRates(playDeviceNum, recDeviceNum);
3540 
3541  s << wxT("Supported Rates:") << e;
3542  for (int k = 0; k < (int) supportedSampleRates.size(); k++) {
3543  s << wxT(" ") << (int)supportedSampleRates[k] << e;
3544  }
3545  }else{
3546  s << wxT("Cannot check mutual sample rates without both devices.") << e;
3547  return o.GetString();
3548  }
3549 
3550 #if defined(USE_PORTMIXER)
3551  if (supportedSampleRates.size() > 0)
3552  {
3553  int highestSampleRate = supportedSampleRates.back();
3554  bool EmulateMixerInputVol = true;
3555  bool EmulateMixerOutputVol = true;
3556  float MixerInputVol = 1.0;
3557  float MixerOutputVol = 1.0;
3558 
3559  int error;
3560 
3561  PaStream *stream;
3562 
3563  PaStreamParameters playbackParameters;
3564 
3565  playbackParameters.device = playDeviceNum;
3566  playbackParameters.sampleFormat = paFloat32;
3567  playbackParameters.hostApiSpecificStreamInfo = NULL;
3568  playbackParameters.channelCount = 1;
3569  if (Pa_GetDeviceInfo(playDeviceNum)){
3570  playbackParameters.suggestedLatency =
3571  Pa_GetDeviceInfo(playDeviceNum)->defaultLowOutputLatency;
3572  }
3573  else{
3574  playbackParameters.suggestedLatency = DEFAULT_LATENCY_CORRECTION/1000.0;
3575  }
3576 
3577  PaStreamParameters captureParameters;
3578 
3579  captureParameters.device = recDeviceNum;
3580  captureParameters.sampleFormat = paFloat32;;
3581  captureParameters.hostApiSpecificStreamInfo = NULL;
3582  captureParameters.channelCount = 1;
3583  if (Pa_GetDeviceInfo(recDeviceNum)){
3584  captureParameters.suggestedLatency =
3585  Pa_GetDeviceInfo(recDeviceNum)->defaultLowInputLatency;
3586  }else{
3587  captureParameters.suggestedLatency = DEFAULT_LATENCY_CORRECTION/1000.0;
3588  }
3589 
3590  error = Pa_OpenStream(&stream,
3591  &captureParameters, &playbackParameters,
3592  highestSampleRate, paFramesPerBufferUnspecified,
3593  paClipOff | paDitherOff,
3594  audacityAudioCallback, NULL);
3595 
3596  if (error) {
3597  error = Pa_OpenStream(&stream,
3598  &captureParameters, NULL,
3599  highestSampleRate, paFramesPerBufferUnspecified,
3600  paClipOff | paDitherOff,
3601  audacityAudioCallback, NULL);
3602  }
3603 
3604  if (error) {
3605  s << wxT("Received ") << error << wxT(" while opening devices") << e;
3606  return o.GetString();
3607  }
3608 
3609  PxMixer *PortMixer = Px_OpenMixer(stream, 0);
3610 
3611  if (!PortMixer) {
3612  s << wxT("Unable to open Portmixer") << e;
3613  Pa_CloseStream(stream);
3614  return o.GetString();
3615  }
3616 
3617  s << wxT("==============================") << e;
3618  s << wxT("Available mixers:") << e;
3619 
3620  // FIXME: ? PortMixer errors on query not reported in GetDeviceInfo
3621  cnt = Px_GetNumMixers(stream);
3622  for (int i = 0; i < cnt; i++) {
3623  wxString name = wxSafeConvertMB2WX(Px_GetMixerName(stream, i));
3624  s << i << wxT(" - ") << name << e;
3625  }
3626 
3627  s << wxT("==============================") << e;
3628  s << wxT("Available recording sources:") << e;
3629  cnt = Px_GetNumInputSources(PortMixer);
3630  for (int i = 0; i < cnt; i++) {
3631  wxString name = wxSafeConvertMB2WX(Px_GetInputSourceName(PortMixer, i));
3632  s << i << wxT(" - ") << name << e;
3633  }
3634 
3635  s << wxT("==============================") << e;
3636  s << wxT("Available playback volumes:") << e;
3637  cnt = Px_GetNumOutputVolumes(PortMixer);
3638  for (int i = 0; i < cnt; i++) {
3639  wxString name = wxSafeConvertMB2WX(Px_GetOutputVolumeName(PortMixer, i));
3640  s << i << wxT(" - ") << name << e;
3641  }
3642 
3643  // Determine mixer capabilities - it it doesn't support either
3644  // input or output, we emulate them (by multiplying this value
3645  // by all incoming/outgoing samples)
3646 
3647  MixerOutputVol = Px_GetPCMOutputVolume(PortMixer);
3648  EmulateMixerOutputVol = false;
3649  Px_SetPCMOutputVolume(PortMixer, 0.0);
3650  if (Px_GetPCMOutputVolume(PortMixer) > 0.1)
3651  EmulateMixerOutputVol = true;
3652  Px_SetPCMOutputVolume(PortMixer, 0.2f);
3653  if (Px_GetPCMOutputVolume(PortMixer) < 0.1 ||
3654  Px_GetPCMOutputVolume(PortMixer) > 0.3)
3655  EmulateMixerOutputVol = true;
3656  Px_SetPCMOutputVolume(PortMixer, MixerOutputVol);
3657 
3658  MixerInputVol = Px_GetInputVolume(PortMixer);
3659  EmulateMixerInputVol = false;
3660  Px_SetInputVolume(PortMixer, 0.0);
3661  if (Px_GetInputVolume(PortMixer) > 0.1)
3662  EmulateMixerInputVol = true;
3663  Px_SetInputVolume(PortMixer, 0.2f);
3664  if (Px_GetInputVolume(PortMixer) < 0.1 ||
3665  Px_GetInputVolume(PortMixer) > 0.3)
3666  EmulateMixerInputVol = true;
3667  Px_SetInputVolume(PortMixer, MixerInputVol);
3668 
3669  Pa_CloseStream(stream);
3670 
3671  s << wxT("==============================") << e;
3672  s << wxT("Recording volume is ") << (EmulateMixerInputVol? wxT("emulated"): wxT("native")) << e;
3673  s << wxT("Playback volume is ") << (EmulateMixerOutputVol? wxT("emulated"): wxT("native")) << e;
3674 
3675  Px_CloseMixer(PortMixer);
3676 
3677  } //end of massive if statement if a valid sample rate has been found
3678 #endif
3679  return o.GetString();
3680 }
3681 
3682 #ifdef EXPERIMENTAL_MIDI_OUT
3683 // FIXME: When EXPERIMENTAL_MIDI_IN is added (eventually) this should also be enabled -- Poke
3684 wxString AudioIO::GetMidiDeviceInfo()
3685 {
3686  wxStringOutputStream o;
3687  wxTextOutputStream s(o, wxEOL_UNIX);
3688  wxString e(wxT("\n"));
3689 
3690  if (IsStreamActive()) {
3691  return wxT("Stream is active ... unable to gather information.");
3692  }
3693 
3694 
3695  // XXX: May need to trap errors as with the normal device info
3696  int recDeviceNum = Pm_GetDefaultInputDeviceID();
3697  int playDeviceNum = Pm_GetDefaultOutputDeviceID();
3698  int cnt = Pm_CountDevices();
3699 
3700  wxLogDebug(wxT("PortMidi reports %d MIDI devices"), cnt);
3701 
3702  s << wxT("==============================") << e;
3703  s << wxT("Default recording device number: ") << recDeviceNum << e;
3704  s << wxT("Default playback device number: ") << playDeviceNum << e;
3705 
3706  wxString recDevice = gPrefs->Read(wxT("/MidiIO/RecordingDevice"), wxT(""));
3707  wxString playDevice = gPrefs->Read(wxT("/MidiIO/PlaybackDevice"), wxT(""));
3708 
3709  // This gets info on all available audio devices (input and output)
3710  if (cnt <= 0) {
3711  s << wxT("No devices found\n");
3712  return o.GetString();
3713  }
3714 
3715  for (int i = 0; i < cnt; i++) {
3716  s << wxT("==============================") << e;
3717 
3718  const PmDeviceInfo* info = Pm_GetDeviceInfo(i);
3719  if (!info) {
3720  s << wxT("Device info unavailable for: ") << i << e;
3721  continue;
3722  }
3723 
3724  wxString name = wxSafeConvertMB2WX(info->name);
3725  wxString hostName = wxSafeConvertMB2WX(info->interf);
3726 
3727  s << wxT("Device ID: ") << i << e;
3728  s << wxT("Device name: ") << name << e;
3729  s << wxT("Host name: ") << hostName << e;
3730  s << wxT("Supports output: ") << info->output << e;
3731  s << wxT("Supports input: ") << info->input << e;
3732  s << wxT("Opened: ") << info->opened << e;
3733 
3734  if (name == playDevice && info->output)
3735  playDeviceNum = i;
3736 
3737  if (name == recDevice && info->input)
3738  recDeviceNum = i;
3739 
3740  // XXX: This is only done because the same was applied with PortAudio
3741  // If PortMidi returns -1 for the default device, use the first one
3742  if (recDeviceNum < 0 && info->input){
3743  recDeviceNum = i;
3744  }
3745  if (playDeviceNum < 0 && info->output){
3746  playDeviceNum = i;
3747  }
3748  }
3749 
3750  bool haveRecDevice = (recDeviceNum >= 0);
3751  bool havePlayDevice = (playDeviceNum >= 0);
3752 
3753  s << wxT("==============================") << e;
3754  if (haveRecDevice) {
3755  s << wxT("Selected MIDI recording device: ") << recDeviceNum << wxT(" - ") << recDevice << e;
3756  } else {
3757  s << wxT("No MIDI recording device found for '") << recDevice << wxT("'.") << e;
3758  }
3759  if (havePlayDevice) {
3760  s << wxT("Selected MIDI playback device: ") << playDeviceNum << wxT(" - ") << playDevice << e;
3761  } else {
3762  s << wxT("No MIDI playback device found for '") << playDevice << wxT("'.") << e;
3763  }
3764 
3765  // Mention our conditional compilation flags for Alpha only
3766 #ifdef IS_ALPHA
3767 
3768  s << wxT("==============================") << e;
3769 #ifdef EXPERIMENTAL_MIDI_OUT
3770  s << wxT("EXPERIMENTAL_MIDI_OUT is enabled") << e;
3771 #else
3772  s << wxT("EXPERIMENTAL_MIDI_OUT is NOT enabled") << e;
3773 #endif
3774 #ifdef EXPERIMENTAL_MIDI_IN
3775  s << wxT("EXPERIMENTAL_MIDI_IN is enabled") << e;
3776 #else
3777  s << wxT("EXPERIMENTAL_MIDI_IN is NOT enabled") << e;
3778 #endif
3779 
3780 #endif
3781 
3782  return o.GetString();
3783 }
3784 #endif
3785 
3786 // This method is the data gateway between the audio thread (which
3787 // communicates with the disk) and the PortAudio callback thread
3788 // (which communicates with the audio device).
3790 {
3791  unsigned int i;
3792 
3793  auto delayedHandler = [this] ( AudacityException * pException ) {
3794  // In the main thread, stop recording
3795  // This is one place where the application handles disk
3796  // exhaustion exceptions from wave track operations, without rolling
3797  // back to the last pushed undo state. Instead, partial recording
3798  // results are pushed as a NEW undo state. For this reason, as
3799  // commented elsewhere, we want an exception safety guarantee for
3800  // the output wave tracks, after the failed append operation, that
3801  // the tracks remain as they were after the previous successful
3802  // (block-level) appends.
3803 
3804  // Note that the Flush in StopStream() may throw another exception,
3805  // but StopStream() contains that exception, and the logic in
3806  // AudacityException::DelayedHandlerAction prevents redundant message
3807  // boxes.
3808  StopStream();
3809  DefaultDelayedHandlerAction{}( pException );
3810  };
3811 
3812  if (mPlaybackTracks.size() > 0)
3813  {
3814  // Though extremely unlikely, it is possible that some buffers
3815  // will have more samples available than others. This could happen
3816  // if we hit this code during the PortAudio callback. To keep
3817  // things simple, we only write as much data as is vacant in
3818  // ALL buffers, and advance the global time by that much.
3819  // MB: subtract a few samples because the code below has rounding errors
3820  auto nAvailable = (int)GetCommonlyAvailPlayback() - 10;
3821 
3822  //
3823  // Don't fill the buffers at all unless we can do the
3824  // full mMaxPlaybackSecsToCopy. This improves performance
3825  // by not always trying to process tiny chunks, eating the
3826  // CPU unnecessarily.
3827  //
3828  // The exception is if we're at the end of the selected
3829  // region - then we should just fill the buffer.
3830  //
3831  if (nAvailable >= (int)mPlaybackSamplesToCopy ||
3832  (mPlayMode == PLAY_STRAIGHT &&
3833  nAvailable > 0 &&
3834  mWarpedTime+(nAvailable/mRate) >= mWarpedLength))
3835  {
3836  // Limit maximum buffer size (increases performance)
3837  auto available =
3838  std::min<size_t>( nAvailable, mPlaybackSamplesToCopy );
3839 
3840  // msmeyer: When playing a very short selection in looped
3841  // mode, the selection must be copied to the buffer multiple
3842  // times, to ensure, that the buffer has a reasonable size
3843  // This is the purpose of this loop.
3844  // PRL: or, when scrubbing, we may get work repeatedly from the
3845  // scrub queue.
3846  bool done = false;
3847  Maybe<wxMutexLocker> cleanup;
3848  do {
3849  // How many samples to produce for each channel.
3850  auto frames = available;
3851  bool progress = true;
3852 #ifdef EXPERIMENTAL_SCRUBBING_SUPPORT
3853  if (mPlayMode == PLAY_SCRUB)
3854  // scrubbing does not use warped time and length
3855  frames = limitSampleBufferSize(frames, mScrubDuration);
3856  else
3857 #endif
3858  {
3859  double deltat = frames / mRate;
3860  if (mWarpedTime + deltat > mWarpedLength)
3861  {
3862  frames = (mWarpedLength - mWarpedTime) * mRate;
3863  // Don't fall into an infinite loop, if loop-playing a selection
3864  // that is so short, it has no samples: detect that case
3865  progress =
3866  !(mPlayMode == PLAY_LOOPED &&
3867  mWarpedTime == 0.0 && frames == 0);
3868  mWarpedTime = mWarpedLength;
3869  }
3870  else
3871  mWarpedTime += deltat;
3872  }
3873 
3874  if (!progress)
3875  frames = available;
3876 
3877  for (i = 0; i < mPlaybackTracks.size(); i++)
3878  {
3879  // The mixer here isn't actually mixing: it's just doing
3880  // resampling, format conversion, and possibly time track
3881  // warping
3882  decltype(mPlaybackMixers[i]->Process(frames))
3883  processed = 0;
3884  samplePtr warpedSamples;
3885  //don't do anything if we have no length. In particular, Process() will fail an wxAssert
3886  //that causes a crash since this is not the GUI thread and wxASSERT is a GUI call.
3887 
3888  // don't generate either if scrubbing at zero speed.
3889 #ifdef EXPERIMENTAL_SCRUBBING_SUPPORT
3890  const bool silent = (mPlayMode == PLAY_SCRUB) && mSilentScrub;
3891 #else
3892  const bool silent = false;
3893 #endif
3894 
3895  if (progress && !silent && frames > 0)
3896  {
3897  processed = mPlaybackMixers[i]->Process(frames);
3898  wxASSERT(processed <= frames);
3899  warpedSamples = mPlaybackMixers[i]->GetBuffer();
3900  const auto put = mPlaybackBuffers[i]->Put
3901  (warpedSamples, floatSample, processed);
3902  // wxASSERT(put == processed);
3903  // but we can't assert in this thread
3904  wxUnusedVar(put);
3905  }
3906 
3907  //if looping and processed is less than the full chunk/block/buffer that gets pulled from
3908  //other longer tracks, then we still need to advance the ring buffers or
3909  //we'll trip up on ourselves when we start them back up again.
3910  //if not looping we never start them up again, so its okay to not do anything
3911  // If scrubbing, we may be producing some silence. Otherwise this should not happen,
3912  // but makes sure anyway that we produce equal
3913  // numbers of samples for all channels for this pass of the do-loop.
3914  if(processed < frames && mPlayMode != PLAY_STRAIGHT)
3915  {
3916  mSilentBuf.Resize(frames, floatSample);
3917  ClearSamples(mSilentBuf.ptr(), floatSample, 0, frames);
3918  const auto put = mPlaybackBuffers[i]->Put
3919  (mSilentBuf.ptr(), floatSample, frames - processed);
3920  // wxASSERT(put == frames - processed);
3921  // but we can't assert in this thread
3922  wxUnusedVar(put);
3923  }
3924  }
3925 
3926  available -= frames;
3927  wxASSERT(available >= 0);
3928 
3929  switch (mPlayMode)
3930  {
3931 #ifdef EXPERIMENTAL_SCRUBBING_SUPPORT
3932  case PLAY_SCRUB:
3933  {
3934  mScrubDuration -= frames;
3935  wxASSERT(mScrubDuration >= 0);
3936  done = (available == 0);
3937  if (!done && mScrubDuration <= 0)
3938  {
3939  sampleCount startSample, endSample;
3940  mScrubQueue->Transformer(startSample, endSample, mScrubDuration, cleanup);
3941  if (mScrubDuration < 0)
3942  {
3943  // Can't play anything
3944  // Stop even if we don't fill up available
3945  mScrubDuration = 0;
3946  done = true;
3947  }
3948  else
3949  {
3950  mSilentScrub = (endSample == startSample);
3951  if (!mSilentScrub)
3952  {
3953  double startTime, endTime, speed;
3954  startTime = startSample.as_double() / mRate;
3955  endTime = endSample.as_double() / mRate;
3956  auto diff = (endSample - startSample).as_long_long();
3957  speed = double(std::abs(diff)) / mScrubDuration.as_double();
3958  for (i = 0; i < mPlaybackTracks.size(); i++)
3959  mPlaybackMixers[i]->SetTimesAndSpeed(startTime, endTime, speed);
3960  }
3961  }
3962  }
3963  }
3964  break;
3965 #endif
3966  case PLAY_LOOPED:
3967  {
3968  done = !progress || (available == 0);
3969  // msmeyer: If playing looped, check if we are at the end of the buffer
3970  // and if yes, restart from the beginning.
3971  if (mWarpedTime >= mWarpedLength)
3972  {
3973  for (i = 0; i < mPlaybackTracks.size(); i++)
3974  mPlaybackMixers[i]->Restart();
3975  mWarpedTime = 0.0;
3976  }
3977  }
3978  break;
3979  default:
3980  done = true;
3981  break;
3982  }
3983  } while (!done);
3984  }
3985  } // end of playback buffering
3986 
3987  if (!mRecordingException &&
3988  mCaptureTracks.size() > 0)
3989  GuardedCall( [&] {
3990  // start record buffering
3991  const auto avail = GetCommonlyAvailCapture(); // samples
3992  const auto remainingTime =
3993  std::max(0.0, mRecordingSchedule.ToConsume());
3994  // This may be a very big double number:
3995  const auto remainingSamples = remainingTime * mRate;
3996  bool latencyCorrected = true;
3997 
3998  double deltat = avail / mRate;
3999 
4001  deltat >= mMinCaptureSecsToCopy)
4002  {
4003  // Append captured samples to the end of the WaveTracks.
4004  // The WaveTracks have their own buffering for efficiency.
4005  AutoSaveFile blockFileLog;
4006  auto numChannels = mCaptureTracks.size();
4007 
4008  for( i = 0; i < numChannels; i++ )
4009  {
4010  sampleFormat trackFormat = mCaptureTracks[i]->GetSampleFormat();
4011 
4012  AutoSaveFile appendLog;
4013  size_t discarded = 0;
4014 
4016  const auto correction = mRecordingSchedule.TotalCorrection();
4017  if (correction >= 0) {
4018  // Rightward shift
4019  // Once only (per track per recording), insert some initial
4020  // silence.
4021  size_t size = floor( correction * mRate * mFactor);
4022  SampleBuffer temp(size, trackFormat);
4023  ClearSamples(temp.ptr(), trackFormat, 0, size);
4024  mCaptureTracks[i]->Append(temp.ptr(), trackFormat,
4025  size, 1, &appendLog);
4026  }
4027  else {
4028  // Leftward shift
4029  // discard some samples from the ring buffers.
4030  size_t size = floor(
4032 
4033  // The ring buffer might have grown concurrently -- don't discard more
4034  // than the "avail" value noted above.
4035  discarded = mCaptureBuffers[i]->Discard(std::min(avail, size));
4036 
4037  if (discarded < size)
4038  // We need to visit this again to complete the
4039  // discarding.
4040  latencyCorrected = false;
4041  }
4042  }
4043 
4044  const float *pCrossfadeSrc = nullptr;
4045  size_t crossfadeStart = 0, totalCrossfadeLength = 0;
4046  if (i < mRecordingSchedule.mCrossfadeData.size())
4047  {
4048  // Do crossfading
4049  // The supplied crossfade samples are at the same rate as the track
4050  const auto &data = mRecordingSchedule.mCrossfadeData[i];
4051  totalCrossfadeLength = data.size();
4052  if (totalCrossfadeLength) {
4053  crossfadeStart =
4054  floor(mRecordingSchedule.Consumed() * mCaptureTracks[i]->GetRate());
4055  if (crossfadeStart < totalCrossfadeLength)
4056  pCrossfadeSrc = data.data() + crossfadeStart;
4057  }
4058  }
4059 
4060  wxASSERT(discarded <= avail);
4061  size_t toGet = avail - discarded;
4062  SampleBuffer temp;
4063  size_t size;
4065  if( mFactor == 1.0 )
4066  {
4067  // Take captured samples directly
4068  size = toGet;
4069  if (pCrossfadeSrc)
4070  // Change to float for crossfade calculation
4071  format = floatSample;
4072  else
4073  format = trackFormat;
4074  temp.Allocate(size, format);
4075  const auto got =
4076  mCaptureBuffers[i]->Get(temp.ptr(), format, toGet);
4077  // wxASSERT(got == toGet);
4078  // but we can't assert in this thread
4079  wxUnusedVar(got);
4080  if (double(size) > remainingSamples)
4081  size = floor(remainingSamples);
4082  }
4083  else
4084  {
4085  size = lrint(toGet * mFactor);
4086  format = floatSample;
4087  SampleBuffer temp1(toGet, floatSample);
4088  temp.Allocate(size, format);
4089  const auto got =
4090  mCaptureBuffers[i]->Get(temp1.ptr(), floatSample, toGet);
4091  // wxASSERT(got == toGet);
4092  // but we can't assert in this thread
4093  wxUnusedVar(got);
4094  /* we are re-sampling on the fly. The last resampling call
4095  * must flush any samples left in the rate conversion buffer
4096  * so that they get recorded
4097  */
4098  if (toGet > 0 ) {
4099  if (double(toGet) > remainingSamples)
4100  toGet = floor(remainingSamples);
4101  const auto results =
4102  mResample[i]->Process(mFactor, (float *)temp1.ptr(), toGet,
4103  !IsStreamActive(), (float *)temp.ptr(), size);
4104  size = results.second;
4105  }
4106  }
4107 
4108  if (pCrossfadeSrc) {
4109  wxASSERT(format == floatSample);
4110  size_t crossfadeLength = std::min(size, totalCrossfadeLength - crossfadeStart);
4111  if (crossfadeLength) {
4112  auto ratio = double(crossfadeStart) / totalCrossfadeLength;
4113  auto ratioStep = 1.0 / totalCrossfadeLength;
4114  auto pCrossfadeDst = (float*)temp.ptr();
4115 
4116  // Crossfade loop here
4117  for (size_t ii = 0; ii < crossfadeLength; ++ii) {
4118  *pCrossfadeDst = ratio * *pCrossfadeDst + (1.0 - ratio) * *pCrossfadeSrc;
4119  ++pCrossfadeSrc, ++pCrossfadeDst;
4120  ratio += ratioStep;
4121  }
4122  }
4123  }
4124 
4125  // Now append
4126  // see comment in second handler about guarantee
4127  mCaptureTracks[i]->Append(temp.ptr(), format,
4128  size, 1,
4129  &appendLog);
4130 
4131  if (!appendLog.IsEmpty())
4132  {
4133  blockFileLog.StartTag(wxT("recordingrecovery"));
4134  blockFileLog.WriteAttr(wxT("id"), mCaptureTracks[i]->GetAutoSaveIdent());
4135  blockFileLog.WriteAttr(wxT("channel"), (int)i);
4136  blockFileLog.WriteAttr(wxT("numchannels"), numChannels);
4137  blockFileLog.WriteSubTree(appendLog);
4138  blockFileLog.EndTag(wxT("recordingrecovery"));
4139  }
4140  } // end loop over capture channels
4141 
4142  // Now update the recording shedule position
4143  mRecordingSchedule.mPosition += avail / mRate;
4144  mRecordingSchedule.mLatencyCorrected = latencyCorrected;
4145 
4146  if (mListener && !blockFileLog.IsEmpty())
4147  mListener->OnAudioIONewBlockFiles(blockFileLog);
4148  }
4149  // end of record buffering
4150  },
4151  // handler
4152  [this] ( AudacityException *pException ) {
4153  if ( pException ) {
4154  // So that we don't attempt to fill the recording buffer again
4155  // before the main thread stops recording
4157  return ;
4158  }
4159  else
4160  // Don't want to intercept other exceptions (?)
4161  throw;
4162  },
4163  delayedHandler
4164  );
4165 }
4166 
4168 {
4169  if (IsBusy())
4170  return;
4171 
4172  mListener = listener;
4173 }
4174 
4175 #ifdef EXPERIMENTAL_MIDI_OUT
4176 
4177 static Alg_update gAllNotesOff; // special event for loop ending
4178 // the fields of this event are never used, only the address is important
4179 
4180 double AudioIO::UncorrectedMidiEventTime()
4181 {
4182  double time;
4183  if (mTimeTrack)
4184  time =
4185  mTimeTrack->ComputeWarpedLength(mT0, mNextEventTime - MidiLoopOffset())
4186  + mT0 + (mMidiLoopPasses * mWarpedLength);
4187  else
4188  time = mNextEventTime;
4189 
4190  return time + PauseTime();
4191 }
4192 
4193 void AudioIO::OutputEvent()
4194 {
4195  int channel = (mNextEvent->chan) & 0xF; // must be in [0..15]
4196  int command = -1;
4197  int data1 = -1;
4198  int data2 = -1;
4199 
4200  double eventTime = UncorrectedMidiEventTime();
4201 
4202  // 0.0005 is for rounding
4203  double time = eventTime + 0.0005 -
4204  (mSynthLatency * 0.001);
4205 
4206  time += 1; // MidiTime() has a 1s offset
4207  // state changes have to go out without delay because the
4208  // midi stream time gets reset when playback starts, and
4209  // we don't want to leave any control changes scheduled for later
4210  if (time < 0 || mSendMidiState) time = 0;
4211  PmTimestamp timestamp = (PmTimestamp) (time * 1000); /* s to ms */
4212 
4213  // The special event gAllNotesOff means "end of playback, send
4214  // all notes off on all channels"
4215  if (mNextEvent == &gAllNotesOff) {
4216  bool looping = (mPlayMode == gAudioIO->PLAY_LOOPED);
4217  AllNotesOff(looping);
4218  if (looping) {
4219  // jump back to beginning of loop
4220  ++mMidiLoopPasses;
4221  PrepareMidiIterator(false, MidiLoopOffset());
4222  } else {
4223  mNextEvent = NULL;
4224  }
4225  return;
4226  }
4227 
4228  // if mNextEvent's channel is visible, play it, visibility can
4229  // be updated while playing. Be careful: if we have a note-off,
4230  // then we must not pay attention to the channel selection
4231  // or mute/solo buttons because we must turn the note off
4232  // even if the user changed something after the note began
4233  // Note that because multiple tracks can output to the same
4234  // MIDI channels, it is not a good idea to send "All Notes Off"
4235  // when the user presses the mute button. We have no easy way
4236  // to know what notes are sounding on any given muted track, so
4237  // we'll just wait for the note-off events to happen.
4238  // Also note that note-offs are only sent when we call
4239  // mIterator->request_note_off(), so notes that are not played
4240  // will note generate random note-offs. There is the interesting
4241  // case that if the playback is paused, all-notes-off WILL be sent
4242  // and if playback resumes, the pending note-off events WILL also
4243  // be sent (but if that is a problem, there would also be a problem
4244  // in the non-pause case.
4245  if (((mNextEventTrack->IsVisibleChan(channel)) &&
4246  // only play if note is not muted:
4247  !((mHasSolo || mNextEventTrack->GetMute()) &&
4248  !mNextEventTrack->GetSolo())) ||
4249  (mNextEvent->is_note() && !mNextIsNoteOn)) {
4250  // Note event
4251  if (mNextEvent->is_note() && !mSendMidiState) {
4252  // Pitch and velocity
4253  data1 = mNextEvent->get_pitch();
4254  if (mNextIsNoteOn) {
4255  data2 = mNextEvent->get_loud(); // get velocity
4256  int offset = mNextEventTrack->GetVelocity();
4257  data2 += offset; // offset comes from per-track slider
4258  // clip velocity to insure a legal note-on value
4259  data2 = (data2 < 1 ? 1 : (data2 > 127 ? 127 : data2));
4260  // since we are going to play this note, we need to get a note_off
4261  mIterator->request_note_off();
4262 
4263 #ifdef AUDIO_IO_GB_MIDI_WORKAROUND
4264  mPendingNotesOff.push_back(std::make_pair(channel, data1));
4265 #endif
4266  }
4267  else {
4268  data2 = 0; // 0 velocity means "note off"
4269 #ifdef AUDIO_IO_GB_MIDI_WORKAROUND
4270  auto end = mPendingNotesOff.end();
4271  auto iter = std::find(
4272  mPendingNotesOff.begin(), end, std::make_pair(channel, data1) );
4273  if (iter != end)
4274  mPendingNotesOff.erase(iter);
4275 #endif
4276  }
4277  command = 0x90; // MIDI NOTE ON (or OFF when velocity == 0)
4278  // Update event
4279  } else if (mNextEvent->is_update()) {
4280  // this code is based on allegrosmfwr.cpp -- it could be improved
4281  // by comparing attribute pointers instead of string compares
4282  Alg_update_ptr update = (Alg_update_ptr) mNextEvent;
4283  const char *name = update->get_attribute();
4284 
4285  if (!strcmp(name, "programi")) {
4286  // Instrument change
4287  data1 = update->parameter.i;
4288  data2 = 0;
4289  command = 0xC0; // MIDI PROGRAM CHANGE
4290  } else if (!strncmp(name, "control", 7)) {
4291  // Controller change
4292 
4293  // The number of the controller being changed is embedded
4294  // in the parameter name.
4295  data1 = atoi(name + 7);
4296  // Allegro normalizes controller values
4297  data2 = ROUND(update->parameter.r * 127);
4298  command = 0xB0;
4299  } else if (!strcmp(name, "bendr")) {
4300  // Bend change
4301 
4302  // Reverse Allegro's post-processing of bend values
4303  int temp = ROUND(0x2000 * (update->parameter.r + 1));
4304  if (temp > 0x3fff) temp = 0x3fff; // 14 bits maximum
4305  if (temp < 0) temp = 0;
4306  data1 = temp & 0x7f; // low 7 bits
4307  data2 = temp >> 7; // high 7 bits
4308  command = 0xE0; // MIDI PITCH BEND
4309  } else if (!strcmp(name, "pressurer")) {
4310  // Pressure change
4311  data1 = (int) (update->parameter.r * 127);
4312  if (update->get_identifier() < 0) {
4313  // Channel pressure
4314  data2 = 0;
4315  command = 0xD0; // MIDI CHANNEL PRESSURE
4316  } else {
4317  // Key pressure
4318  data2 = data1;
4319  data1 = update->get_identifier();
4320  command = 0xA0; // MIDI POLY PRESSURE
4321  }
4322  }
4323  }
4324  if (command != -1) {
4325  // keep track of greatest timestamp used
4326  if (timestamp > mMaxMidiTimestamp) {
4327  mMaxMidiTimestamp = timestamp;
4328  }
4329  Pm_WriteShort(mMidiStream, timestamp,
4330  Pm_Message((int) (command + channel),
4331  (long) data1, (long) data2));
4332  /* wxPrintf("Pm_WriteShort %lx (%p) @ %d, advance %d\n",
4333  Pm_Message((int) (command + channel),
4334  (long) data1, (long) data2),
4335  mNextEvent, timestamp, timestamp - Pt_Time()); */
4336  }
4337  }
4338 }
4339 
4340 void AudioIO::GetNextEvent()
4341 {
4342  mNextEventTrack = NULL; // clear it just to be safe
4343  // now get the next event and the track from which it came
4344  double nextOffset;
4345  if (!mIterator) {
4346  mNextEvent = NULL;
4347  return;
4348  }
4349  auto midiLoopOffset = MidiLoopOffset();
4350  mNextEvent = mIterator->next(&mNextIsNoteOn,
4351  (void **) &mNextEventTrack,
4352  &nextOffset, mT1 + midiLoopOffset);
4353 
4354  mNextEventTime = mT1 + midiLoopOffset + 1;
4355  if (mNextEvent) {
4356  mNextEventTime = (mNextIsNoteOn ? mNextEvent->time :
4357  mNextEvent->get_end_time()) + nextOffset;;
4358  }
4359  if (mNextEventTime > (mT1 + midiLoopOffset)){ // terminate playback at mT1
4360  mNextEvent = &gAllNotesOff;
4361  mNextEventTime = mT1 + midiLoopOffset - ALG_EPS;
4362  mNextIsNoteOn = true; // do not look at duration
4363  mIterator->end();
4364  mIterator.reset(); // debugging aid
4365  }
4366 }
4367 
4368 
4369 bool AudioIO::SetHasSolo(bool hasSolo)
4370 {
4371  mHasSolo = hasSolo;
4372  return mHasSolo;
4373 }
4374 
4375 
4376 void AudioIO::FillMidiBuffers()
4377 {
4378  // Keep track of time paused. If not paused, fill buffers.
4379  if (gAudioIO->IsPaused()) {
4380  if (!gAudioIO->mMidiPaused) {
4381  gAudioIO->mMidiPaused = true;
4382  gAudioIO->AllNotesOff(); // to avoid hanging notes during pause
4383  }
4384  return;
4385  }
4386 
4387  if (gAudioIO->mMidiPaused) {
4388  gAudioIO->mMidiPaused = false;
4389  }
4390 
4391  bool hasSolo = false;
4392  auto numPlaybackTracks = gAudioIO->mPlaybackTracks.size();
4393  for(unsigned t = 0; t < numPlaybackTracks; t++ )
4394  if( gAudioIO->mPlaybackTracks[t]->GetSolo() ) {
4395  hasSolo = true;
4396  break;
4397  }
4398  auto numMidiPlaybackTracks = gAudioIO->mMidiPlaybackTracks.size();
4399  for(unsigned t = 0; t < numMidiPlaybackTracks; t++ )
4400  if( gAudioIO->mMidiPlaybackTracks[t]->GetSolo() ) {
4401  hasSolo = true;
4402  break;
4403  }
4404  SetHasSolo(hasSolo);
4405  // If we compute until mNextEventTime > current audio track time,
4406  // we would have a built-in compute-ahead of mAudioOutLatency, and
4407  // it's probably good to compute MIDI when we compute audio (so when
4408  // we stop, both stop about the same time).
4409  double time = AudioTime(); // compute to here
4410  // But if mAudioOutLatency is very low, we might need some extra
4411  // compute-ahead to deal with mSynthLatency or even this thread.
4412  double actual_latency = (MIDI_SLEEP + THREAD_LATENCY +
4413  MIDI_MINIMAL_LATENCY_MS + mSynthLatency) * 0.001;
4414  if (actual_latency > mAudioOutLatency) {
4415  time += actual_latency - mAudioOutLatency;
4416  }
4417  while (mNextEvent &&
4418  UncorrectedMidiEventTime() < time) {
4419  OutputEvent();
4420  GetNextEvent();
4421  }
4422 
4423  // test for end
4424  double realTime = gAudioIO->MidiTime() * 0.001 -
4425  gAudioIO->PauseTime();
4426  realTime -= 1; // MidiTime() runs ahead 1s
4427 
4428  // XXX Is this still true now? It seems to break looping --Poke
4429  //
4430  // The TrackPanel::OnTimer() method updates the time position
4431  // indicator every 200ms, so it tends to not advance the
4432  // indicator to the end of the selection (mT1) but instead stop
4433  // up to 200ms before the end. At this point, output is shut
4434  // down and the indicator is removed, but for a brief time, the
4435  // indicator is clearly stopped before reaching mT1. To avoid
4436  // this, we do not set mMidiOutputComplete until we are actually
4437  // 0.22s beyond mT1 (even though we stop playing at mT1). This
4438  // gives OnTimer() time to wake up and draw the final time
4439  // position at mT1 before shutting down the stream.
4440  const double loopDelay = 0.220;
4441 
4442  double timeAtSpeed;
4443  if (gAudioIO->mTimeTrack)
4444  timeAtSpeed = gAudioIO->mTimeTrack->SolveWarpedLength(gAudioIO->mT0, realTime);
4445  else
4446  timeAtSpeed = realTime;
4447 
4448  gAudioIO->mMidiOutputComplete =
4449  (gAudioIO->mPlayMode == gAudioIO->PLAY_STRAIGHT && // PRL: what if scrubbing?
4450  timeAtSpeed >= gAudioIO->mT1 + loopDelay);
4451  // !gAudioIO->mNextEvent);
4452 }
4453 
4454 double AudioIO::PauseTime()
4455 {
4456  return mNumPauseFrames / mRate;
4457 }
4458 
4459 
4460 // MidiTime() is an estimate in milliseconds of the current audio
4461 // output (DAC) time + 1s. In other words, what audacity track time
4462 // corresponds to the audio (including pause insertions) at the output?
4463 //
4464 PmTimestamp AudioIO::MidiTime()
4465 {
4466  // note: the extra 0.0005 is for rounding. Round down by casting to
4467  // unsigned long, then convert to PmTimeStamp (currently signed)
4468 
4469  // PRL: the time correction is really Midi latency achieved by different
4470  // means than specifying it to Pm_OpenStream. The use of the accumulated
4471  // sample count generated by the audio callback (in AudioTime()) might also
4472  // have the virtue of keeping the Midi output synched with audio.
4473 
4474  PmTimestamp ts;
4475  // subtract latency here because mSystemMinusAudioTime gets us
4476  // to the current *write* time, but we're writing ahead by audio output
4477  // latency (mAudioOutLatency).
4478  double now = SystemTime(mUsingAlsa);
4479  ts = (PmTimestamp) ((unsigned long)
4480  (1000 * (now + 1.0005 -
4481  mSystemMinusAudioTimePlusLatency)));
4482  // wxPrintf("AudioIO::MidiTime() %d time %g sys-aud %g\n",
4483  // ts, now, mSystemMinusAudioTime);
4484  return ts + MIDI_MINIMAL_LATENCY_MS;
4485 }
4486 
4487 
4488 void AudioIO::AllNotesOff(bool looping)
4489 {
4490 #ifdef __WXGTK__
4491  bool doDelay = !looping;
4492 #else
4493  bool doDelay = false;
4494  static_cast<void>(looping);// compiler food.
4495 #endif
4496 
4497  // to keep track of when MIDI should all be delivered,
4498  // update mMaxMidiTimestamp to now:
4499  PmTimestamp now = MidiTime();
4500  if (mMaxMidiTimestamp < now) {
4501  mMaxMidiTimestamp = now;
4502  }
4503 #ifdef AUDIO_IO_GB_MIDI_WORKAROUND
4504  // PRL:
4505  // Send individual note-off messages for each note-on not yet paired.
4506 
4507  // RBD:
4508  // Even this did not work as planned. My guess is ALSA does not use
4509  // a "stable sort" for timed messages, so that when a note-off is
4510  // added later at the same time as a future note-on, the order is
4511  // not respected, and the note-off can go first, leaving a stuck note.
4512  // The workaround here is to use mMaxMidiTimestamp to ensure that
4513  // note-offs come at least 1ms later than any previous message
4514 
4515  // PRL:
4516  // I think we should do that only when stopping or pausing, not when looping
4517  // Note that on Linux, MIDI always uses ALSA, no matter whether portaudio
4518  // uses some other host api.
4519 
4520  mMaxMidiTimestamp += 1;
4521  for (const auto &pair : mPendingNotesOff) {
4522  Pm_WriteShort(mMidiStream,
4523  (doDelay ? mMaxMidiTimestamp : 0),
4524  Pm_Message(
4525  0x90 + pair.first, pair.second, 0));
4526  mMaxMidiTimestamp++; // allow 1ms per note-off
4527  }
4528  mPendingNotesOff.clear();
4529 
4530  // Proceed to do the usual messages too.
4531 #endif
4532 
4533  for (int chan = 0; chan < 16; chan++) {
4534  Pm_WriteShort(mMidiStream,
4535  (doDelay ? mMaxMidiTimestamp : 0),
4536  Pm_Message(0xB0 + chan, 0x7B, 0));
4537  mMaxMidiTimestamp++; // allow 1ms per all-notes-off
4538  }
4539 }
4540 
4541 #endif
4542 
4543 // Automated Input Level Adjustment - Automatically tries to find an acceptable input volume
4544 #ifdef EXPERIMENTAL_AUTOMATED_INPUT_LEVEL_ADJUSTMENT
4545 void AudioIO::AILAInitialize() {
4546  gPrefs->Read(wxT("/AudioIO/AutomatedInputLevelAdjustment"), &mAILAActive, false);
4547  gPrefs->Read(wxT("/AudioIO/TargetPeak"), &mAILAGoalPoint, AILA_DEF_TARGET_PEAK);
4548  gPrefs->Read(wxT("/AudioIO/DeltaPeakVolume"), &mAILAGoalDelta, AILA_DEF_DELTA_PEAK);
4549  gPrefs->Read(wxT("/AudioIO/AnalysisTime"), &mAILAAnalysisTime, AILA_DEF_ANALYSIS_TIME);
4550  gPrefs->Read(wxT("/AudioIO/NumberAnalysis"), &mAILATotalAnalysis, AILA_DEF_NUMBER_ANALYSIS);
4551  mAILAGoalDelta /= 100.0;
4552  mAILAGoalPoint /= 100.0;
4553  mAILAAnalysisTime /= 1000.0;
4554  mAILAMax = 0.0;
4555  mAILALastStartTime = max(0.0, mT0);
4556  mAILAClipped = false;
4557  mAILAAnalysisCounter = 0;
4558  mAILAChangeFactor = 1.0;
4559  mAILALastChangeType = 0;
4560  mAILATopLevel = 1.0;
4561  mAILAAnalysisEndTime = -1.0;
4562 }
4563 
4564 void AudioIO::AILADisable() {
4565  mAILAActive = false;
4566 }
4567 
4568 bool AudioIO::AILAIsActive() {
4569  return mAILAActive;
4570 }
4571 
4572 void AudioIO::AILASetStartTime() {
4573  mAILAAbsolutStartTime = Pa_GetStreamTime(mPortStreamV19);
4574  wxPrintf("START TIME %f\n\n", mAILAAbsolutStartTime);
4575 }
4576 
4577 double AudioIO::AILAGetLastDecisionTime() {
4578  return mAILAAnalysisEndTime;
4579 }
4580 
4581 void AudioIO::AILAProcess(double maxPeak) {
4583  if (proj && mAILAActive) {
4584  if (mInputMeter && mInputMeter->IsClipping()) {
4585  mAILAClipped = true;
4586  wxPrintf("clipped");
4587  }
4588 
4589  mAILAMax = max(mAILAMax, maxPeak);
4590 
4591  if ((mAILATotalAnalysis == 0 || mAILAAnalysisCounter < mAILATotalAnalysis) && mTime - mAILALastStartTime >= mAILAAnalysisTime) {
4592  putchar('\n');
4593  mAILAMax = mInputMeter ? mInputMeter->ToLinearIfDB(mAILAMax) : 0.0;
4594  double iv = (double) Px_GetInputVolume(mPortMixer);
4595  unsigned short changetype = 0; //0 - no change, 1 - increase change, 2 - decrease change
4596  wxPrintf("mAILAAnalysisCounter:%d\n", mAILAAnalysisCounter);
4597  wxPrintf("\tmAILAClipped:%d\n", mAILAClipped);
4598  wxPrintf("\tmAILAMax (linear):%f\n", mAILAMax);
4599  wxPrintf("\tmAILAGoalPoint:%f\n", mAILAGoalPoint);
4600  wxPrintf("\tmAILAGoalDelta:%f\n", mAILAGoalDelta);
4601  wxPrintf("\tiv:%f\n", iv);
4602  wxPrintf("\tmAILAChangeFactor:%f\n", mAILAChangeFactor);
4603  if (mAILAClipped || mAILAMax > mAILAGoalPoint + mAILAGoalDelta) {
4604  wxPrintf("too high:\n");
4605  mAILATopLevel = min(mAILATopLevel, iv);
4606  wxPrintf("\tmAILATopLevel:%f\n", mAILATopLevel);
4607  //if clipped or too high
4608  if (iv <= LOWER_BOUND) {
4609  //we can't improve it more now
4610  if (mAILATotalAnalysis != 0) {
4611  mAILAActive = false;
4612  proj->TP_DisplayStatusMessage(_("Automated Recording Level Adjustment stopped. It was not possible to optimize it more. Still too high."));
4613  }
4614  wxPrintf("\talready min vol:%f\n", iv);
4615  }
4616  else {
4617  float vol = (float) max(LOWER_BOUND, iv+(mAILAGoalPoint-mAILAMax)*mAILAChangeFactor);
4618  Px_SetInputVolume(mPortMixer, vol);
4619  wxString msg;
4620  msg.Printf(_("Automated Recording Level Adjustment decreased the volume to %f."), vol);
4621  proj->TP_DisplayStatusMessage(msg);
4622  changetype = 1;
4623  wxPrintf("\tnew vol:%f\n", vol);
4624  float check = Px_GetInputVolume(mPortMixer);
4625  wxPrintf("\tverified %f\n", check);
4626  }
4627  }
4628  else if ( mAILAMax < mAILAGoalPoint - mAILAGoalDelta ) {
4629  //if too low
4630  wxPrintf("too low:\n");
4631  if (iv >= UPPER_BOUND || iv + 0.005 > mAILATopLevel) { //condition for too low volumes and/or variable volumes that cause mAILATopLevel to decrease too much
4632  //we can't improve it more
4633  if (mAILATotalAnalysis != 0) {
4634  mAILAActive = false;
4635  proj->TP_DisplayStatusMessage(_("Automated Recording Level Adjustment stopped. It was not possible to optimize it more. Still too low."));
4636  }
4637  wxPrintf("\talready max vol:%f\n", iv);
4638  }
4639  else {
4640  float vol = (float) min(UPPER_BOUND, iv+(mAILAGoalPoint-mAILAMax)*mAILAChangeFactor);
4641  if (vol > mAILATopLevel) {
4642  vol = (iv + mAILATopLevel)/2.0;
4643  wxPrintf("\tTruncated vol:%f\n", vol);
4644  }
4645  Px_SetInputVolume(mPortMixer, vol);
4646  wxString msg;
4647  msg.Printf(_("Automated Recording Level Adjustment increased the volume to %.2f."), vol);
4648  proj->TP_DisplayStatusMessage(msg);
4649  changetype = 2;
4650  wxPrintf("\tnew vol:%f\n", vol);
4651  float check = Px_GetInputVolume(mPortMixer);
4652  wxPrintf("\tverified %f\n", check);
4653  }
4654  }
4655 
4656  mAILAAnalysisCounter++;
4657  //const PaStreamInfo* info = Pa_GetStreamInfo(mPortStreamV19);
4658  //double latency = 0.0;
4659  //if (info)
4660  // latency = info->inputLatency;
4661  //mAILAAnalysisEndTime = mTime+latency;
4662  mAILAAnalysisEndTime = Pa_GetStreamTime(mPortStreamV19) - mAILAAbsolutStartTime;
4663  mAILAMax = 0;
4664  wxPrintf("\tA decision was made @ %f\n", mAILAAnalysisEndTime);
4665  mAILAClipped = false;
4666  mAILALastStartTime = mTime;
4667 
4668  if (changetype == 0)
4669  mAILAChangeFactor *= 0.8; //time factor
4670  else if (mAILALastChangeType == changetype)
4671  mAILAChangeFactor *= 1.1; //concordance factor
4672  else
4673  mAILAChangeFactor *= 0.7; //discordance factor
4674  mAILALastChangeType = changetype;
4675  putchar('\n');
4676  }
4677 
4678  if (mAILAActive && mAILATotalAnalysis != 0 && mAILAAnalysisCounter >= mAILATotalAnalysis) {
4679  mAILAActive = false;
4680  if (mAILAMax > mAILAGoalPoint + mAILAGoalDelta)
4681  proj->TP_DisplayStatusMessage(_("Automated Recording Level Adjustment stopped. The total number of analyses has been exceeded without finding an acceptable volume. Still too high."));
4682  else if (mAILAMax < mAILAGoalPoint - mAILAGoalDelta)
4683  proj->TP_DisplayStatusMessage(_("Automated Recording Level Adjustment stopped. The total number of analyses has been exceeded without finding an acceptable volume. Still too low."));
4684  else {
4685  wxString msg;
4686  msg.Printf(_("Automated Recording Level Adjustment stopped. %.2f seems an acceptable volume."), Px_GetInputVolume(mPortMixer));
4687  proj->TP_DisplayStatusMessage(msg);
4688  }
4689  }
4690  }
4691 }
4692 #endif
4693 
4695 //
4696 // PortAudio callback thread context
4697 //
4699 
4700 #define MAX(a,b) ((a) > (b) ? (a) : (b))
4701 
4702 static void DoSoftwarePlaythrough(const void *inputBuffer,
4703  sampleFormat inputFormat,
4704  unsigned inputChannels,
4705  float *outputBuffer,
4706  int len)
4707 {
4708  for (unsigned int i=0; i < inputChannels; i++) {
4709  samplePtr inputPtr = ((samplePtr)inputBuffer) + (i * SAMPLE_SIZE(inputFormat));
4710  samplePtr outputPtr = ((samplePtr)outputBuffer) + (i * SAMPLE_SIZE(floatSample));
4711 
4712  CopySamples(inputPtr, inputFormat,
4713  (samplePtr)outputPtr, floatSample,
4714  len, true, inputChannels, 2);
4715  }
4716 
4717  // One mono input channel goes to both output channels...
4718  if (inputChannels == 1)
4719  for (int i=0; i < len; i++)
4720  outputBuffer[2*i + 1] = outputBuffer[2*i];
4721 }
4722 
4723 int audacityAudioCallback(const void *inputBuffer, void *outputBuffer,
4724  unsigned long framesPerBuffer,
4725 // If there were more of these conditionally used arguments, it
4726 // could make sense to make a NEW macro that looks like this:
4727 // USEDIF( EXPERIMENTAL_MIDI_OUT, timeInfo )
4728 #ifdef EXPERIMENTAL_MIDI_OUT
4729  const PaStreamCallbackTimeInfo *timeInfo,
4730 #else
4731  const PaStreamCallbackTimeInfo * WXUNUSED(timeInfo),
4732 #endif
4733  const PaStreamCallbackFlags statusFlags, void * WXUNUSED(userData) )
4734 {
4735  auto numPlaybackChannels = gAudioIO->mNumPlaybackChannels;
4736  auto numPlaybackTracks = gAudioIO->mPlaybackTracks.size();
4737  auto numCaptureChannels = gAudioIO->mNumCaptureChannels;
4738  int callbackReturn = paContinue;
4739  void *tempBuffer = alloca(framesPerBuffer*sizeof(float)*
4740  MAX(numCaptureChannels,numPlaybackChannels));
4741  float *tempFloats = (float*)tempBuffer;
4742 
4743  // output meter may need samples untouched by volume emulation
4744  float *outputMeterFloats;
4745  outputMeterFloats =
4746  (outputBuffer && gAudioIO->mEmulateMixerOutputVol &&
4747  gAudioIO->mMixerOutputVol != 1.0) ?
4748  (float *)alloca(framesPerBuffer*numPlaybackChannels * sizeof(float)) :
4749  (float *)outputBuffer;
4750 
4751 #ifdef EXPERIMENTAL_MIDI_OUT
4752  if (gAudioIO->mCallbackCount++ == 0) {
4753  // This is effectively mSystemMinusAudioTime when the buffer is empty:
4754  gAudioIO->mStartTime = SystemTime(gAudioIO->mUsingAlsa) - gAudioIO->mT0;
4755  // later, mStartTime - mSystemMinusAudioTime will tell us latency
4756  }
4757 
4758  /* GSW: Save timeInfo in case MidiPlayback needs it */
4759  gAudioIO->mAudioCallbackClockTime = PaUtil_GetTime();
4760 
4761  /* for Linux, estimate a smooth audio time as a slowly-changing
4762  offset from system time */
4763  // rnow is system time as a double to simplify math
4764  double rnow = SystemTime(gAudioIO->mUsingAlsa);
4765  // anow is next-sample-to-be-computed audio time as a double
4766  double anow = gAudioIO->AudioTime();
4767 
4768  if (gAudioIO->mUsingAlsa) {
4769  // timeInfo's fields are not all reliable.
4770 
4771  // enow is audio time estimated from our clock synchronization protocol,
4772  // which produces mSystemMinusAudioTime. But we want the estimate
4773  // to drift low, so we steadily increase mSystemMinusAudioTime to
4774  // simulate a fast system clock or a slow audio clock. If anow > enow,
4775  // we'll update mSystemMinusAudioTime to keep in sync. (You might think
4776  // we could just use anow as the "truth", but it has a lot of jitter,
4777  // so we are using enow to smooth out this jitter, in fact to < 1ms.)
4778  // Add worst-case clock drift using previous framesPerBuffer:
4779  const auto increase =
4780  gAudioIO->mAudioFramesPerBuffer * 0.0002 / gAudioIO->mRate;
4781  gAudioIO->mSystemMinusAudioTime += increase;
4782  gAudioIO->mSystemMinusAudioTimePlusLatency += increase;
4783  double enow = rnow - gAudioIO->mSystemMinusAudioTime;
4784 
4785 
4786  // now, use anow instead if it is ahead of enow
4787  if (anow > enow) {
4788  gAudioIO->mSystemMinusAudioTime = rnow - anow;
4789  // Update our mAudioOutLatency estimate during the first 20 callbacks.
4790  // During this period, the buffer should fill. Once we have a good
4791  // estimate of mSystemMinusAudioTime (expected in fewer than 20 callbacks)
4792  // we want to stop the updating in case there is clock drift, which would
4793  // cause the mAudioOutLatency estimation to drift as well. The clock drift
4794  // in the first 20 callbacks should be negligible, however.
4795  if (gAudioIO->mCallbackCount < 20) {
4796  gAudioIO->mAudioOutLatency = gAudioIO->mStartTime -
4797  gAudioIO->mSystemMinusAudioTime;
4798  }
4799  gAudioIO->mSystemMinusAudioTimePlusLatency =
4800  gAudioIO->mSystemMinusAudioTime + gAudioIO->mAudioOutLatency;
4801  }
4802  }
4803  else {
4804  // If not using Alsa, rely on timeInfo to have meaningful values that are
4805  // more precise than the output latency value reported at stream start.
4806  gAudioIO->mSystemMinusAudioTime = rnow - anow;
4807  gAudioIO->mSystemMinusAudioTimePlusLatency =
4808  gAudioIO->mSystemMinusAudioTime +
4809  (timeInfo->outputBufferDacTime - timeInfo->currentTime);
4810  }
4811 
4812  gAudioIO->mAudioFramesPerBuffer = framesPerBuffer;
4813  if (gAudioIO->IsPaused()
4814  // PRL: Why was this added? Was it only because of the mysterious
4815  // initial leading zeroes, now solved by setting mStreamToken early?
4816  || gAudioIO->mStreamToken <= 0
4817  )
4818  gAudioIO->mNumPauseFrames += framesPerBuffer;
4819 
4820  // PRL: Note that when there is a separate MIDI thread, it is effectively
4821  // blocked until the first visit to this line during a playback, and will
4822  // not read gAudioIO->mSystemMinusAudioTimePlusLatency sooner:
4823  gAudioIO->mNumFrames += framesPerBuffer;
4824 
4825 #ifndef USE_MIDI_THREAD
4826  if (gAudioIO->mMidiStream)
4827  gAudioIO->FillMidiBuffers();
4828 #endif
4829 
4830 #endif
4831 
4832  unsigned int i;
4833 
4834  /* Send data to recording VU meter if applicable */
4835 
4836  if (gAudioIO->mInputMeter &&
4837  !gAudioIO->mInputMeter->IsMeterDisabled() &&
4838  inputBuffer) {
4839  // get here if meters are actually live , and being updated
4840  /* It's critical that we don't update the meters while StopStream is
4841  * trying to stop PortAudio, otherwise it can lead to a freeze. We use
4842  * two variables to synchronize:
4843  * mUpdatingMeters tells StopStream when the callback is about to enter
4844  * the code where it might update the meters, and
4845  * mUpdateMeters is how the rest of the code tells the callback when it
4846  * is allowed to actually do the updating.
4847  * Note that mUpdatingMeters must be set first to avoid a race condition.
4848  */
4849  gAudioIO->mUpdatingMeters = true;
4850  if (gAudioIO->mUpdateMeters) {
4852  gAudioIO->mInputMeter->UpdateDisplay(numCaptureChannels,
4853  framesPerBuffer,
4854  (float *)inputBuffer);
4855  else {
4857  (samplePtr)tempFloats, floatSample,
4858  framesPerBuffer * numCaptureChannels);
4859  gAudioIO->mInputMeter->UpdateDisplay(numCaptureChannels,
4860  framesPerBuffer,
4861  tempFloats);
4862  }
4863  }
4864  gAudioIO->mUpdatingMeters = false;
4865  } // end recording VU meter update
4866 
4867  // Stop recording if 'silence' is detected
4868  //
4869  // LL: We'd gotten a little "dangerous" with the control toolbar calls
4870  // here because we are not running in the main GUI thread. Eventually
4871  // the toolbar attempts to update the active project's status bar.
4872  // But, since we're not in the main thread, we can get all manner of
4873  // really weird failures. Or none at all which is even worse, since
4874  // we don't know a problem exists.
4875  //
4876  // By using CallAfter(), we can schedule the call to the toolbar
4877  // to run in the main GUI thread after the next event loop iteration.
4878  if(gAudioIO->mPauseRec && inputBuffer && gAudioIO->mInputMeter) {
4879  if(gAudioIO->mInputMeter->GetMaxPeak() < gAudioIO->mSilenceLevel ) {
4880  if(!gAudioIO->IsPaused()) {
4882  ControlToolBar *bar = p->GetControlToolBar();
4883  bar->CallAfter(&ControlToolBar::Pause);
4884  }
4885  }
4886  else {
4887  if(gAudioIO->IsPaused()) {
4889  ControlToolBar *bar = p->GetControlToolBar();
4890  bar->CallAfter(&ControlToolBar::Pause);
4891  }
4892  }
4893  }
4894  if( gAudioIO->mPaused )
4895  {
4896  if (outputBuffer && numPlaybackChannels > 0)
4897  {
4898  ClearSamples((samplePtr)outputBuffer, floatSample,
4899  0, framesPerBuffer * numPlaybackChannels);
4900 
4901  if (inputBuffer && gAudioIO->mSoftwarePlaythrough) {
4903  numCaptureChannels,
4904  (float *)outputBuffer, (int)framesPerBuffer);
4905  }
4906  }
4907 
4908  return paContinue;
4909  }
4910 
4911  if (gAudioIO->mStreamToken > 0)
4912  {
4913  //
4914  // Mix and copy to PortAudio's output buffer
4915  //
4916 
4917  if( outputBuffer && (numPlaybackChannels > 0) )
4918  {
4919  bool cut = false;
4920  bool linkFlag = false;
4921 
4922  float *outputFloats = (float *)outputBuffer;
4923  for( i = 0; i < framesPerBuffer*numPlaybackChannels; i++)
4924  outputFloats[i] = 0.0;
4925 
4926  if (inputBuffer && gAudioIO->mSoftwarePlaythrough) {
4928  numCaptureChannels,
4929  (float *)outputBuffer, (int)framesPerBuffer);
4930  }
4931 
4932  // Copy the results to outputMeterFloats if necessary
4933  if (outputMeterFloats != outputFloats) {
4934  for (i = 0; i < framesPerBuffer*numPlaybackChannels; ++i) {
4935  outputMeterFloats[i] = outputFloats[i];
4936  }
4937  }
4938 
4939 #ifdef EXPERIMENTAL_SCRUBBING_SUPPORT
4940  // While scrubbing, ignore seek requests
4942  gAudioIO->mSeek = 0.0;
4943  else
4944 #endif
4945  if (gAudioIO->mSeek)
4946  {
4947  int token = gAudioIO->mStreamToken;
4948  wxMutexLocker locker(gAudioIO->mSuspendAudioThread);
4949  if (token != gAudioIO->mStreamToken)
4950  // This stream got destroyed while we waited for it
4951  return paAbort;
4952 
4953  // Pause audio thread and wait for it to finish
4956  {
4957  wxMilliSleep( 50 );
4958  }
4959 
4960  // Calculate the NEW time position
4963  gAudioIO->mSeek = 0.0;
4964 
4965  // Reset mixer positions and flush buffers for all tracks
4966  if(gAudioIO->mTimeTrack)
4967  // Following gives negative when mT0 > mTime
4970  (gAudioIO->mT0, gAudioIO->mTime);
4971  else
4973  gAudioIO->mWarpedTime = std::abs(gAudioIO->mWarpedTime);
4974 
4975  // Reset mixer positions and flush buffers for all tracks
4976  for (i = 0; i < numPlaybackTracks; i++)
4977  {
4978  gAudioIO->mPlaybackMixers[i]->Reposition(gAudioIO->mTime);
4979  const auto toDiscard =
4980  gAudioIO->mPlaybackBuffers[i]->AvailForGet();
4981  const auto discarded =
4982  gAudioIO->mPlaybackBuffers[i]->Discard( toDiscard );
4983  // wxASSERT( discarded == toDiscard );
4984  // but we can't assert in this thread
4985  wxUnusedVar(discarded);
4986  }
4987 
4988  // Reload the ring buffers
4991  {
4992  wxMilliSleep( 50 );
4993  }
4994 
4995  // Reenable the audio thread
4997 
4998  return paContinue;
4999  }
5000 
5001  unsigned numSolo = 0;
5002  for(unsigned t = 0; t < numPlaybackTracks; t++ )
5003  if( gAudioIO->mPlaybackTracks[t]->GetSolo() )
5004  numSolo++;
5005 #ifdef EXPERIMENTAL_MIDI_OUT
5006  auto numMidiPlaybackTracks = gAudioIO->mMidiPlaybackTracks.size();
5007  for( unsigned t = 0; t < numMidiPlaybackTracks; t++ )
5008  if( gAudioIO->mMidiPlaybackTracks[t]->GetSolo() )
5009  numSolo++;
5010 #endif
5011 
5012  const WaveTrack **chans = (const WaveTrack **) alloca(numPlaybackChannels * sizeof(WaveTrack *));
5013  float **tempBufs = (float **) alloca(numPlaybackChannels * sizeof(float *));
5014  for (unsigned int c = 0; c < numPlaybackChannels; c++)
5015  {
5016  tempBufs[c] = (float *) alloca(framesPerBuffer * sizeof(float));
5017  }
5018 
5020  em.RealtimeProcessStart();
5021 
5022  bool selected = false;
5023  int group = 0;
5024  int chanCnt = 0;
5025  decltype(framesPerBuffer) maxLen = 0;
5026  for (unsigned t = 0; t < numPlaybackTracks; t++)
5027  {
5028  const WaveTrack *vt = gAudioIO->mPlaybackTracks[t].get();
5029 
5030  chans[chanCnt] = vt;
5031 
5032  if (linkFlag)
5033  linkFlag = false;
5034  else {
5035  cut = false;
5036 
5037  // Cut if somebody else is soloing
5038  if (numSolo>0 && !vt->GetSolo())
5039  cut = true;
5040 
5041  // Cut if we're muted (unless we're soloing)
5042  if (vt->GetMute() && !vt->GetSolo())
5043  cut = true;
5044 
5045  linkFlag = vt->GetLinked();
5046  selected = vt->GetSelected();
5047 
5048  // If we have a mono track, clear the right channel
5049  if (!linkFlag)
5050  {
5051  memset(tempBufs[1], 0, framesPerBuffer * sizeof(float));
5052  }
5053  }
5054 
5055 #define ORIGINAL_DO_NOT_PLAY_ALL_MUTED_TRACKS_TO_END
5056 #ifdef ORIGINAL_DO_NOT_PLAY_ALL_MUTED_TRACKS_TO_END
5057  decltype(framesPerBuffer) len = 0;
5058  // this is original code prior to r10680 -RBD
5059  if (cut)
5060  {
5061  len = gAudioIO->mPlaybackBuffers[t]->Discard(framesPerBuffer);
5062  // keep going here.
5063  // we may still need to issue a paComplete.
5064  }
5065  else
5066  {
5067  len = gAudioIO->mPlaybackBuffers[t]->Get((samplePtr)tempBufs[chanCnt],
5068  floatSample,
5069  framesPerBuffer);
5070  if (len < framesPerBuffer)
5071  // Pad with zeroes to the end, in case of a short channel
5072  memset((void*)&tempBufs[chanCnt][len], 0,
5073  (framesPerBuffer - len) * sizeof(float));
5074 
5075  chanCnt++;
5076  }
5077 
5078  // PRL: Bug1104:
5079  // There can be a difference of len in different loop passes if one channel
5080  // of a stereo track ends before the other! Take a max!
5081  maxLen = std::max(maxLen, len);
5082 
5083 
5084  if (linkFlag)
5085  {
5086  continue;
5087  }
5088 #else
5089  // This code was reorganized so that if all audio tracks
5090  // are muted, we still return paComplete when the end of
5091  // a selection is reached.
5092  // Vaughan, 2011-10-20: Further comments from Roger, by off-list email:
5093  // ...something to do with what it means to mute all audio tracks. E.g. if you
5094  // mute all and play, does the playback terminate immediately or play
5095  // silence? If it terminates immediately, does that terminate any MIDI
5096  // playback that might also be going on? ...Maybe muted audio tracks + MIDI,
5097  // the playback would NEVER terminate. ...I think the #else part is probably preferable...
5098  size_t len;
5099  if (cut)
5100  {
5101  len =
5102  gAudioIO->mPlaybackBuffers[t]->Discard(framesPerBuffer);
5103  } else
5104  {
5105  len =
5106  gAudioIO->mPlaybackBuffers[t]->Get((samplePtr)tempFloats,
5107  floatSample,
5108  framesPerBuffer);
5109  }
5110 #endif
5111 
5112  // Last channel seen now
5113  len = maxLen;
5114 
5115  if( !cut && selected )
5116  {
5117  len = em.RealtimeProcess(group, chanCnt, tempBufs, len);
5118  }
5119  group++;
5120 
5121  // If our buffer is empty and the time indicator is past
5122  // the end, then we've actually finished playing the entire
5123  // selection.
5124  // msmeyer: We never finish if we are playing looped
5125  // PRL: or scrubbing.
5126  if (len == 0 &&
5128  if ((gAudioIO->ReversedTime()
5129  ? gAudioIO->mTime <= gAudioIO->mT1
5130  : gAudioIO->mTime >= gAudioIO->mT1))
5131  // PRL: singalling MIDI output complete is necessary if
5132  // not USE_MIDI_THREAD, otherwise it's harmlessly redundant
5133 #ifdef EXPERIMENTAL_MIDI_OUT
5134  gAudioIO->mMidiOutputComplete = true,
5135 #endif
5136  callbackReturn = paComplete;
5137  }
5138 
5139  if (cut) // no samples to process, they've been discarded
5140  continue;
5141 
5142  for (int c = 0; c < chanCnt; c++)
5143  {
5144  vt = chans[c];
5145 
5146  if (vt->GetChannel() == Track::LeftChannel ||
5147  vt->GetChannel() == Track::MonoChannel)
5148  {
5149  float gain = vt->GetChannelGain(0);
5150 
5151  // Output volume emulation: possibly copy meter samples, then
5152  // apply volume, then copy to the output buffer
5153  if (outputMeterFloats != outputFloats)
5154  for (decltype(len) i = 0; i < len; ++i)
5155  outputMeterFloats[numPlaybackChannels*i] +=
5156  gain*tempFloats[i];
5157 
5159  gain *= gAudioIO->mMixerOutputVol;
5160 
5161  for(decltype(len) i = 0; i < len; i++)
5162  outputFloats[numPlaybackChannels*i] += gain*tempBufs[c][i];
5163  }
5164 
5165  if (vt->GetChannel() == Track::RightChannel ||
5166  vt->GetChannel() == Track::MonoChannel)
5167  {
5168  float gain = vt->GetChannelGain(1);
5169 
5170  // Output volume emulation (as above)
5171  if (outputMeterFloats != outputFloats)
5172  for (decltype(len) i = 0; i < len; ++i)
5173  outputMeterFloats[numPlaybackChannels*i+1] +=
5174  gain*tempFloats[i];
5175 
5177  gain *= gAudioIO->mMixerOutputVol;
5178 
5179  for(decltype(len) i = 0; i < len; i++)
5180  outputFloats[numPlaybackChannels*i+1] += gain*tempBufs[c][i];
5181  }
5182  }
5183 
5184  chanCnt = 0;
5185  }
5186  // Poke: If there are no playback tracks, then the earlier check
5187  // about the time indicator being passed the end won't happen;
5188  // do it here instead (but not if looping or scrubbing)
5189  if (numPlaybackTracks == 0 &&
5191  {
5192  if ((gAudioIO->ReversedTime()
5193  ? gAudioIO->mTime <= gAudioIO->mT1
5194  : gAudioIO->mTime >= gAudioIO->mT1)) {
5195 
5196  // PRL: singalling MIDI output complete is necessary if
5197  // not USE_MIDI_THREAD, otherwise it's harmlessly redundant
5198 #ifdef EXPERIMENTAL_MIDI_OUT
5199  gAudioIO->mMidiOutputComplete = true,
5200 #endif
5201  callbackReturn = paComplete;
5202  }
5203  }
5204 
5205 #ifdef EXPERIMENTAL_SCRUBBING_SUPPORT
5206  // Update the current time position, for scrubbing
5207  // "Consume" only as much as the ring buffers produced, which may
5208  // be less than framesPerBuffer (during "stutter")
5210  gAudioIO->mTime = gAudioIO->mScrubQueue->Consumer(maxLen);
5211 #endif
5212 
5213  em.RealtimeProcessEnd();
5214 
5215  gAudioIO->mLastPlaybackTimeMillis = ::wxGetLocalTimeMillis();
5216 
5217  //
5218  // Clip output to [-1.0,+1.0] range (msmeyer)
5219  //
5220  for( i = 0; i < framesPerBuffer*numPlaybackChannels; i++)
5221  {
5222  float f = outputFloats[i];
5223  if (f > 1.0)
5224  outputFloats[i] = 1.0;
5225  else if (f < -1.0)
5226  outputFloats[i] = -1.0;
5227  }
5228 
5229  // Same for meter output
5230  if (outputMeterFloats != outputFloats)
5231  {
5232  for (i = 0; i < framesPerBuffer*numPlaybackChannels; ++i)
5233  {
5234  float f = outputMeterFloats[i];
5235  if (f > 1.0)
5236  outputMeterFloats[i] = 1.0;
5237  else if (f < -1.0)
5238  outputMeterFloats[i] = -1.0;
5239  }
5240  }
5241  }
5242 
5243  //
5244  // Copy from PortAudio to our input buffers.
5245  //
5246 
5247  if( inputBuffer && (numCaptureChannels > 0) )
5248  {
5249  // If there are no playback tracks, and we are recording, then the
5250  // earlier checks for being passed the end won't happen, so do it here.
5251  if (gAudioIO->mTime >= gAudioIO->mT1) {
5252  callbackReturn = paComplete;
5253  }
5254 
5255  // The error likely from a too-busy CPU falling behind real-time data
5256  // is paInputOverflow
5257  bool inputError =
5258  (statusFlags & (paInputOverflow))
5259  && !(statusFlags & paPrimingOutput);
5260 
5261  // But it seems it's easy to get false positives, at least on Mac
5262  // So we have not decided to enable this extra detection yet in
5263  // production
5264 
5265  size_t len = framesPerBuffer;
5266  for(unsigned t = 0; t < numCaptureChannels; t++)
5267  len = std::min( len,
5268  gAudioIO->mCaptureBuffers[t]->AvailForPut());
5269 
5270  if (gAudioIO->mSimulateRecordingErrors && 100LL * rand() < RAND_MAX)
5271  // Make spurious errors for purposes of testing the error
5272  // reporting
5273  len = 0;
5274 
5275  // A different symptom is that len < framesPerBuffer because
5276  // the other thread, executing FillBuffers, isn't consuming fast
5277  // enough from mCaptureBuffers; maybe it's CPU-bound, or maybe the
5278  // storage device it writes is too slow
5279  if (gAudioIO->mDetectDropouts &&
5280  ((gAudioIO->mDetectUpstreamDropouts && inputError) ||
5281  len < framesPerBuffer) ) {
5282  // Assume that any good partial buffer should be written leftmost
5283  // and zeroes will be padded after; label the zeroes.
5284  auto start = gAudioIO->mTime + len / gAudioIO->mRate +
5286  auto duration = (framesPerBuffer - len) / gAudioIO->mRate;
5287  auto interval = std::make_pair( start, duration );
5288  gAudioIO->mLostCaptureIntervals.push_back( interval );
5289  }
5290 
5291  if (len < framesPerBuffer)
5292  {
5293  gAudioIO->mLostSamples += (framesPerBuffer - len);
5294  wxPrintf(wxT("lost %d samples\n"), (int)(framesPerBuffer - len));
5295  }
5296 
5297  if (len > 0) {
5298  for(unsigned t = 0; t < numCaptureChannels; t++) {
5299 
5300  // dmazzoni:
5301  // Un-interleave. Ugly special-case code required because the
5302  // capture channels could be in three different sample formats;
5303  // it'd be nice to be able to call CopySamples, but it can't
5304  // handle multiplying by the gain and then clipping. Bummer.
5305 
5306  switch(gAudioIO->mCaptureFormat) {
5307  case floatSample: {
5308  float *inputFloats = (float *)inputBuffer;
5309  for( i = 0; i < len; i++)
5310  tempFloats[i] =
5311  inputFloats[numCaptureChannels*i+t];
5312  } break;
5313  case int24Sample:
5314  // We should never get here. Audacity's int24Sample format
5315  // is different from PortAudio's sample format and so we
5316  // make PortAudio return float samples when recording in
5317  // 24-bit samples.
5318  wxASSERT(false);
5319  break;
5320  case int16Sample: {
5321  short *inputShorts = (short *)inputBuffer;
5322  short *tempShorts = (short *)tempBuffer;
5323  for( i = 0; i < len; i++) {
5324  float tmp = inputShorts[numCaptureChannels*i+t];
5325  if (tmp > 32767)
5326  tmp = 32767;
5327  if (tmp < -32768)
5328  tmp = -32768;
5329  tempShorts[i] = (short)(tmp);
5330  }
5331  } break;
5332  } // switch
5333 
5334  const auto put =
5335  gAudioIO->mCaptureBuffers[t]->Put(
5336  (samplePtr)tempBuffer, gAudioIO->mCaptureFormat, len);
5337  // wxASSERT(put == len);
5338  // but we can't assert in this thread
5339  wxUnusedVar(put);
5340  }
5341  }
5342  }
5343 
5344  // Update the current time position if not scrubbing
5345  // (Already did it above, for scrubbing)
5346 #ifdef EXPERIMENTAL_SCRUBBING_SUPPORT
5348 #endif
5349  {
5350  double delta = framesPerBuffer / gAudioIO->mRate;
5351  if (gAudioIO->ReversedTime())
5352  delta *= -1.0;
5353  if (gAudioIO->mTimeTrack)
5354  // MB: this is why SolveWarpedLength is needed :)
5355  gAudioIO->mTime =
5357  else
5358  gAudioIO->mTime += delta;
5359  }
5360 
5361  // Wrap to start if looping
5363  {
5364  while (gAudioIO->ReversedTime()
5365  ? gAudioIO->mTime <= gAudioIO->mT1
5366  : gAudioIO->mTime >= gAudioIO->mT1)
5367  {
5368  // LL: This is not exactly right, but I'm at my wits end trying to
5369  // figure it out. Feel free to fix it. :-)
5370  // MB: it's much easier than you think, mTime isn't warped at all!
5372  }
5373  }
5374 
5375  // Record the reported latency from PortAudio.
5376  // TODO: Don't recalculate this with every callback?
5377 
5378  // 01/21/2009: Disabled until a better solution presents itself.
5379  #if 0
5380  // As of 06/17/2006, portaudio v19 returns inputBufferAdcTime set to
5381  // zero. It is being worked on, but for now we just can't do much
5382  // but follow the leader.
5383  //
5384  // 08/27/2006: too inconsistent for now...just leave it a zero.
5385  //
5386  // 04/16/2008: Looks like si->inputLatency comes back with something useful though.
5387  // This rearranged logic uses si->inputLatency, but if PortAudio fixes inputBufferAdcTime,
5388  // this code won't have to be modified to use it.
5389  // Also avoids setting mLastRecordingOffset except when simultaneously playing and recording.
5390  //
5391  if (numCaptureChannels > 0 && numPlaybackChannels > 0) // simultaneously playing and recording
5392  {
5393  if (timeInfo->inputBufferAdcTime > 0)
5394  gAudioIO->mLastRecordingOffset = timeInfo->inputBufferAdcTime - timeInfo->outputBufferDacTime;
5395  else if (gAudioIO->mLastRecordingOffset == 0.0)
5396  {
5397  const PaStreamInfo* si = Pa_GetStreamInfo( gAudioIO->mPortStreamV19 );
5398  gAudioIO->mLastRecordingOffset = -si->inputLatency;
5399  }
5400  }
5401  #endif
5402  } // if mStreamToken > 0
5403  else {
5404  // No tracks to play, but we should clear the output, and
5405  // possibly do software playthrough...
5406 
5407  if( outputBuffer && (numPlaybackChannels > 0) ) {
5408  float *outputFloats = (float *)outputBuffer;
5409  for( i = 0; i < framesPerBuffer*numPlaybackChannels; i++)
5410  outputFloats[i] = 0.0;
5411 
5412  if (inputBuffer && gAudioIO->mSoftwarePlaythrough) {
5414  numCaptureChannels,
5415  (float *)outputBuffer, (int)framesPerBuffer);
5416  }
5417 
5418  // Copy the results to outputMeterFloats if necessary
5419  if (outputMeterFloats != outputFloats) {
5420  for (i = 0; i < framesPerBuffer*numPlaybackChannels; ++i) {
5421  outputMeterFloats[i] = outputFloats[i];
5422  }
5423  }
5424  }
5425 
5426  }
5427  /* Send data to playback VU meter if applicable */
5428  if (gAudioIO->mOutputMeter &&
5430  outputMeterFloats) {
5431  // Get here if playback meter is live
5432  /* It's critical that we don't update the meters while StopStream is
5433  * trying to stop PortAudio, otherwise it can lead to a freeze. We use
5434  * two variables to synchronize:
5435  * mUpdatingMeters tells StopStream when the callback is about to enter
5436  * the code where it might update the meters, and
5437  * mUpdateMeters is how the rest of the code tells the callback when it
5438  * is allowed to actually do the updating.
5439  * Note that mUpdatingMeters must be set first to avoid a race condition.
5440  */
5441  gAudioIO->mUpdatingMeters = true;
5442  if (gAudioIO->mUpdateMeters) {
5443  gAudioIO->mOutputMeter->UpdateDisplay(numPlaybackChannels,
5444  framesPerBuffer,
5445  outputMeterFloats);
5446 
5447  //v Vaughan, 2011-02-25: Moved this update back to TrackPanel::OnTimer()
5448  // as it helps with playback issues reported by Bill and noted on Bug 258.
5449  // The problem there occurs if Software Playthrough is on.
5450  // Could conditionally do the update here if Software Playthrough is off,
5451  // and in TrackPanel::OnTimer() if Software Playthrough is on, but not now.
5452  // PRL 12 Jul 2015: and what was in TrackPanel::OnTimer is now handled by means of event
5453  // type EVT_TRACK_PANEL_TIMER
5454  //AudacityProject* pProj = GetActiveProject();
5455  //MixerBoard* pMixerBoard = pProj->GetMixerBoard();
5456  //if (pMixerBoard)
5457  // pMixerBoard->UpdateMeters(gAudioIO->GetStreamTime(),
5458  // (pProj->mLastPlayMode == loopedPlay));
5459  }
5460  gAudioIO->mUpdatingMeters = false;
5461  } // end playback VU meter update
5462 
5463  return callbackReturn;
5464 }
5465 
5467 {
5468  return mDuration - Consumed();
5469 }
5470 
5472 {
5473  return std::max( 0.0, mPosition + TotalCorrection() );
5474 }
5475 
5477 {
5478  return std::max(0.0, -( mPosition + TotalCorrection() ) );
5479 }
5480 
5482 {
5483  return GetNumCaptureChannels() > 0 &&
5485 }
int StartStream(const TransportTracks &tracks, double t0, double t1, const AudioIOStartStreamOptions &options)
Start recording or playing back audio.
Definition: AudioIO.cpp:1864
virtual void OnAudioIOStartRecording()=0
size_t GetCommonlyAvailCapture()
Get the number of audio samples ready in all of the recording buffers.
Definition: AudioIO.cpp:3305
double LimitStreamTime(double absoluteTime) const
Clamps the given time to be between mT0 and mT1.
Definition: AudioIO.cpp:2919
void StartTag(const wxString &name) override
bool GetSolo() const
Definition: Track.h:384
AudioIO uses the PortAudio library to play and record sound.
Definition: AudioIO.h:172
A ToolBar that has the main Transport buttons.
AudacityPrefs * gPrefs
Definition: Prefs.cpp:73
wxArrayString GetInputSourceNames()
Get the list of inputs to the current mixer device.
Definition: AudioIO.cpp:1398
void StopStream()
Stop recording, playback or input monitoring.
Definition: AudioIO.cpp:2562
GrowableSampleBuffer & Resize(size_t count, sampleFormat format)
Definition: SampleFormat.h:101
double ComputeWarpedLength(double t0, double t1) const
Compute the duration (in seconds at playback) of the specified region of the track.
Definition: TimeTrack.cpp:160
bool OutputMixerEmulated()
Find out if the output level control is being emulated via software attenuation.
Definition: AudioIO.cpp:1393
size_t RealtimeProcess(int group, unsigned chans, float **buffers, size_t numSamples)
void Transformer(sampleCount &startSample, sampleCount &endSample, sampleCount &duration, Maybe< wxMutexLocker > &cleanup)
Definition: AudioIO.cpp:664
sampleCount maxSample
Definition: Scrubbing.h:44
double mMinCaptureSecsToCopy
Definition: AudioIO.h:700
std::unique_ptr< AudioIO > ugAudioIO
Definition: AudioIO.cpp:481
double GetTime(double rate) const
Definition: AudioIO.cpp:918
static std::vector< long > mCachedSampleRates
Definition: AudioIO.h:778
Duration(ScrubQueue &queue_)
Definition: AudioIO.cpp:944
root of a hierarchy of classes that are thrown and caught by Audacity.
TimeTrack * timeTrack
Definition: AudioIO.h:137
void WriteAttr(const wxString &name, const wxString &value) override
#define ENV_DB_KEY
Definition: GUISettings.h:15
double GetStreamTime()
During playback, the (unwarped) track time most recently played.
Definition: AudioIO.cpp:2960
bool IsEmpty() const
bool IsCapturing() const
Definition: AudioIO.cpp:5481
double TotalCorrection() const
Definition: AudioIO.h:857
static double mCachedBestRateIn
Definition: AudioIO.h:779
static int mNextStreamToken
Definition: AudioIO.h:675
bool GetSelected() const
Definition: Track.h:276
bool IsStreamActive()
Returns true if the audio i/o is running at all, but not during cleanup.
Definition: AudioIO.cpp:2890
void SetMissingAliasedFileWarningShouldShow(bool b)
Changes the behavior of missing aliased blockfiles warnings.
WaveTrackConstArray prerollTracks
Definition: AudioIO.h:165
enum AudioIO::@3 mPlayMode
void reinit(Integral count, bool initialize=false)
Definition: MemoryX.h:117
bool mDetectDropouts
Definition: AudioIO.h:831
sampleCount mScrubDuration
Definition: AudioIO.h:819
static std::vector< long > GetSupportedSampleRates(int playDevice=-1, int recDevice=-1, double rate=0.0)
Get a list of sample rates the current input/output device combination supports.
Definition: AudioIO.cpp:3097
void RealtimeAddProcessor(int group, unsigned chans, float rate)
wxString WarningDialogKey(const wxString &internalDialogName)
Definition: Warning.cpp:115
void CopySamples(samplePtr src, sampleFormat srcFormat, samplePtr dst, sampleFormat dstFormat, unsigned int len, bool highQuality, unsigned int srcStride, unsigned int dstStride)
bool IsAvailable(AudacityProject *projecT)
Function to automatically set an acceptable volume.
Definition: AudioIO.cpp:2516
bool mDetectUpstreamDropouts
Definition: AudioIO.h:843
volatile bool mUpdatingMeters
Definition: AudioIO.h:730
float mMixerOutputVol
Definition: AudioIO.h:746
#define USE_MIDI_THREAD
Definition: AudioIO.h:116
void SetMeters()
Set the current VU meters - this should be done once after each call to StartStream currently...
Definition: AudioIO.cpp:2547
double LastTimeInQueue() const
Definition: AudioIO.cpp:582
wxLongLong mLastScrubTimeMillis
Definition: AudioIO.cpp:967
unsigned GetNumCaptureChannels() const
Definition: AudioIO.h:399
#define SAMPLE_SIZE(SampleFormat)
Definition: Types.h:198
double Consumer(unsigned long frames)
Definition: AudioIO.cpp:748
SampleBuffer & Allocate(size_t count, sampleFormat format)
Definition: SampleFormat.h:67
double mTime
Current time position during playback, in seconds. Between mT0 and mT1.
Definition: AudioIO.h:684
sampleCount mGoal
Definition: AudioIO.cpp:929
bool mInputMixerWorks
Can we control the hardware input level?
Definition: AudioIO.h:745
bool mSoftwarePlaythrough
Definition: AudioIO.h:704
unsigned mTrailingIdx
Definition: AudioIO.cpp:963
bool GetLinked() const
Definition: Track.h:279
sampleCount mDuration
Definition: AudioIO.cpp:933
double GetLastTimeInScrubQueue() const
return the ending time of the last enqueued scrub interval.
Definition: AudioIO.cpp:2872
bool IsAudioTokenActive(int token)
Returns true if the stream is active, or even if audio I/O is busy cleaning up its data or writing to...
Definition: AudioIO.cpp:2909
double as_double() const
Definition: Types.h:88
~AudioIO()
Definition: AudioIO.cpp:1283
double NormalizeStreamTime(double absoluteTime) const
Normalizes the given time, clamping it and handling gaps from cut preview.
Definition: AudioIO.cpp:2928
const TimeTrack * mTimeTrack
Definition: AudioIO.h:769
struct AudioIO::RecordingSchedule mRecordingSchedule
int AudacityMessageBox(const wxString &message, const wxString &caption=AudacityMessageBoxCaptionStr(), long style=wxOK|wxCENTRE, wxWindow *parent=NULL, int x=wxDefaultCoord, int y=wxDefaultCoord)
Definition: ErrorDialog.h:92
Definition: MemoryX.h:204
void StartStreamCleanup(bool bOnlyBuffers=false)
Clean up after StartStream if it fails.
Definition: AudioIO.cpp:2387
void FillBuffers()
Definition: AudioIO.cpp:3789
MeterPanel * mOutputMeter
Definition: AudioIO.h:728
float GetChannelGain(int channel) const
Definition: WaveTrack.cpp:440
ArrayOf< std::unique_ptr< RingBuffer > > mPlaybackBuffers
Definition: AudioIO.h:670
virtual void OnAudioIOStopRecording()=0
bool IsBusy()
Returns true if audio i/o is busy starting, stopping, playing, or recording.
Definition: AudioIO.cpp:2882
wxString DeviceName(const PaDeviceInfo *info)
Definition: AudioIO.cpp:1154
ScrubbingOptions * pScrubbingOptions
Definition: AudioIO.h:150
MeterPanel is a panel that paints the meter used for monitoring or playback.
Definition: Meter.h:97
static int GetOptimalSupportedSampleRate()
Get a supported sample rate which can be used a an optimal default.
Definition: AudioIO.cpp:3141
Entry mEntries[Size]
Definition: AudioIO.cpp:962
const double mRate
Definition: AudioIO.cpp:966
static int getPlayDevIndex(const wxString &devName=wxEmptyString)
get the index of the device selected in the preferences.
Definition: AudioIO.cpp:3328
void StartMonitoring(double sampleRate)
Start up Portaudio for capture and recording as needed for input monitoring and software playthrough ...
Definition: AudioIO.cpp:1822
float mSilenceLevel
Definition: AudioIO.h:707
ArrayOf< std::unique_ptr< Resample > > mResample
Definition: AudioIO.h:667
void WriteSubTree(const AutoSaveFile &value)
MixerBoard * GetMixerBoard()
Definition: Project.h:516
bool InputMixerWorks()
Find out if the input hardware level control is available.
Definition: AudioIO.cpp:1388
sampleFormat mCaptureFormat
Definition: AudioIO.h:710
GrowableSampleBuffer mSilentBuf
Definition: AudioIO.h:758
wxString HostName(const PaDeviceInfo *info)
Definition: AudioIO.cpp:1161
ArrayOf< std::unique_ptr< Mixer > > mPlaybackMixers
Definition: AudioIO.h:673
void DeinitAudioIO()
Definition: AudioIO.cpp:1149
bool Init(Entry *previous, sampleCount s0, sampleCount s1, sampleCount &duration, const ScrubbingOptions &options)
Definition: AudioIO.cpp:795
std::unique_ptr< ScrubQueue > mScrubQueue
Definition: AudioIO.h:815
#define safenew
Definition: Audacity.h:230
#define BAD_STREAM_TIME
Definition: AudioIO.h:80
double mWarpedTime
Definition: AudioIO.h:689
size_t limitSampleBufferSize(size_t bufferSize, sampleCount limit)
Definition: Types.h:178
static int mCachedPlaybackIndex
Definition: AudioIO.h:774
wxMutex mSuspendAudioThread
Definition: AudioIO.h:812
#define DEFAULT_LATENCY_CORRECTION
Definition: AudioIO.h:86
wxAtomicInt mRecordingException
Definition: AudioIO.h:824
#define ENV_DB_RANGE
Definition: GUISettings.h:16
AudacityProject provides the main window, with tools and tracks contained within it.
Definition: Project.h:176
void SetPlaybackMeter(AudacityProject *project, MeterPanel *meter)
Definition: AudioIO.cpp:2535
static std::vector< long > mCachedPlaybackRates
Definition: AudioIO.h:775
PRCrossfadeData * pCrossfadeData
Definition: AudioIO.h:154
bool mPaused
True if audio playback is paused.
Definition: AudioIO.h:702
void GetMixer(int *inputSource, float *inputVolume, float *playbackVolume)
Definition: AudioIO.cpp:1357
static double MaxAllowedScrubSpeed()
Definition: Scrubbing.h:64
void EndTag(const wxString &name) override
ArrayOf< std::unique_ptr< RingBuffer > > mCaptureBuffers
Definition: AudioIO.h:668
int format
Definition: ExportPCM.cpp:56
bool ReversedTime() const
True if the end time is before the start time.
Definition: AudioIO.h:541
volatile int mStreamToken
Definition: AudioIO.h:674
double Consumed() const
Definition: AudioIO.cpp:5471
MeterPanel * GetCaptureMeter()
Definition: Project.cpp:5104
unsigned mMiddleIdx
Definition: AudioIO.cpp:964
WaveTrackArray mCaptureTracks
Definition: AudioIO.h:669
#define DEFAULT_SYNTH_LATENCY
Definition: AudioIO.h:83
bool mEmulateMixerOutputVol
Definition: AudioIO.h:737
bool Producer(double end, const ScrubbingOptions &options)
Definition: AudioIO.cpp:599
PaStream * mPortStreamV19
Definition: AudioIO.h:703
struct holding stream options, including a pointer to the TimeTrack and AudioIOListener and whether t...
Definition: AudioIO.h:123
sampleCount mS0
Definition: AudioIO.cpp:927
static std::vector< long > mCachedCaptureRates
Definition: AudioIO.h:777
void ClearRecordingException()
Definition: AudioIO.h:827
std::vector< std::shared_ptr< const WaveTrack > > WaveTrackConstArray
Definition: AudioIO.h:67
bool IsMeterDisabled() const
Find out if the level meter is disabled or not.
Definition: Meter.cpp:1773
ScrubQueue(double t0, double t1, wxLongLong startClockMillis, double rate, long maxDebt, const ScrubbingOptions &options)
Definition: AudioIO.cpp:547
double mCaptureRingBufferSecs
Definition: AudioIO.h:698
double ToDiscard() const
Definition: AudioIO.cpp:5476
bool IsPaused()
Find out if playback / recording is currently paused.
Definition: AudioIO.cpp:2857
void UpdateDisplay(unsigned numChannels, int numFrames, float *sampleData)
Update the meters with a block of audio data.
Definition: Meter.cpp:886
const wxLongLong clockTime
Definition: AudioIO.cpp:954
IteratorRange< Iterator > make_iterator_range(const Iterator &i1, const Iterator &i2)
Definition: MemoryX.h:677
const long mMaxDebt
Definition: AudioIO.cpp:972
Entry()
Definition: AudioIO.cpp:787
sampleFormat
Definition: Types.h:188
double ToConsume() const
Definition: AudioIO.cpp:5466
#define lrint(dbl)
Definition: float_cast.h:136
int audacityAudioCallback(const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo *timeInfo, PaStreamCallbackFlags statusFlags, void *userData)
char * samplePtr
Definition: Types.h:203
A Track that contains audio waveform data.
Definition: WaveTrack.h:60
double GetBestRate(bool capturing, bool playing, double sampleRate)
Return a valid sample rate that is supported by the current I/O device(s).
Definition: AudioIO.cpp:3161
bool EnqueueScrub(double endTimeOrSpeed, const ScrubbingOptions &options)
enqueue a NEW scrub play interval, using the last end as the NEW start, to be played over the same du...
Definition: AudioIO.cpp:2864
void RealtimeInitialize(double rate)
void HandleDeviceChange()
update state after changing what audio devices are selected
Definition: AudioIO.cpp:1426
if(pTrack &&pTrack->GetDisplay()!=WaveTrack::Spectrum)
AudacityProject * mOwningProject
Definition: AudioIO.h:726
EffectManager is the class that handles effects and effect categories.
Definition: EffectManager.h:45
static PaSampleFormat AudacityToPortAudioSampleFormat(sampleFormat format)
Definition: AudioIO.cpp:1627
int min(int a, int b)
wxLongLong mLastPlaybackTimeMillis
Definition: AudioIO.h:716
AudioIOListener * mListener
Definition: AudioIO.h:760
volatile bool mAudioThreadShouldCallFillBuffersOnce
Definition: AudioIO.h:712
samplePtr ptr() const
Definition: SampleFormat.h:81
wxCondition mAvailable
Definition: AudioIO.cpp:975
unsigned int mNumPlaybackChannels
Definition: AudioIO.h:709
WaveTrackConstArray playbackTracks
Definition: AudioIO.h:158
#define LAT1CTOWX(X)
Definition: Internat.h:180
R GuardedCall(const F1 &body, const F2 &handler=F2::Default(), const F3 &delayedHandler={})
double mSeek
Definition: AudioIO.h:696
unsigned int mNumCaptureChannels
Definition: AudioIO.h:708
static EffectManager & Get()
size_t GetCommonlyAvailPlayback()
Get the number of audio samples free in all of the playback buffers.
Definition: AudioIO.cpp:3296
wxLongLong mLastTransformerTimeMillis
Definition: AudioIO.cpp:969
void TP_DisplayStatusMessage(const wxString &msg) override
Definition: Project.cpp:5356
std::unique_ptr< AudioThread > mThread
Definition: AudioIO.h:661
wxWeakRef< MeterPanel > mInputMeter
Definition: AudioIO.h:727
void SetCaptureMeter(AudacityProject *project, MeterPanel *meter)
Definition: AudioIO.cpp:2521
unsigned long long mLostSamples
Definition: AudioIO.h:711
static void DoSoftwarePlaythrough(const void *inputBuffer, sampleFormat inputFormat, unsigned inputChannels, float *outputBuffer, int len)
Definition: AudioIO.cpp:4702
unsigned mLeadingIdx
Definition: AudioIO.cpp:965
sampleCount mS1
Definition: AudioIO.cpp:928
PRCrossfadeData mCrossfadeData
Definition: AudioIO.h:850
virtual void OnAudioIONewBlockFiles(const AutoSaveFile &blockFileLog)=0
double mRate
Audio playback rate in samples per second.
Definition: AudioIO.h:678
void Reset(double sampleRate, bool resetClipping)
This method is thread-safe! Feel free to call from a different thread (like from an audio I/O callbac...
Definition: Meter.cpp:826
double maxSpeed
Definition: Scrubbing.h:53
Monitors record play start/stop and new blockfiles. Has callbacks for these events.
bool mUpdateMeters
Definition: AudioIO.h:729
void SetMixer(int inputSource)
Definition: AudioIO.cpp:1325
_("Move Track &Down")+wxT("\t")+(GetActiveProject() -> GetCommandManager() ->GetKeyFromName(wxT("TrackMoveDown")).Raw()), OnMoveTrack) POPUP_MENU_ITEM(OnMoveTopID, _("Move Track to &Top")+wxT("\t")+(GetActiveProject() ->GetCommandManager() ->GetKeyFromName(wxT("TrackMoveTop")).Raw()), OnMoveTrack) POPUP_MENU_ITEM(OnMoveBottomID, _("Move Track to &Bottom")+wxT("\t")+(GetActiveProject() ->GetCommandManager() ->GetKeyFromName(wxT("TrackMoveBottom")).Raw()), OnMoveTrack)#define SET_TRACK_NAME_PLUGIN_SYMBOLclass SetTrackNameCommand:public AudacityCommand
AudioIO * gAudioIO
Definition: AudioIO.cpp:482
ControlToolBar * GetControlToolBar()
Definition: Project.cpp:5003
volatile double mLastRecordingOffset
Definition: AudioIO.h:723
void SetListener(AudioIOListener *listener)
Definition: AudioIO.cpp:4167
const wxChar * name
Definition: Distortion.cpp:94
sampleCount mCredit
Definition: AudioIO.cpp:970
bool IsMonitoring()
Returns true if we're monitoring input (but not recording or playing actual audio) ...
Definition: AudioIO.cpp:2914
double minSpeed
Definition: Scrubbing.h:52
static int mCachedCaptureIndex
Definition: AudioIO.h:776
static const int NumStandardRates
How many standard sample rates there are.
Definition: AudioIO.h:410
AUDACITY_DLL_API AudacityProject * GetActiveProject()
Definition: Project.cpp:308
void ClearSamples(samplePtr dst, sampleFormat format, size_t start, size_t len)
bool mUsingAlsa
Definition: AudioIO.h:771
double mWarpedLength
Definition: AudioIO.h:694
double mCutPreviewGapLen
Definition: AudioIO.h:756
static std::vector< long > GetSupportedCaptureRates(int devIndex=-1, double rate=0.0)
Get a list of sample rates the input (recording) device supports.
Definition: AudioIO.cpp:3031
sampleCount minSample
Definition: Scrubbing.h:45
double mT0
Playback starts at offset of mT0, which is measured in seconds.
Definition: AudioIO.h:680
double mCutPreviewGapStart
Definition: AudioIO.h:755
MeterPanel * GetPlaybackMeter()
Definition: Project.cpp:5090
virtual void OnAudioIORate(int rate)=0
wxString GetDeviceInfo()
Get diagnostic information on all the available audio I/O devices.
Definition: AudioIO.cpp:3444
static double mCachedBestRateOut
Definition: AudioIO.h:780
double SolveWarpedLength(double t0, double length) const
Compute how much unwarped time must have elapsed if length seconds of warped time has elapsed...
Definition: TimeTrack.cpp:165
bool enqueueBySpeed
Definition: Scrubbing.h:47
bool GetMute() const
Definition: Track.h:383
static const int StandardRates[]
Array of common audio sample rates.
Definition: AudioIO.h:408
std::vector< std::pair< double, double > > mLostCaptureIntervals
Definition: AudioIO.h:830
AudioIOListener * listener
Definition: AudioIO.h:138
void InitAudioIO()
Definition: AudioIO.cpp:1116
sampleCount mDebt
Definition: AudioIO.cpp:971
static const int NumRatesToTry
How many sample rates to try.
Definition: AudioIO.h:538
volatile bool mAudioThreadFillBuffersLoopActive
Definition: AudioIO.h:714
AudacityApp & wxGetApp()
static sampleFormat SampleFormatChoice()
#define DEFAULT_LATENCY_DURATION
Definition: AudioIO.h:85
sampleCount mPlayed
Definition: AudioIO.cpp:940
static const int RatesToTry[]
Array of audio sample rates to try to use.
Definition: AudioIO.h:536
void RealtimeFinalize()
double mFactor
Definition: AudioIO.h:676
size_t as_size_t() const
Definition: Types.h:92
PaError mLastPaError
Definition: AudioIO.h:724
const sampleCount duration
Definition: AudioIO.cpp:955
void ResetMeters(const bool bResetClipping)
size_t mPlaybackSamplesToCopy
Definition: AudioIO.h:699
void SetPaused(bool state)
Pause and un-pause playback and recording.
Definition: AudioIO.cpp:2840
static std::vector< long > GetSupportedPlaybackRates(int DevIndex=-1, double rate=0.0)
Get a list of sample rates the output (playback) device supports.
Definition: AudioIO.cpp:2969
void RealtimeSuspend()
#define MAX(a, b)
Definition: AudioIO.cpp:4700
bool StartPortAudioStream(double sampleRate, unsigned int numPlaybackChannels, unsigned int numCaptureChannels, sampleFormat captureFormat)
Opens the portaudio stream(s) used to do playback or recording (or both) through. ...
Definition: AudioIO.cpp:1640
Definition: AudioIO.cpp:785
static bool ValidateDeviceNames(const wxString &play, const wxString &rec)
Ensure selected device names are valid.
Definition: AudioIO.cpp:1168
void RealtimeProcessEnd()
double mT1
Playback ends at offset of mT1, which is measured in seconds. Note that mT1 may be less than mT0 duri...
Definition: AudioIO.h:682
ExitCode Entry() override
Definition: AudioIO.cpp:3243
void create(Args &&...args)
Definition: MemoryX.h:251
volatile bool mAudioThreadFillBuffersLoopRunning
Definition: AudioIO.h:713
virtual int GetChannel() const override
Definition: WaveTrack.cpp:236
WaveTrackArray captureTracks
Definition: AudioIO.h:159
bool mPauseRec
True if Sound Activated Recording is enabled.
Definition: AudioIO.h:706
void SetRecordingException()
Definition: AudioIO.h:825
bool mSilentScrub
Definition: AudioIO.h:818
static int getRecordDevIndex(const wxString &devName=wxEmptyString)
get the index of the supplied (named) recording device, or the device selected in the preferences if ...
Definition: AudioIO.cpp:3385
WaveTrackConstArray mPlaybackTracks
Definition: AudioIO.h:671
void InitSilent(const Entry &previous, sampleCount duration)
Definition: AudioIO.cpp:910
void Flush()
Flush must be called after last Append.
Definition: WaveTrack.cpp:1650
static double MinAllowedScrubSpeed()
Definition: Scrubbing.h:66
friend int audacityAudioCallback(const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo *timeInfo, PaStreamCallbackFlags statusFlags, void *userData)
void RealtimeProcessStart()
a class wrapping reading and writing of arbitrary data in text or binary format to a file...
Definition: AutoRecovery.h:76
bool mSimulateRecordingErrors
Definition: AudioIO.h:839
wxDEFINE_EVENT(EVT_AUDIOIO_PLAYBACK, wxCommandEvent)
double mPlaybackRingBufferSecs
Definition: AudioIO.h:697
Defined different on Mac and other platforms (on Mac it does not use wxWidgets wxThread), this class sits in a thread loop reading and writing audio.
Definition: AudioIO.cpp:1094