forked from Sneeds-Feed-and-Seed/sneedacity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProjectAudioManager.cpp
1178 lines (996 loc) · 37.3 KB
/
ProjectAudioManager.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
/**********************************************************************
Sneedacity: A Digital Audio Editor
ProjectAudioManager.cpp
Paul Licameli split from ProjectManager.cpp
**********************************************************************/
#include "ProjectAudioManager.h"
#include <wx/frame.h>
#include <wx/statusbr.h>
#include "AudioIO.h"
#include "CommonCommandFlags.h"
#include "LabelTrack.h"
#include "Menus.h"
#include "Project.h"
#include "ProjectAudioIO.h"
#include "ProjectFileIO.h"
#include "ProjectHistory.h"
#include "ProjectSettings.h"
#include "ProjectStatus.h"
#include "TimeTrack.h"
#include "TrackPanelAx.h"
#include "UndoManager.h"
#include "ViewInfo.h"
#include "WaveTrack.h"
#include "toolbars/ToolManager.h"
#include "prefs/TracksPrefs.h"
#include "tracks/ui/Scrubbing.h"
#include "tracks/ui/TrackView.h"
#include "widgets/ErrorDialog.h"
#include "widgets/MeterPanelBase.h"
#include "widgets/Warning.h"
#include "widgets/SneedacityMessageBox.h"
static SneedacityProject::AttachedObjects::RegisteredFactory
sProjectAudioManagerKey {
[]( SneedacityProject &project ) {
return std::make_shared< ProjectAudioManager >( project );
}
};
ProjectAudioManager &ProjectAudioManager::Get( SneedacityProject &project )
{
return project.AttachedObjects::Get< ProjectAudioManager >(
sProjectAudioManagerKey );
}
const ProjectAudioManager &ProjectAudioManager::Get(
const SneedacityProject &project )
{
return Get( const_cast< SneedacityProject & >( project ) );
}
ProjectAudioManager::ProjectAudioManager( SneedacityProject &project )
: mProject{ project }
{
static ProjectStatus::RegisteredStatusWidthFunction
registerStatusWidthFunction{ StatusWidthFunction };
project.Bind( EVT_CHECKPOINT_FAILURE,
&ProjectAudioManager::OnCheckpointFailure, this );
}
ProjectAudioManager::~ProjectAudioManager() = default;
static TranslatableString FormatRate( int rate )
{
if (rate > 0) {
return XO("Actual Rate: %d").Format( rate );
}
else
// clear the status field
return {};
}
auto ProjectAudioManager::StatusWidthFunction(
const SneedacityProject &project, StatusBarField field )
-> ProjectStatus::StatusWidthResult
{
if ( field == rateStatusBarField ) {
auto &audioManager = ProjectAudioManager::Get( project );
int rate = audioManager.mDisplayedRate;
return {
{ { FormatRate( rate ) } },
50
};
}
return {};
}
/*! @excsafety{Strong} -- For state of mCutPreviewTracks */
int ProjectAudioManager::PlayPlayRegion(const SelectedRegion &selectedRegion,
const AudioIOStartStreamOptions &options,
PlayMode mode,
bool backwards, /* = false */
bool playWhiteSpace /* = false */)
{
auto &projectAudioManager = *this;
bool canStop = projectAudioManager.CanStopAudioStream();
if ( !canStop )
return -1;
bool useMidi = true;
// Remove these lines to experiment with scrubbing/seeking of note tracks
if (options.pScrubbingOptions)
useMidi = false;
// Uncomment this for laughs!
// backwards = true;
double t0 = selectedRegion.t0();
double t1 = selectedRegion.t1();
// SelectedRegion guarantees t0 <= t1, so we need another boolean argument
// to indicate backwards play.
const bool looped = options.playLooped;
if (backwards)
std::swap(t0, t1);
projectAudioManager.SetLooping( mode == PlayMode::loopedPlay );
projectAudioManager.SetCutting( mode == PlayMode::cutPreviewPlay );
bool success = false;
auto gAudioIO = AudioIO::Get();
if (gAudioIO->IsBusy())
return -1;
const bool cutpreview = mode == PlayMode::cutPreviewPlay;
if (cutpreview && t0==t1)
return -1; /* msmeyer: makes no sense */
SneedacityProject *p = &mProject;
auto &tracks = TrackList::Get( *p );
mLastPlayMode = mode;
bool hasaudio;
if (useMidi)
hasaudio = ! tracks.Any<PlayableTrack>().empty();
else
hasaudio = ! tracks.Any<WaveTrack>().empty();
double latestEnd = (playWhiteSpace)? t1 : tracks.GetEndTime();
if (!hasaudio)
return -1; // No need to continue without audio tracks
#if defined(EXPERIMENTAL_SEEK_BEHIND_CURSOR)
double init_seek = 0.0;
#endif
double loop_offset = 0.0;
if (t1 == t0) {
if (looped) {
const auto &selectedRegion = ViewInfo::Get( *p ).selectedRegion;
// play selection if there is one, otherwise
// set start of play region to project start,
// and loop the project from current play position.
if ((t0 > selectedRegion.t0()) && (t0 < selectedRegion.t1())) {
t0 = selectedRegion.t0();
t1 = selectedRegion.t1();
}
else {
// loop the entire project
// Bug2347, loop playback from cursor position instead of project start
loop_offset = t0 - tracks.GetStartTime();
t0 = tracks.GetStartTime();
t1 = tracks.GetEndTime();
}
} else {
// move t0 to valid range
if (t0 < 0) {
t0 = tracks.GetStartTime();
}
else if (t0 > tracks.GetEndTime()) {
t0 = tracks.GetEndTime();
}
#if defined(EXPERIMENTAL_SEEK_BEHIND_CURSOR)
else {
init_seek = t0; //AC: init_seek is where playback will 'start'
t0 = tracks.GetStartTime();
}
#endif
}
t1 = tracks.GetEndTime();
}
else {
// maybe t1 < t0, with backwards scrubbing for instance
if (backwards)
std::swap(t0, t1);
t0 = std::max(0.0, std::min(t0, latestEnd));
t1 = std::max(0.0, std::min(t1, latestEnd));
if (backwards)
std::swap(t0, t1);
}
int token = -1;
if (t1 != t0) {
if (cutpreview) {
const double tless = std::min(t0, t1);
const double tgreater = std::max(t0, t1);
double beforeLen, afterLen;
gPrefs->Read(wxT("/AudioIO/CutPreviewBeforeLen"), &beforeLen, 2.0);
gPrefs->Read(wxT("/AudioIO/CutPreviewAfterLen"), &afterLen, 1.0);
double tcp0 = tless-beforeLen;
double diff = tgreater - tless;
double tcp1 = (tgreater+afterLen) - diff;
SetupCutPreviewTracks(tcp0, tless, tgreater, tcp1);
if (backwards)
std::swap(tcp0, tcp1);
if (mCutPreviewTracks)
{
AudioIOStartStreamOptions myOptions = options;
myOptions.cutPreviewGapStart = t0;
myOptions.cutPreviewGapLen = t1 - t0;
token = gAudioIO->StartStream(
GetAllPlaybackTracks(*mCutPreviewTracks, false, useMidi),
tcp0, tcp1, myOptions);
}
else
// Cannot create cut preview tracks, clean up and exit
return -1;
}
else {
token = gAudioIO->StartStream(
GetAllPlaybackTracks( tracks, false, useMidi ),
t0, t1, options);
}
if (token != 0) {
success = true;
ProjectAudioIO::Get(*p).SetAudioIOToken(token);
if (loop_offset != 0.0) {
// Bug 2347
gAudioIO->SeekStream(loop_offset);
}
#if defined(EXPERIMENTAL_SEEK_BEHIND_CURSOR )
//AC: If init_seek was set, now's the time to make it happen.
gAudioIO->SeekStream(init_seek);
#endif
}
else {
// Bug1627 (part of it):
// infinite error spew when trying to start scrub:
// Problem was that the error dialog yields to events,
// causing recursion to this function in the scrub timer
// handler! Easy fix, just delay the user alert instead.
auto &window = GetProjectFrame( mProject );
window.CallAfter( [&]{
// Show error message if stream could not be opened
ShowExceptionDialog(&window, XO("Error"),
XO("Error opening sound device.\nTry changing the audio host, playback device and the project sample rate."),
wxT("Error_opening_sound_device"));
});
}
}
if (!success)
return -1;
return token;
}
void ProjectAudioManager::PlayCurrentRegion(bool looped /* = false */,
bool cutpreview /* = false */)
{
auto &projectAudioManager = *this;
bool canStop = projectAudioManager.CanStopAudioStream();
if ( !canStop )
return;
SneedacityProject *p = &mProject;
{
const auto &playRegion = ViewInfo::Get( *p ).playRegion;
auto options = DefaultPlayOptions( *p );
options.playLooped = looped;
if (cutpreview)
options.envelope = nullptr;
auto mode =
cutpreview ? PlayMode::cutPreviewPlay
: options.playLooped ? PlayMode::loopedPlay
: PlayMode::normalPlay;
PlayPlayRegion(SelectedRegion(playRegion.GetStart(), playRegion.GetEnd()),
options,
mode);
}
}
void ProjectAudioManager::Stop(bool stopStream /* = true*/)
{
SneedacityProject *project = &mProject;
auto &projectAudioManager = *this;
bool canStop = projectAudioManager.CanStopAudioStream();
if ( !canStop )
return;
if(project) {
// Let scrubbing code do some appearance change
auto &scrubber = Scrubber::Get( *project );
scrubber.StopScrubbing();
}
auto gAudioIO = AudioIO::Get();
auto cleanup = finally( [&]{
projectAudioManager.SetStopping( false );
} );
if (stopStream && gAudioIO->IsBusy()) {
// flag that we are stopping
projectAudioManager.SetStopping( true );
// Allow UI to update for that
while( wxTheApp->ProcessIdle() )
;
}
if(stopStream)
gAudioIO->StopStream();
projectAudioManager.SetLooping( false );
projectAudioManager.SetCutting( false );
#ifdef EXPERIMENTAL_AUTOMATED_INPUT_LEVEL_ADJUSTMENT
gAudioIO->AILADisable();
#endif
projectAudioManager.SetPaused( false );
//Make sure you tell gAudioIO to unpause
gAudioIO->SetPaused( false );
ClearCutPreviewTracks();
// So that we continue monitoring after playing or recording.
// also clean the MeterQueues
if( project ) {
auto &projectAudioIO = ProjectAudioIO::Get( *project );
auto meter = projectAudioIO.GetPlaybackMeter();
if( meter ) {
meter->Clear();
}
meter = projectAudioIO.GetCaptureMeter();
if( meter ) {
meter->Clear();
}
}
const auto toolbar = ToolManager::Get( *project ).GetToolBar(ScrubbingBarID);
if (toolbar)
toolbar->EnableDisableButtons();
}
void ProjectAudioManager::Pause()
{
auto &projectAudioManager = *this;
bool canStop = projectAudioManager.CanStopAudioStream();
if ( !canStop ) {
auto gAudioIO = AudioIO::Get();
gAudioIO->SetPaused(!gAudioIO->IsPaused());
}
else {
OnPause();
}
}
WaveTrackArray ProjectAudioManager::ChooseExistingRecordingTracks(
SneedacityProject &proj, bool selectedOnly, double targetRate)
{
auto p = &proj;
size_t recordingChannels = std::max(0, AudioIORecordChannels.Read());
bool strictRules = (recordingChannels <= 2);
// Iterate over all wave tracks, or over selected wave tracks only.
// If target rate was specified, ignore all tracks with other rates.
//
// In the usual cases of one or two recording channels, seek a first-fit
// unbroken sub-sequence for which the total number of channels matches the
// required number exactly. Never drop inputs or fill only some channels
// of a track.
//
// In case of more than two recording channels, choose tracks only among the
// selected. Simply take the earliest wave tracks, until the number of
// channels is enough. If there are fewer channels than inputs, but at least
// one channel, then some of the input channels will be dropped.
//
// Resulting tracks may be non-consecutive within the list of all tracks
// (there may be non-wave tracks between, or non-selected tracks when
// considering selected tracks only.)
if (!strictRules && !selectedOnly)
return {};
auto &trackList = TrackList::Get( *p );
std::vector<unsigned> channelCounts;
WaveTrackArray candidates;
const auto range = trackList.Leaders<WaveTrack>();
for ( auto candidate : selectedOnly ? range + &Track::IsSelected : range ) {
if (targetRate != RATE_NOT_SELECTED && candidate->GetRate() != targetRate)
continue;
// count channels in this track
const auto channels = TrackList::Channels( candidate );
unsigned nChannels = channels.size();
if (strictRules && nChannels > recordingChannels) {
// The recording would under-fill this track's channels
// Can't use any partial accumulated results
// either. Keep looking.
candidates.clear();
channelCounts.clear();
continue;
}
else {
// Might use this but may have to discard some of the accumulated
while(strictRules &&
nChannels + candidates.size() > recordingChannels) {
auto nOldChannels = channelCounts[0];
wxASSERT(nOldChannels > 0);
channelCounts.erase(channelCounts.begin());
candidates.erase(candidates.begin(),
candidates.begin() + nOldChannels);
}
channelCounts.push_back(nChannels);
for ( auto channel : channels ) {
candidates.push_back(channel->SharedPointer<WaveTrack>());
if(candidates.size() == recordingChannels)
// Done!
return candidates;
}
}
}
if (!strictRules && !candidates.empty())
// good enough
return candidates;
// If the loop didn't exit early, we could not find enough channels
return {};
}
/*! @excsafety{Strong} -- For state of current project's tracks */
void ProjectAudioManager::OnRecord(bool altAppearance)
{
bool bPreferNewTrack;
gPrefs->Read("/GUI/PreferNewTrackRecord", &bPreferNewTrack, false);
const bool appendRecord = (altAppearance == bPreferNewTrack);
// Code from CommandHandler start...
SneedacityProject *p = &mProject;
if (p) {
const auto &selectedRegion = ViewInfo::Get( *p ).selectedRegion;
double t0 = selectedRegion.t0();
double t1 = selectedRegion.t1();
// When no time selection, recording duration is 'unlimited'.
if (t1 == t0)
t1 = DBL_MAX;
auto options = DefaultPlayOptions(*p);
WaveTrackArray existingTracks;
// Checking the selected tracks: counting them and
// making sure they all have the same rate
const auto selectedTracks{ GetPropertiesOfSelected(*p) };
const int rateOfSelected{ selectedTracks.rateOfSelected };
const int numberOfSelected{ selectedTracks.numberOfSelected };
const bool allSameRate{ selectedTracks.allSameRate };
if (!allSameRate) {
SneedacityMessageBox(XO("The tracks selected "
"for recording must all have the same sampling rate"),
XO("Mismatched Sampling Rates"),
wxICON_ERROR | wxCENTRE);
return;
}
if (appendRecord) {
const auto trackRange = TrackList::Get( *p ).Any< const WaveTrack >();
// Try to find wave tracks to record into. (If any are selected,
// try to choose only from them; else if wave tracks exist, may record into any.)
existingTracks = ChooseExistingRecordingTracks(*p, true, rateOfSelected);
if (!existingTracks.empty()) {
t0 = std::max(t0,
(trackRange + &Track::IsSelected).max(&Track::GetEndTime));
}
else {
if (numberOfSelected > 0 && rateOfSelected != options.rate) {
SneedacityMessageBox(XO(
"Too few tracks are selected for recording at this sample rate.\n"
"(Sneedacity requires two channels at the same sample rate for\n"
"each stereo track)"),
XO("Too Few Compatible Tracks Selected"),
wxICON_ERROR | wxCENTRE);
return;
}
existingTracks = ChooseExistingRecordingTracks(*p, false, options.rate);
t0 = std::max( t0, trackRange.max( &Track::GetEndTime ) );
// If suitable tracks still not found, will record into NEW ones,
// but the choice of t0 does not depend on that.
}
// Whether we decided on NEW tracks or not:
if (t1 <= selectedRegion.t0() && selectedRegion.t1() > selectedRegion.t0()) {
t1 = selectedRegion.t1(); // record within the selection
}
else {
t1 = DBL_MAX; // record for a long, long time
}
}
TransportTracks transportTracks;
if (UseDuplex()) {
// Remove recording tracks from the list of tracks for duplex ("overdub")
// playback.
/* TODO: set up stereo tracks if that is how the user has set up
* their preferences, and choose sample format based on prefs */
transportTracks = GetAllPlaybackTracks(TrackList::Get( *p ), false, true);
for (const auto &wt : existingTracks) {
auto end = transportTracks.playbackTracks.end();
auto it = std::find(transportTracks.playbackTracks.begin(), end, wt);
if (it != end)
transportTracks.playbackTracks.erase(it);
}
}
transportTracks.captureTracks = existingTracks;
if (rateOfSelected != RATE_NOT_SELECTED)
options.rate = rateOfSelected;
DoRecord(*p, transportTracks, t0, t1, altAppearance, options);
}
}
bool ProjectAudioManager::UseDuplex()
{
bool duplex;
gPrefs->Read(wxT("/AudioIO/Duplex"), &duplex,
#ifdef EXPERIMENTAL_DA
false
#else
true
#endif
);
return duplex;
}
bool ProjectAudioManager::DoRecord(SneedacityProject &project,
const TransportTracks &tracks,
double t0, double t1,
bool altAppearance,
const AudioIOStartStreamOptions &options)
{
auto &projectAudioManager = *this;
CommandFlag flags = AlwaysEnabledFlag; // 0 means recalc flags.
// NB: The call may have the side effect of changing flags.
bool allowed = MenuManager::Get(project).TryToMakeActionAllowed(
flags,
AudioIONotBusyFlag() | CanStopAudioStreamFlag());
if (!allowed)
return false;
// ...end of code from CommandHandler.
auto gAudioIO = AudioIO::Get();
if (gAudioIO->IsBusy())
return false;
projectAudioManager.SetAppending( !altAppearance );
bool success = false;
auto transportTracks = tracks;
// Will replace any given capture tracks with temporaries
transportTracks.captureTracks.clear();
const auto p = &project;
bool appendRecord = !tracks.captureTracks.empty();
{
if (appendRecord) {
// Append recording:
// Pad selected/all wave tracks to make them all the same length
for (const auto &wt : tracks.captureTracks)
{
auto endTime = wt->GetEndTime();
// If the track was chosen for recording and playback both,
// remember the original in preroll tracks, before making the
// pending replacement.
bool prerollTrack = make_iterator_range(transportTracks.playbackTracks).contains(wt);
if (prerollTrack)
transportTracks.prerollTracks.push_back(wt);
// A function that copies all the non-sample data between
// wave tracks; in case the track recorded to changes scale
// type (for instance), during the recording.
auto updater = [](Track &d, const Track &s){
auto &dst = static_cast<WaveTrack&>(d);
auto &src = static_cast<const WaveTrack&>(s);
dst.Reinit(src);
};
// Get a copy of the track to be appended, to be pushed into
// undo history only later.
auto pending = std::static_pointer_cast<WaveTrack>(
TrackList::Get( *p ).RegisterPendingChangedTrack(
updater, wt.get() ) );
// End of current track is before or at recording start time.
// Less than or equal, not just less than, to ensure a clip boundary.
// when append recording.
if (endTime <= t0) {
// Pad the recording track with silence, up to the
// maximum time.
auto newTrack = pending->EmptyCopy();
newTrack->InsertSilence(0.0, t0 - endTime);
newTrack->Flush();
pending->Clear(endTime, t0);
pending->Paste(endTime, newTrack.get());
}
transportTracks.captureTracks.push_back(pending);
}
TrackList::Get( *p ).UpdatePendingTracks();
}
if( transportTracks.captureTracks.empty() )
{ // recording to NEW track(s).
bool recordingNameCustom, useTrackNumber, useDateStamp, useTimeStamp;
wxString defaultTrackName, defaultRecordingTrackName;
// Count the tracks.
auto &trackList = TrackList::Get( *p );
auto numTracks = trackList.Leaders< const WaveTrack >().size();
auto recordingChannels = std::max(1, AudioIORecordChannels.Read());
gPrefs->Read(wxT("/GUI/TrackNames/RecordingNameCustom"), &recordingNameCustom, false);
gPrefs->Read(wxT("/GUI/TrackNames/TrackNumber"), &useTrackNumber, false);
gPrefs->Read(wxT("/GUI/TrackNames/DateStamp"), &useDateStamp, false);
gPrefs->Read(wxT("/GUI/TrackNames/TimeStamp"), &useTimeStamp, false);
defaultTrackName = TracksPrefs::GetDefaultAudioTrackNamePreference();
gPrefs->Read(wxT("/GUI/TrackNames/RecodingTrackName"), &defaultRecordingTrackName, defaultTrackName);
wxString baseTrackName = recordingNameCustom? defaultRecordingTrackName : defaultTrackName;
Track *first {};
for (int c = 0; c < recordingChannels; c++) {
auto newTrack = WaveTrackFactory::Get( *p ).NewWaveTrack();
if (!first)
first = newTrack.get();
// Quantize bounds to the rate of the new track.
if (c == 0) {
if (t0 < DBL_MAX)
t0 = newTrack->LongSamplesToTime(newTrack->TimeToLongSamples(t0));
if (t1 < DBL_MAX)
t1 = newTrack->LongSamplesToTime(newTrack->TimeToLongSamples(t1));
}
newTrack->SetOffset(t0);
wxString nameSuffix = wxString(wxT(""));
if (useTrackNumber) {
nameSuffix += wxString::Format(wxT("%d"), 1 + (int) numTracks + c);
}
if (useDateStamp) {
if (!nameSuffix.empty()) {
nameSuffix += wxT("_");
}
nameSuffix += wxDateTime::Now().FormatISODate();
}
if (useTimeStamp) {
if (!nameSuffix.empty()) {
nameSuffix += wxT("_");
}
nameSuffix += wxDateTime::Now().FormatISOTime();
}
// ISO standard would be nice, but ":" is unsafe for file name.
nameSuffix.Replace(wxT(":"), wxT("-"));
if (baseTrackName.empty()) {
newTrack->SetName(nameSuffix);
}
else if (nameSuffix.empty()) {
newTrack->SetName(baseTrackName);
}
else {
newTrack->SetName(baseTrackName + wxT("_") + nameSuffix);
}
TrackList::Get( *p ).RegisterPendingNewTrack( newTrack );
if ((recordingChannels > 2) &&
!(ProjectSettings::Get(*p).GetTracksFitVerticallyZoomed())) {
TrackView::Get( *newTrack ).SetMinimized(true);
}
transportTracks.captureTracks.push_back(newTrack);
}
TrackList::Get( *p ).GroupChannels(*first, recordingChannels);
// Bug 1548. First of new tracks needs the focus.
TrackFocus::Get(*p).Set(first);
if (TrackList::Get(*p).back())
TrackList::Get(*p).back()->EnsureVisible();
}
//Automated Input Level Adjustment Initialization
#ifdef EXPERIMENTAL_AUTOMATED_INPUT_LEVEL_ADJUSTMENT
gAudioIO->AILAInitialize();
#endif
int token = gAudioIO->StartStream(transportTracks, t0, t1, options);
success = (token != 0);
if (success) {
ProjectAudioIO::Get( *p ).SetAudioIOToken(token);
}
else {
CancelRecording();
// Show error message if stream could not be opened
auto msg = XO("Error opening recording device.\nError code: %s")
.Format( gAudioIO->LastPaErrorString() );
ShowExceptionDialog(&GetProjectFrame( mProject ),
XO("Error"), msg, wxT("Error_opening_sound_device"));
}
}
return success;
}
void ProjectAudioManager::OnPause()
{
auto &projectAudioManager = *this;
bool canStop = projectAudioManager.CanStopAudioStream();
if ( !canStop ) {
return;
}
bool paused = !projectAudioManager.Paused();
projectAudioManager.SetPaused( paused );
auto gAudioIO = AudioIO::Get();
#ifdef EXPERIMENTAL_SCRUBBING_SUPPORT
auto project = &mProject;
auto &scrubber = Scrubber::Get( *project );
// Bug 1494 - Pausing a seek or scrub should just STOP as
// it is confusing to be in a paused scrub state.
bool bStopInstead = paused &&
gAudioIO->IsScrubbing() &&
!scrubber.IsSpeedPlaying() &&
!scrubber.IsKeyboardScrubbing();
if (bStopInstead) {
Stop();
return;
}
if (gAudioIO->IsScrubbing())
scrubber.Pause(paused);
else
#endif
{
gAudioIO->SetPaused(paused);
}
}
/*! @excsafety{Strong} -- For state of mCutPreviewTracks*/
void ProjectAudioManager::SetupCutPreviewTracks(double WXUNUSED(playStart), double cutStart,
double cutEnd, double WXUNUSED(playEnd))
{
ClearCutPreviewTracks();
SneedacityProject *p = &mProject;
{
auto trackRange = TrackList::Get( *p ).Selected< const PlayableTrack >();
if( !trackRange.empty() ) {
auto cutPreviewTracks = TrackList::Create( nullptr );
for (const auto track1 : trackRange) {
// Duplicate and change tracks
// Clear has a very small chance of throwing
auto newTrack = track1->Duplicate();
newTrack->Clear(cutStart, cutEnd);
cutPreviewTracks->Add( newTrack );
}
// use No-throw-guarantee:
mCutPreviewTracks = cutPreviewTracks;
}
}
}
void ProjectAudioManager::ClearCutPreviewTracks()
{
if (mCutPreviewTracks)
mCutPreviewTracks->Clear();
mCutPreviewTracks.reset();
}
void ProjectAudioManager::CancelRecording()
{
const auto project = &mProject;
TrackList::Get( *project ).ClearPendingTracks();
}
void ProjectAudioManager::OnAudioIORate(int rate)
{
auto &project = mProject;
mDisplayedRate = rate;
auto display = FormatRate( rate );
ProjectStatus::Get( project ).Set( display, rateStatusBarField );
}
void ProjectAudioManager::OnAudioIOStartRecording()
{
// Auto-save was done here before, but it is unnecessary, provided there
// are sufficient autosaves when pushing or modifying undo states.
}
// This is called after recording has stopped and all tracks have flushed.
void ProjectAudioManager::OnAudioIOStopRecording()
{
auto &project = mProject;
auto &projectAudioIO = ProjectAudioIO::Get( project );
auto &projectFileIO = ProjectFileIO::Get( project );
auto &window = GetProjectFrame( project );
// Only push state if we were capturing and not monitoring
if (projectAudioIO.GetAudioIOToken() > 0)
{
auto &history = ProjectHistory::Get( project );
if (IsTimerRecordCancelled()) {
// discard recording
history.RollbackState();
// Reset timer record
ResetTimerRecordCancelled();
}
else {
// Add to history
// We want this to have No-fail-guarantee if we get here from exception
// handling of recording, and that means we rely on the last autosave
// successfully committed to the database, not risking a failure
history.PushState(XO("Recorded Audio"), XO("Record"),
UndoPush::NOAUTOSAVE);
// Now, we may add a label track to give information about
// dropouts. We allow failure of this.
auto &tracks = TrackList::Get( project );
auto gAudioIO = AudioIO::Get();
auto &intervals = gAudioIO->LostCaptureIntervals();
if (intervals.size()) {
// Make a track with labels for recording errors
auto uTrack = std::make_shared<LabelTrack>();
auto pTrack = uTrack.get();
tracks.Add( uTrack );
/* i18n-hint: A name given to a track, appearing as its menu button.
The translation should be short or else it will not display well.
At most, about 11 Latin characters.
Dropout is a loss of a short sequence of audio sample data from the
recording */
pTrack->SetName(_("Dropouts"));
long counter = 1;
for (auto &interval : intervals)
pTrack->AddLabel(
SelectedRegion{ interval.first,
interval.first + interval.second },
wxString::Format(wxT("%ld"), counter++));
history.ModifyState( true ); // this might fail and throw
// CallAfter so that we avoid any problems of yielding
// to the event loop while still inside the timer callback,
// entering StopStream() recursively
wxTheApp->CallAfter( [&] {
ShowWarningDialog(&window, wxT("DropoutDetected"), XO("\
Recorded audio was lost at the labeled locations. Possible causes:\n\
\n\
Other applications are competing with Sneedacity for processor time\n\
\n\
You are saving directly to a slow external storage device\n\
"
),
false,
XXO("Turn off dropout detection"));
});
}
}
}
}
void ProjectAudioManager::OnAudioIONewBlocks(const WaveTrackArray *tracks)
{
auto &project = mProject;
auto &projectFileIO = ProjectFileIO::Get( project );
projectFileIO.AutoSave(true);
}
void ProjectAudioManager::OnCommitRecording()
{
const auto project = &mProject;
TrackList::Get( *project ).ApplyPendingTracks();
}
void ProjectAudioManager::OnSoundActivationThreshold()
{
auto &project = mProject;
auto gAudioIO = AudioIO::Get();
if ( gAudioIO && &project == gAudioIO->GetOwningProject() ) {
wxTheApp->CallAfter( [this]{ Pause(); } );
}
}
void ProjectAudioManager::OnCheckpointFailure(wxCommandEvent &evt)
{
evt.Skip();
Stop();
}
bool ProjectAudioManager::Playing() const
{
auto gAudioIO = AudioIO::Get();
return
gAudioIO->IsBusy() &&
CanStopAudioStream() &&
// ... and not merely monitoring
!gAudioIO->IsMonitoring() &&
// ... and not punch-and-roll recording
gAudioIO->GetNumCaptureChannels() == 0;
}
bool ProjectAudioManager::Recording() const
{
auto gAudioIO = AudioIO::Get();
return
gAudioIO->IsBusy() &&
CanStopAudioStream() &&
gAudioIO->GetNumCaptureChannels() > 0;
}
bool ProjectAudioManager::CanStopAudioStream() const
{
auto gAudioIO = AudioIO::Get();
return (!gAudioIO->IsStreamActive() ||
gAudioIO->IsMonitoring() ||
gAudioIO->GetOwningProject() == &mProject );
}
const ReservedCommandFlag&
CanStopAudioStreamFlag(){ static ReservedCommandFlag flag{
[](const SneedacityProject &project){
auto &projectAudioManager = ProjectAudioManager::Get( project );
bool canStop = projectAudioManager.CanStopAudioStream();
return canStop;
}
}; return flag; }