forked from audacity/audacity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AudioIOBase.cpp
1354 lines (1129 loc) · 41.8 KB
/
AudioIOBase.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**********************************************************************
Audacity: A Digital Audio Editor
AudioIOBase.cpp
Paul Licameli split from AudioIO.cpp
**********************************************************************/
#include "Audacity.h"
#include "AudioIOBase.h"
#include "Experimental.h"
#include <wx/sstream.h>
#include <wx/txtstrm.h>
#include "Envelope.h"
#include "Prefs.h"
#include "prefs/RecordingPrefs.h"
#include "widgets/MeterPanelBase.h"
#if USE_PORTMIXER
#include "portmixer.h"
#endif
#ifdef EXPERIMENTAL_MIDI_OUT
#include "../lib-src/portmidi/pm_common/portmidi.h"
#endif
int AudioIOBase::mCachedPlaybackIndex = -1;
std::vector<long> AudioIOBase::mCachedPlaybackRates;
int AudioIOBase::mCachedCaptureIndex = -1;
std::vector<long> AudioIOBase::mCachedCaptureRates;
std::vector<long> AudioIOBase::mCachedSampleRates;
double AudioIOBase::mCachedBestRateIn = 0.0;
const int AudioIOBase::StandardRates[] = {
8000,
11025,
16000,
22050,
32000,
44100,
48000,
88200,
96000,
176400,
192000,
352800,
384000
};
const int AudioIOBase::NumStandardRates = WXSIZEOF(AudioIOBase::StandardRates);
const int AudioIOBase::RatesToTry[] = {
8000,
9600,
11025,
12000,
15000,
16000,
22050,
24000,
32000,
44100,
48000,
88200,
96000,
176400,
192000,
352800,
384000
};
const int AudioIOBase::NumRatesToTry = WXSIZEOF(AudioIOBase::RatesToTry);
wxString AudioIOBase::DeviceName(const PaDeviceInfo* info)
{
wxString infoName = wxSafeConvertMB2WX(info->name);
return infoName;
}
wxString AudioIOBase::HostName(const PaDeviceInfo* info)
{
wxString hostapiName = wxSafeConvertMB2WX(Pa_GetHostApiInfo(info->hostApi)->name);
return hostapiName;
}
std::unique_ptr<AudioIOBase> AudioIOBase::ugAudioIO;
AudioIOBase *AudioIOBase::Get()
{
return ugAudioIO.get();
}
AudioIOBase::~AudioIOBase() = default;
void AudioIOBase::SetMixer(int inputSource)
{
#if defined(USE_PORTMIXER)
int oldRecordSource = Px_GetCurrentInputSource(mPortMixer);
if ( inputSource != oldRecordSource )
Px_SetCurrentInputSource(mPortMixer, inputSource);
#endif
}
void AudioIOBase::HandleDeviceChange()
{
// This should not happen, but it would screw things up if it did.
// Vaughan, 2010-10-08: But it *did* happen, due to a bug, and nobody
// caught it because this method just returned. Added wxASSERT().
wxASSERT(!IsStreamActive());
if (IsStreamActive())
return;
// get the selected record and playback devices
const int playDeviceNum = getPlayDevIndex();
const int recDeviceNum = getRecordDevIndex();
// If no change needed, return
if (mCachedPlaybackIndex == playDeviceNum &&
mCachedCaptureIndex == recDeviceNum)
return;
// cache playback/capture rates
mCachedPlaybackRates = GetSupportedPlaybackRates(playDeviceNum);
mCachedCaptureRates = GetSupportedCaptureRates(recDeviceNum);
mCachedSampleRates = GetSupportedSampleRates(playDeviceNum, recDeviceNum);
mCachedPlaybackIndex = playDeviceNum;
mCachedCaptureIndex = recDeviceNum;
mCachedBestRateIn = 0.0;
#if defined(USE_PORTMIXER)
// if we have a PortMixer object, close it down
if (mPortMixer) {
#if __WXMAC__
// on the Mac we must make sure that we restore the hardware playthrough
// state of the sound device to what it was before, because there isn't
// a UI for this (!)
if (Px_SupportsPlaythrough(mPortMixer) && mPreviousHWPlaythrough >= 0.0)
Px_SetPlaythrough(mPortMixer, mPreviousHWPlaythrough);
mPreviousHWPlaythrough = -1.0;
#endif
Px_CloseMixer(mPortMixer);
mPortMixer = NULL;
}
// that might have given us no rates whatsoever, so we have to guess an
// answer to do the next bit
int numrates = mCachedSampleRates.size();
int highestSampleRate;
if (numrates > 0)
{
highestSampleRate = mCachedSampleRates[numrates - 1];
}
else
{ // we don't actually have any rates that work for Rec and Play. Guess one
// to use for messing with the mixer, which doesn't actually do either
highestSampleRate = 44100;
// mCachedSampleRates is still empty, but it's not used again, so
// can ignore
}
mInputMixerWorks = false;
mEmulateMixerOutputVol = true;
mMixerOutputVol = 1.0;
int error;
// This tries to open the device with the samplerate worked out above, which
// will be the highest available for play and record on the device, or
// 44.1kHz if the info cannot be fetched.
PaStream *stream;
PaStreamParameters playbackParameters;
playbackParameters.device = playDeviceNum;
playbackParameters.sampleFormat = paFloat32;
playbackParameters.hostApiSpecificStreamInfo = NULL;
playbackParameters.channelCount = 1;
if (Pa_GetDeviceInfo(playDeviceNum))
playbackParameters.suggestedLatency =
Pa_GetDeviceInfo(playDeviceNum)->defaultLowOutputLatency;
else
playbackParameters.suggestedLatency = DEFAULT_LATENCY_CORRECTION/1000.0;
PaStreamParameters captureParameters;
captureParameters.device = recDeviceNum;
captureParameters.sampleFormat = paFloat32;;
captureParameters.hostApiSpecificStreamInfo = NULL;
captureParameters.channelCount = 1;
if (Pa_GetDeviceInfo(recDeviceNum))
captureParameters.suggestedLatency =
Pa_GetDeviceInfo(recDeviceNum)->defaultLowInputLatency;
else
captureParameters.suggestedLatency = DEFAULT_LATENCY_CORRECTION/1000.0;
// try opening for record and playback
// Not really doing I/O so pass nullptr for the callback function
error = Pa_OpenStream(&stream,
&captureParameters, &playbackParameters,
highestSampleRate, paFramesPerBufferUnspecified,
paClipOff | paDitherOff,
nullptr, NULL);
if (!error) {
// Try portmixer for this stream
mPortMixer = Px_OpenMixer(stream, 0);
if (!mPortMixer) {
Pa_CloseStream(stream);
error = true;
}
}
// if that failed, try just for record
if( error ) {
error = Pa_OpenStream(&stream,
&captureParameters, NULL,
highestSampleRate, paFramesPerBufferUnspecified,
paClipOff | paDitherOff,
nullptr, NULL);
if (!error) {
mPortMixer = Px_OpenMixer(stream, 0);
if (!mPortMixer) {
Pa_CloseStream(stream);
error = true;
}
}
}
// finally, try just for playback
if ( error ) {
error = Pa_OpenStream(&stream,
NULL, &playbackParameters,
highestSampleRate, paFramesPerBufferUnspecified,
paClipOff | paDitherOff,
nullptr, NULL);
if (!error) {
mPortMixer = Px_OpenMixer(stream, 0);
if (!mPortMixer) {
Pa_CloseStream(stream);
error = true;
}
}
}
// FIXME: TRAP_ERR errors in HandleDeviceChange not reported.
// if it's still not working, give up
if( error )
return;
// Set input source
#if USE_PORTMIXER
int sourceIndex;
if (gPrefs->Read(wxT("/AudioIO/RecordingSourceIndex"), &sourceIndex)) {
if (sourceIndex >= 0) {
//the current index of our source may be different because the stream
//is a combination of two devices, so update it.
sourceIndex = getRecordSourceIndex(mPortMixer);
if (sourceIndex >= 0)
SetMixer(sourceIndex);
}
}
#endif
// Determine mixer capabilities - if it doesn't support control of output
// signal level, we emulate it (by multiplying this value by all outgoing
// samples)
mMixerOutputVol = Px_GetPCMOutputVolume(mPortMixer);
mEmulateMixerOutputVol = false;
Px_SetPCMOutputVolume(mPortMixer, 0.0);
if (Px_GetPCMOutputVolume(mPortMixer) > 0.1)
mEmulateMixerOutputVol = true;
Px_SetPCMOutputVolume(mPortMixer, 0.2f);
if (Px_GetPCMOutputVolume(mPortMixer) < 0.1 ||
Px_GetPCMOutputVolume(mPortMixer) > 0.3)
mEmulateMixerOutputVol = true;
Px_SetPCMOutputVolume(mPortMixer, mMixerOutputVol);
float inputVol = Px_GetInputVolume(mPortMixer);
mInputMixerWorks = true; // assume it works unless proved wrong
Px_SetInputVolume(mPortMixer, 0.0);
if (Px_GetInputVolume(mPortMixer) > 0.1)
mInputMixerWorks = false; // can't set to zero
Px_SetInputVolume(mPortMixer, 0.2f);
if (Px_GetInputVolume(mPortMixer) < 0.1 ||
Px_GetInputVolume(mPortMixer) > 0.3)
mInputMixerWorks = false; // can't set level accurately
Px_SetInputVolume(mPortMixer, inputVol);
Pa_CloseStream(stream);
#if 0
wxPrintf("PortMixer: Playback: %s Recording: %s\n",
mEmulateMixerOutputVol? "emulated": "native",
mInputMixerWorks? "hardware": "no control");
#endif
mMixerOutputVol = 1.0;
#endif // USE_PORTMIXER
}
void AudioIOBase::SetCaptureMeter(AudacityProject *project, MeterPanelBase *meter)
{
if (( mOwningProject ) && ( mOwningProject != project))
return;
if (meter)
{
mInputMeter = meter;
mInputMeter->Reset(mRate, true);
}
else
mInputMeter.Release();
}
void AudioIOBase::SetPlaybackMeter(AudacityProject *project, MeterPanelBase *meter)
{
if (( mOwningProject ) && ( mOwningProject != project))
return;
if (meter)
{
mOutputMeter = meter;
mOutputMeter->Reset(mRate, true);
}
else
mOutputMeter.Release();
}
bool AudioIOBase::IsPaused() const
{
return mPaused;
}
bool AudioIOBase::IsBusy() const
{
if (mStreamToken != 0)
return true;
return false;
}
bool AudioIOBase::IsStreamActive() const
{
bool isActive = false;
// JKC: Not reporting any Pa error, but that looks OK.
if( mPortStreamV19 )
isActive = (Pa_IsStreamActive( mPortStreamV19 ) > 0);
#ifdef EXPERIMENTAL_MIDI_OUT
if( mMidiStreamActive && !mMidiOutputComplete )
isActive = true;
#endif
return isActive;
}
bool AudioIOBase::IsStreamActive(int token) const
{
return (this->IsStreamActive() && this->IsAudioTokenActive(token));
}
bool AudioIOBase::IsAudioTokenActive(int token) const
{
return ( token > 0 && token == mStreamToken );
}
bool AudioIOBase::IsMonitoring() const
{
return ( mPortStreamV19 && mStreamToken==0 );
}
void AudioIOBase::PlaybackSchedule::Init(
const double t0, const double t1,
const AudioIOStartStreamOptions &options,
const RecordingSchedule *pRecordingSchedule )
{
if ( pRecordingSchedule )
// It does not make sense to apply the time warp during overdub recording,
// which defeats the purpose of making the recording synchronized with
// the existing audio. (Unless we figured out the inverse warp of the
// captured samples in real time.)
// So just quietly ignore the time track.
mEnvelope = nullptr;
else
mEnvelope = options.envelope;
mT0 = t0;
if (pRecordingSchedule)
mT0 -= pRecordingSchedule->mPreRoll;
mT1 = t1;
if (pRecordingSchedule)
// adjust mT1 so that we don't give paComplete too soon to fill up the
// desired length of recording
mT1 -= pRecordingSchedule->mLatencyCorrection;
// Main thread's initialization of mTime
SetTrackTime( mT0 );
mPlayMode = options.playLooped
? PlaybackSchedule::PLAY_LOOPED
: PlaybackSchedule::PLAY_STRAIGHT;
mCutPreviewGapStart = options.cutPreviewGapStart;
mCutPreviewGapLen = options.cutPreviewGapLen;
#ifdef EXPERIMENTAL_SCRUBBING_SUPPORT
bool scrubbing = (options.pScrubbingOptions != nullptr);
// Scrubbing is not compatible with looping or recording or a time track!
if (scrubbing)
{
const auto &scrubOptions = *options.pScrubbingOptions;
if (pRecordingSchedule ||
Looping() ||
mEnvelope ||
scrubOptions.maxSpeed < ScrubbingOptions::MinAllowedScrubSpeed()) {
wxASSERT(false);
scrubbing = false;
}
else
mPlayMode = (scrubOptions.isPlayingAtSpeed)
? PlaybackSchedule::PLAY_AT_SPEED
: PlaybackSchedule::PLAY_SCRUB;
}
#endif
mWarpedTime = 0.0;
#ifdef EXPERIMENTAL_SCRUBBING_SUPPORT
if (Scrubbing())
mWarpedLength = 0.0f;
else
#endif
mWarpedLength = RealDuration(mT1);
}
double AudioIOBase::PlaybackSchedule::LimitTrackTime() const
{
// Track time readout for the main thread
// Allows for forward or backward play
return ClampTrackTime( GetTrackTime() );
}
double AudioIOBase::PlaybackSchedule::ClampTrackTime( double trackTime ) const
{
if (ReversedTime())
return std::max(mT1, std::min(mT0, trackTime));
else
return std::max(mT0, std::min(mT1, trackTime));
}
double AudioIOBase::PlaybackSchedule::NormalizeTrackTime() const
{
// Track time readout for the main thread
// dmazzoni: This function is needed for two reasons:
// One is for looped-play mode - this function makes sure that the
// position indicator keeps wrapping around. The other reason is
// more subtle - it's because PortAudio can query the hardware for
// the current stream time, and this query is not always accurate.
// Sometimes it's a little behind or ahead, and so this function
// makes sure that at least we clip it to the selection.
//
// msmeyer: There is also the possibility that we are using "cut preview"
// mode. In this case, we should jump over a defined "gap" in the
// audio.
double absoluteTime;
#ifdef EXPERIMENTAL_SCRUBBING_SUPPORT
// Limit the time between t0 and t1 if not scrubbing.
// Should the limiting be necessary in any play mode if there are no bugs?
if (Interactive())
absoluteTime = GetTrackTime();
else
#endif
absoluteTime = LimitTrackTime();
if (mCutPreviewGapLen > 0)
{
// msmeyer: We're in cut preview mode, so if we are on the right
// side of the gap, we jump over it.
if (absoluteTime > mCutPreviewGapStart)
absoluteTime += mCutPreviewGapLen;
}
return absoluteTime;
}
double AudioIOBase::GetStreamTime()
{
// Track time readout for the main thread
if( !IsStreamActive() )
return BAD_STREAM_TIME;
return mPlaybackSchedule.NormalizeTrackTime();
}
std::vector<long> AudioIOBase::GetSupportedPlaybackRates(int devIndex, double rate)
{
if (devIndex == -1)
{ // weren't given a device index, get the prefs / default one
devIndex = getPlayDevIndex();
}
// Check if we can use the cached rates
if (mCachedPlaybackIndex != -1 && devIndex == mCachedPlaybackIndex
&& (rate == 0.0 || make_iterator_range(mCachedPlaybackRates).contains(rate)))
{
return mCachedPlaybackRates;
}
std::vector<long> supported;
int irate = (int)rate;
const PaDeviceInfo* devInfo = NULL;
int i;
devInfo = Pa_GetDeviceInfo(devIndex);
if (!devInfo)
{
wxLogDebug(wxT("GetSupportedPlaybackRates() Could not get device info!"));
return supported;
}
// LLL: Remove when a proper method of determining actual supported
// DirectSound rate is devised.
const PaHostApiInfo* hostInfo = Pa_GetHostApiInfo(devInfo->hostApi);
bool isDirectSound = (hostInfo && hostInfo->type == paDirectSound);
PaStreamParameters pars;
pars.device = devIndex;
pars.channelCount = 1;
pars.sampleFormat = paFloat32;
pars.suggestedLatency = devInfo->defaultHighOutputLatency;
pars.hostApiSpecificStreamInfo = NULL;
// JKC: PortAudio Errors handled OK here. No need to report them
for (i = 0; i < NumRatesToTry; i++)
{
// LLL: Remove when a proper method of determining actual supported
// DirectSound rate is devised.
if (!(isDirectSound && RatesToTry[i] > 200000)){
if (Pa_IsFormatSupported(NULL, &pars, RatesToTry[i]) == 0)
supported.push_back(RatesToTry[i]);
Pa_Sleep( 10 );// There are ALSA drivers that don't like being probed
// too quickly.
}
}
if (irate != 0 && !make_iterator_range(supported).contains(irate))
{
// LLL: Remove when a proper method of determining actual supported
// DirectSound rate is devised.
if (!(isDirectSound && RatesToTry[i] > 200000))
if (Pa_IsFormatSupported(NULL, &pars, irate) == 0)
supported.push_back(irate);
}
return supported;
}
std::vector<long> AudioIOBase::GetSupportedCaptureRates(int devIndex, double rate)
{
if (devIndex == -1)
{ // not given a device, look up in prefs / default
devIndex = getRecordDevIndex();
}
// Check if we can use the cached rates
if (mCachedCaptureIndex != -1 && devIndex == mCachedCaptureIndex
&& (rate == 0.0 || make_iterator_range(mCachedCaptureRates).contains(rate)))
{
return mCachedCaptureRates;
}
std::vector<long> supported;
int irate = (int)rate;
const PaDeviceInfo* devInfo = NULL;
int i;
devInfo = Pa_GetDeviceInfo(devIndex);
if (!devInfo)
{
wxLogDebug(wxT("GetSupportedCaptureRates() Could not get device info!"));
return supported;
}
double latencyDuration = DEFAULT_LATENCY_DURATION;
long recordChannels = 1;
gPrefs->Read(wxT("/AudioIO/LatencyDuration"), &latencyDuration);
gPrefs->Read(wxT("/AudioIO/RecordChannels"), &recordChannels);
// LLL: Remove when a proper method of determining actual supported
// DirectSound rate is devised.
const PaHostApiInfo* hostInfo = Pa_GetHostApiInfo(devInfo->hostApi);
bool isDirectSound = (hostInfo && hostInfo->type == paDirectSound);
PaStreamParameters pars;
pars.device = devIndex;
pars.channelCount = recordChannels;
pars.sampleFormat = paFloat32;
pars.suggestedLatency = latencyDuration / 1000.0;
pars.hostApiSpecificStreamInfo = NULL;
for (i = 0; i < NumRatesToTry; i++)
{
// LLL: Remove when a proper method of determining actual supported
// DirectSound rate is devised.
if (!(isDirectSound && RatesToTry[i] > 200000))
{
if (Pa_IsFormatSupported(&pars, NULL, RatesToTry[i]) == 0)
supported.push_back(RatesToTry[i]);
Pa_Sleep( 10 );// There are ALSA drivers that don't like being probed
// too quickly.
}
}
if (irate != 0 && !make_iterator_range(supported).contains(irate))
{
// LLL: Remove when a proper method of determining actual supported
// DirectSound rate is devised.
if (!(isDirectSound && RatesToTry[i] > 200000))
if (Pa_IsFormatSupported(&pars, NULL, irate) == 0)
supported.push_back(irate);
}
return supported;
}
std::vector<long> AudioIOBase::GetSupportedSampleRates(
int playDevice, int recDevice, double rate)
{
// Not given device indices, look up prefs
if (playDevice == -1) {
playDevice = getPlayDevIndex();
}
if (recDevice == -1) {
recDevice = getRecordDevIndex();
}
// Check if we can use the cached rates
if (mCachedPlaybackIndex != -1 && mCachedCaptureIndex != -1 &&
playDevice == mCachedPlaybackIndex &&
recDevice == mCachedCaptureIndex &&
(rate == 0.0 || make_iterator_range(mCachedSampleRates).contains(rate)))
{
return mCachedSampleRates;
}
auto playback = GetSupportedPlaybackRates(playDevice, rate);
auto capture = GetSupportedCaptureRates(recDevice, rate);
int i;
// Return only sample rates which are in both arrays
std::vector<long> result;
for (i = 0; i < (int)playback.size(); i++)
if (make_iterator_range(capture).contains(playback[i]))
result.push_back(playback[i]);
// If this yields no results, use the default sample rates nevertheless
/* if (result.empty())
{
for (i = 0; i < NumStandardRates; i++)
result.push_back(StandardRates[i]);
}*/
return result;
}
/** \todo: should this take into account PortAudio's value for
* PaDeviceInfo::defaultSampleRate? In principal this should let us work out
* which rates are "real" and which resampled in the drivers, and so prefer
* the real rates. */
int AudioIOBase::GetOptimalSupportedSampleRate()
{
auto rates = GetSupportedSampleRates();
if (make_iterator_range(rates).contains(44100))
return 44100;
if (make_iterator_range(rates).contains(48000))
return 48000;
// if there are no supported rates, the next bit crashes. So check first,
// and give them a "sensible" value if there are no valid values. They
// will still get an error later, but with any luck may have changed
// something by then. It's no worse than having an invalid default rate
// stored in the preferences, which we don't check for
if (rates.empty()) return 44100;
return rates.back();
}
#if USE_PORTMIXER
int AudioIOBase::getRecordSourceIndex(PxMixer *portMixer)
{
int i;
wxString sourceName = gPrefs->Read(wxT("/AudioIO/RecordingSource"), wxT(""));
int numSources = Px_GetNumInputSources(portMixer);
for (i = 0; i < numSources; i++) {
if (sourceName == wxString(wxSafeConvertMB2WX(Px_GetInputSourceName(portMixer, i))))
return i;
}
return -1;
}
#endif
int AudioIOBase::getPlayDevIndex(const wxString &devNameArg)
{
wxString devName(devNameArg);
// if we don't get given a device, look up the preferences
if (devName.empty())
{
devName = gPrefs->Read(wxT("/AudioIO/PlaybackDevice"), wxT(""));
}
wxString hostName = gPrefs->Read(wxT("/AudioIO/Host"), wxT(""));
PaHostApiIndex hostCnt = Pa_GetHostApiCount();
PaHostApiIndex hostNum;
for (hostNum = 0; hostNum < hostCnt; hostNum++)
{
const PaHostApiInfo *hinfo = Pa_GetHostApiInfo(hostNum);
if (hinfo && wxString(wxSafeConvertMB2WX(hinfo->name)) == hostName)
{
for (PaDeviceIndex hostDevice = 0; hostDevice < hinfo->deviceCount; hostDevice++)
{
PaDeviceIndex deviceNum = Pa_HostApiDeviceIndexToDeviceIndex(hostNum, hostDevice);
const PaDeviceInfo *dinfo = Pa_GetDeviceInfo(deviceNum);
if (dinfo && DeviceName(dinfo) == devName && dinfo->maxOutputChannels > 0 )
{
// this device name matches the stored one, and works.
// So we say this is the answer and return it
return deviceNum;
}
}
// The device wasn't found so use the default for this host.
// LL: At this point, preferences and active no longer match.
return hinfo->defaultOutputDevice;
}
}
// The host wasn't found, so use the default output device.
// FIXME: TRAP_ERR PaErrorCode not handled well (this code is similar to input code
// and the input side has more comments.)
PaDeviceIndex deviceNum = Pa_GetDefaultOutputDevice();
// Sometimes PortAudio returns -1 if it cannot find a suitable default
// device, so we just use the first one available
//
// LL: At this point, preferences and active no longer match
//
// And I can't imagine how far we'll get specifying an "invalid" index later
// on...are we certain "0" even exists?
if (deviceNum < 0) {
wxASSERT(false);
deviceNum = 0;
}
return deviceNum;
}
int AudioIOBase::getRecordDevIndex(const wxString &devNameArg)
{
wxString devName(devNameArg);
// if we don't get given a device, look up the preferences
if (devName.empty())
{
devName = gPrefs->Read(wxT("/AudioIO/RecordingDevice"), wxT(""));
}
wxString hostName = gPrefs->Read(wxT("/AudioIO/Host"), wxT(""));
PaHostApiIndex hostCnt = Pa_GetHostApiCount();
PaHostApiIndex hostNum;
for (hostNum = 0; hostNum < hostCnt; hostNum++)
{
const PaHostApiInfo *hinfo = Pa_GetHostApiInfo(hostNum);
if (hinfo && wxString(wxSafeConvertMB2WX(hinfo->name)) == hostName)
{
for (PaDeviceIndex hostDevice = 0; hostDevice < hinfo->deviceCount; hostDevice++)
{
PaDeviceIndex deviceNum = Pa_HostApiDeviceIndexToDeviceIndex(hostNum, hostDevice);
const PaDeviceInfo *dinfo = Pa_GetDeviceInfo(deviceNum);
if (dinfo && DeviceName(dinfo) == devName && dinfo->maxInputChannels > 0 )
{
// this device name matches the stored one, and works.
// So we say this is the answer and return it
return deviceNum;
}
}
// The device wasn't found so use the default for this host.
// LL: At this point, preferences and active no longer match.
return hinfo->defaultInputDevice;
}
}
// The host wasn't found, so use the default input device.
// FIXME: TRAP_ERR PaErrorCode not handled well in getRecordDevIndex()
PaDeviceIndex deviceNum = Pa_GetDefaultInputDevice();
// Sometimes PortAudio returns -1 if it cannot find a suitable default
// device, so we just use the first one available
// PortAudio has an error reporting function. We should log/report the error?
//
// LL: At this point, preferences and active no longer match
//
// And I can't imagine how far we'll get specifying an "invalid" index later
// on...are we certain "0" even exists?
if (deviceNum < 0) {
// JKC: This ASSERT will happen if you run with no config file
// This happens once. Config file will exist on the next run.
// TODO: Look into this a bit more. Could be relevant to blank Device Toolbar.
wxASSERT(false);
deviceNum = 0;
}
return deviceNum;
}
wxString AudioIOBase::GetDeviceInfo()
{
wxStringOutputStream o;
wxTextOutputStream s(o, wxEOL_UNIX);
if (IsStreamActive()) {
return _("Stream is active ... unable to gather information.\n");
}
// FIXME: TRAP_ERR PaErrorCode not handled. 3 instances in GetDeviceInfo().
int recDeviceNum = Pa_GetDefaultInputDevice();
int playDeviceNum = Pa_GetDefaultOutputDevice();
int cnt = Pa_GetDeviceCount();
// PRL: why only into the log?
wxLogDebug(wxT("Portaudio reports %d audio devices"),cnt);
s << wxT("==============================\n");
s << wxString::Format(_("Default recording device number: %d\n"), recDeviceNum);
s << wxString::Format(_("Default playback device number: %d\n"), playDeviceNum);
wxString recDevice = gPrefs->Read(wxT("/AudioIO/RecordingDevice"), wxT(""));
wxString playDevice = gPrefs->Read(wxT("/AudioIO/PlaybackDevice"), wxT(""));
int j;
// This gets info on all available audio devices (input and output)
if (cnt <= 0) {
s << _("No devices found\n");
return o.GetString();
}
const PaDeviceInfo* info;
for (j = 0; j < cnt; j++) {
s << wxT("==============================\n");
info = Pa_GetDeviceInfo(j);
if (!info) {
s << wxString::Format(_("Device info unavailable for: %d\n"), j);
continue;
}
wxString name = DeviceName(info);
s << wxString::Format(_("Device ID: %d\n"), j);
s << wxString::Format(_("Device name: %s\n"), name);
s << wxString::Format(_("Host name: %s\n"), HostName(info));
s << wxString::Format(_("Recording channels: %d\n"), info->maxInputChannels);
s << wxString::Format(_("Playback channels: %d\n"), info->maxOutputChannels);
s << wxString::Format(_("Low Recording Latency: %g\n"), info->defaultLowInputLatency);
s << wxString::Format(_("Low Playback Latency: %g\n"), info->defaultLowOutputLatency);
s << wxString::Format(_("High Recording Latency: %g\n"), info->defaultHighInputLatency);
s << wxString::Format(_("High Playback Latency: %g\n"), info->defaultHighOutputLatency);
auto rates = GetSupportedPlaybackRates(j, 0.0);
/* i18n-hint: Supported, meaning made available by the system */
s << _("Supported Rates:\n");
for (int k = 0; k < (int) rates.size(); k++) {
s << wxT(" ") << (int)rates[k] << wxT("\n");
}
if (name == playDevice && info->maxOutputChannels > 0)
playDeviceNum = j;
if (name == recDevice && info->maxInputChannels > 0)
recDeviceNum = j;
// Sometimes PortAudio returns -1 if it cannot find a suitable default
// device, so we just use the first one available
if (recDeviceNum < 0 && info->maxInputChannels > 0){
recDeviceNum = j;
}
if (playDeviceNum < 0 && info->maxOutputChannels > 0){
playDeviceNum = j;
}
}
bool haveRecDevice = (recDeviceNum >= 0);
bool havePlayDevice = (playDeviceNum >= 0);
s << wxT("==============================\n");
if (haveRecDevice)
s << wxString::Format(_("Selected recording device: %d - %s\n"), recDeviceNum, recDevice);
else
s << wxString::Format(_("No recording device found for '%s'.\n"), recDevice);
if (havePlayDevice)
s << wxString::Format(_("Selected playback device: %d - %s\n"), playDeviceNum, playDevice);
else
s << wxString::Format(_("No playback device found for '%s'.\n"), playDevice);
std::vector<long> supportedSampleRates;
if (havePlayDevice && haveRecDevice) {
supportedSampleRates = GetSupportedSampleRates(playDeviceNum, recDeviceNum);
s << _("Supported Rates:\n");
for (int k = 0; k < (int) supportedSampleRates.size(); k++) {
s << wxT(" ") << (int)supportedSampleRates[k] << wxT("\n");
}
}
else {
s << _("Cannot check mutual sample rates without both devices.\n");
return o.GetString();
}
#if defined(USE_PORTMIXER)
if (supportedSampleRates.size() > 0)
{
int highestSampleRate = supportedSampleRates.back();
bool EmulateMixerInputVol = true;
bool EmulateMixerOutputVol = true;
float MixerInputVol = 1.0;
float MixerOutputVol = 1.0;
int error;
PaStream *stream;
PaStreamParameters playbackParameters;
playbackParameters.device = playDeviceNum;
playbackParameters.sampleFormat = paFloat32;
playbackParameters.hostApiSpecificStreamInfo = NULL;
playbackParameters.channelCount = 1;
if (Pa_GetDeviceInfo(playDeviceNum)){
playbackParameters.suggestedLatency =
Pa_GetDeviceInfo(playDeviceNum)->defaultLowOutputLatency;
}
else{
playbackParameters.suggestedLatency = DEFAULT_LATENCY_CORRECTION/1000.0;
}
PaStreamParameters captureParameters;
captureParameters.device = recDeviceNum;
captureParameters.sampleFormat = paFloat32;;
captureParameters.hostApiSpecificStreamInfo = NULL;
captureParameters.channelCount = 1;
if (Pa_GetDeviceInfo(recDeviceNum)){
captureParameters.suggestedLatency =
Pa_GetDeviceInfo(recDeviceNum)->defaultLowInputLatency;
}else{
captureParameters.suggestedLatency = DEFAULT_LATENCY_CORRECTION/1000.0;
}
// Not really doing I/O so pass nullptr for the callback function
error = Pa_OpenStream(&stream,
&captureParameters, &playbackParameters,
highestSampleRate, paFramesPerBufferUnspecified,
paClipOff | paDitherOff,
nullptr, NULL);
if (error) {
error = Pa_OpenStream(&stream,
&captureParameters, NULL,
highestSampleRate, paFramesPerBufferUnspecified,
paClipOff | paDitherOff,
nullptr, NULL);
}