-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
enginebuffer.cpp
1455 lines (1255 loc) · 51.8 KB
/
enginebuffer.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
#include "engine/enginebuffer.h"
#include <QtDebug>
#include "control/controlindicator.h"
#include "control/controllinpotmeter.h"
#include "control/controlpotmeter.h"
#include "control/controlproxy.h"
#include "control/controlpushbutton.h"
#include "engine/bufferscalers/enginebufferscalelinear.h"
#include "engine/bufferscalers/enginebufferscalerubberband.h"
#include "engine/bufferscalers/enginebufferscalest.h"
#include "engine/cachingreader/cachingreader.h"
#include "engine/channels/enginechannel.h"
#include "engine/controls/bpmcontrol.h"
#include "engine/controls/clockcontrol.h"
#include "engine/controls/cuecontrol.h"
#include "engine/controls/enginecontrol.h"
#include "engine/controls/keycontrol.h"
#include "engine/controls/loopingcontrol.h"
#include "engine/controls/quantizecontrol.h"
#include "engine/controls/ratecontrol.h"
#include "engine/enginemaster.h"
#include "engine/engineworkerscheduler.h"
#include "engine/readaheadmanager.h"
#include "engine/sync/enginesync.h"
#include "engine/sync/synccontrol.h"
#include "moc_enginebuffer.cpp"
#include "preferences/usersettings.h"
#include "track/beatfactory.h"
#include "track/keyutils.h"
#include "track/track.h"
#include "util/assert.h"
#include "util/compatibility.h"
#include "util/defs.h"
#include "util/logger.h"
#include "util/sample.h"
#include "util/timer.h"
#include "waveform/visualplayposition.h"
#include "waveform/waveformwidgetfactory.h"
#ifdef __VINYLCONTROL__
#include "engine/controls/vinylcontrolcontrol.h"
#endif
namespace {
const mixxx::Logger kLogger("EngineBuffer");
constexpr double kLinearScalerElipsis =
1.00058; // 2^(0.01/12): changes < 1 cent allows a linear scaler
constexpr SINT kSamplesPerFrame = 2; // Engine buffer uses Stereo frames only
// Rate at which the playpos slider is updated
constexpr int kPlaypositionUpdateRate = 15; // updates per second
} // anonymous namespace
EngineBuffer::EngineBuffer(const QString& group,
UserSettingsPointer pConfig,
EngineChannel* pChannel,
EngineMaster* pMixingEngine)
: m_group(group),
m_pConfig(pConfig),
m_pLoopingControl(nullptr),
m_pSyncControl(nullptr),
m_pVinylControlControl(nullptr),
m_pRateControl(nullptr),
m_pBpmControl(nullptr),
m_pKeyControl(nullptr),
m_pReadAheadManager(nullptr),
m_pReader(nullptr),
m_filepos_play(kInitialSamplePosition),
m_speed_old(0),
m_tempo_ratio_old(1.),
m_scratching_old(false),
m_reverse_old(false),
m_pitch_old(0),
m_baserate_old(0),
m_rate_old(0.),
m_trackSamplesOld(0),
m_trackSampleRateOld(0),
m_dSlipPosition(0.),
m_dSlipRate(1.0),
m_bSlipEnabledProcessing(false),
m_pRepeat(nullptr),
m_startButton(nullptr),
m_endButton(nullptr),
m_bScalerOverride(false),
m_iSeekPhaseQueued(0),
m_iEnableSyncQueued(SYNC_REQUEST_NONE),
m_iSyncModeQueued(SYNC_INVALID),
m_bPlayAfterLoading(false),
m_iSampleRate(0),
m_pCrossfadeBuffer(SampleUtil::alloc(MAX_BUFFER_LEN)),
m_bCrossfadeReady(false),
m_iLastBufferSize(0) {
m_queuedSeek.setValue(kNoQueuedSeek);
// zero out crossfade buffer
SampleUtil::clear(m_pCrossfadeBuffer, MAX_BUFFER_LEN);
m_pReader = new CachingReader(group, pConfig);
connect(m_pReader, &CachingReader::trackLoading,
this, &EngineBuffer::slotTrackLoading,
Qt::DirectConnection);
connect(m_pReader, &CachingReader::trackLoaded,
this, &EngineBuffer::slotTrackLoaded,
Qt::DirectConnection);
connect(m_pReader, &CachingReader::trackLoadFailed,
this, &EngineBuffer::slotTrackLoadFailed,
Qt::DirectConnection);
// Play button
m_playButton = new ControlPushButton(ConfigKey(m_group, "play"));
m_playButton->setButtonMode(ControlPushButton::TOGGLE);
m_playButton->connectValueChangeRequest(
this, &EngineBuffer::slotControlPlayRequest,
Qt::DirectConnection);
//Play from Start Button (for sampler)
m_playStartButton = new ControlPushButton(ConfigKey(m_group, "start_play"));
connect(m_playStartButton, &ControlObject::valueChanged,
this, &EngineBuffer::slotControlPlayFromStart,
Qt::DirectConnection);
// Jump to start and stop button
m_stopStartButton = new ControlPushButton(ConfigKey(m_group, "start_stop"));
connect(m_stopStartButton, &ControlObject::valueChanged,
this, &EngineBuffer::slotControlJumpToStartAndStop,
Qt::DirectConnection);
//Stop playback (for sampler)
m_stopButton = new ControlPushButton(ConfigKey(m_group, "stop"));
connect(m_stopButton, &ControlObject::valueChanged,
this, &EngineBuffer::slotControlStop,
Qt::DirectConnection);
// Start button
m_startButton = new ControlPushButton(ConfigKey(m_group, "start"));
m_startButton->setButtonMode(ControlPushButton::TRIGGER);
connect(m_startButton, &ControlObject::valueChanged,
this, &EngineBuffer::slotControlStart,
Qt::DirectConnection);
// End button
m_endButton = new ControlPushButton(ConfigKey(m_group, "end"));
connect(m_endButton, &ControlObject::valueChanged,
this, &EngineBuffer::slotControlEnd,
Qt::DirectConnection);
m_pSlipButton = new ControlPushButton(ConfigKey(m_group, "slip_enabled"));
m_pSlipButton->setButtonMode(ControlPushButton::TOGGLE);
m_playposSlider = new ControlLinPotmeter(
ConfigKey(m_group, "playposition"), 0.0, 1.0, 0, 0, true);
connect(m_playposSlider, &ControlObject::valueChanged,
this, &EngineBuffer::slotControlSeek,
Qt::DirectConnection);
// Control used to communicate ratio playpos to GUI thread
m_visualPlayPos = VisualPlayPosition::getVisualPlayPosition(m_group);
m_pRepeat = new ControlPushButton(ConfigKey(m_group, "repeat"));
m_pRepeat->setButtonMode(ControlPushButton::TOGGLE);
m_pSampleRate = new ControlProxy("[Master]", "samplerate", this);
m_pKeylockEngine = new ControlProxy("[Master]", "keylock_engine", this);
m_pKeylockEngine->connectValueChanged(this, &EngineBuffer::slotKeylockEngineChanged,
Qt::DirectConnection);
m_pTrackSamples = new ControlObject(ConfigKey(m_group, "track_samples"));
m_pTrackSampleRate = new ControlObject(ConfigKey(m_group, "track_samplerate"));
m_pKeylock = new ControlPushButton(ConfigKey(m_group, "keylock"), true);
m_pKeylock->setButtonMode(ControlPushButton::TOGGLE);
m_pEject = new ControlPushButton(ConfigKey(m_group, "eject"));
connect(m_pEject, &ControlObject::valueChanged,
this, &EngineBuffer::slotEjectTrack,
Qt::DirectConnection);
m_pTrackLoaded = new ControlObject(ConfigKey(m_group, "track_loaded"), false);
m_pTrackLoaded->setReadOnly();
// Quantization Controller for enabling and disabling the
// quantization (alignment) of loop in/out positions and (hot)cues with
// beats.
QuantizeControl* quantize_control = new QuantizeControl(group, pConfig);
addControl(quantize_control);
m_pQuantize = ControlObject::getControl(ConfigKey(group, "quantize"));
// Create the Loop Controller
m_pLoopingControl = new LoopingControl(group, pConfig);
addControl(m_pLoopingControl);
m_pEngineSync = pMixingEngine->getEngineSync();
m_pSyncControl = new SyncControl(group, pConfig, pChannel, m_pEngineSync);
#ifdef __VINYLCONTROL__
m_pVinylControlControl = new VinylControlControl(group, pConfig);
addControl(m_pVinylControlControl);
#endif
// Create the Rate Controller
m_pRateControl = new RateControl(group, pConfig);
// Add the Rate Controller
addControl(m_pRateControl);
// Looping Control needs Rate Control for Reverse Button
m_pLoopingControl->setRateControl(m_pRateControl);
// Create the BPM Controller
m_pBpmControl = new BpmControl(group, pConfig);
addControl(m_pBpmControl);
// TODO(rryan) remove this dependence?
m_pRateControl->setBpmControl(m_pBpmControl);
m_pSyncControl->setEngineControls(m_pRateControl, m_pBpmControl);
pMixingEngine->getEngineSync()->addSyncableDeck(m_pSyncControl);
addControl(m_pSyncControl);
m_fwdButton = ControlObject::getControl(ConfigKey(group, "fwd"));
m_backButton = ControlObject::getControl(ConfigKey(group, "back"));
m_pKeyControl = new KeyControl(group, pConfig);
addControl(m_pKeyControl);
// Create the clock controller
m_pClockControl = new ClockControl(group, pConfig);
addControl(m_pClockControl);
// Create the cue controller
m_pCueControl = new CueControl(group, pConfig);
addControl(m_pCueControl);
m_pReadAheadManager = new ReadAheadManager(m_pReader,
m_pLoopingControl);
m_pReadAheadManager->addRateControl(m_pRateControl);
// Construct scaling objects
m_pScaleLinear = new EngineBufferScaleLinear(m_pReadAheadManager);
m_pScaleST = new EngineBufferScaleST(m_pReadAheadManager);
m_pScaleRB = new EngineBufferScaleRubberBand(m_pReadAheadManager);
if (m_pKeylockEngine->get() == SOUNDTOUCH) {
m_pScaleKeylock = m_pScaleST;
} else {
m_pScaleKeylock = m_pScaleRB;
}
m_pScaleVinyl = m_pScaleLinear;
m_pScale = m_pScaleVinyl;
m_pScale->clear();
m_bScalerChanged = true;
m_pPassthroughEnabled = new ControlProxy(group, "passthrough", this);
m_pPassthroughEnabled->connectValueChanged(this, &EngineBuffer::slotPassthroughChanged,
Qt::DirectConnection);
#ifdef __SCALER_DEBUG__
df.setFileName("mixxx-debug.csv");
df.open(QIODevice::WriteOnly | QIODevice::Text);
writer.setDevice(&df);
#endif
// Now that all EngineControls have been created call setEngineMaster.
// TODO(XXX): Get rid of EngineControl::setEngineMaster and
// EngineControl::setEngineBuffer entirely and pass them through the
// constructor.
setEngineMaster(pMixingEngine);
}
EngineBuffer::~EngineBuffer() {
#ifdef __SCALER_DEBUG__
//close the writer
df.close();
#endif
delete m_pReadAheadManager;
delete m_pReader;
delete m_playButton;
delete m_playStartButton;
delete m_stopStartButton;
delete m_startButton;
delete m_endButton;
delete m_stopButton;
delete m_playposSlider;
delete m_pSlipButton;
delete m_pRepeat;
delete m_pSampleRate;
delete m_pTrackLoaded;
delete m_pTrackSamples;
delete m_pTrackSampleRate;
delete m_pScaleLinear;
delete m_pScaleST;
delete m_pScaleRB;
delete m_pKeylock;
delete m_pEject;
SampleUtil::free(m_pCrossfadeBuffer);
qDeleteAll(m_engineControls);
}
double EngineBuffer::fractionalPlayposFromAbsolute(double absolutePlaypos) {
double fFractionalPlaypos = 0.0;
if (m_trackSamplesOld != 0) {
fFractionalPlaypos = math_min<double>(absolutePlaypos, m_trackSamplesOld);
fFractionalPlaypos /= m_trackSamplesOld;
}
return fFractionalPlaypos;
}
void EngineBuffer::enableIndependentPitchTempoScaling(bool bEnable,
const int iBufferSize) {
// MUST ACQUIRE THE PAUSE MUTEX BEFORE CALLING THIS METHOD
// When no time-stretching or pitch-shifting is needed we use our own linear
// interpolation code (EngineBufferScaleLinear). It is faster and sounds
// much better for scratching.
// m_pScaleKeylock and m_pScaleVinyl could change out from under us,
// so cache it.
EngineBufferScale* keylock_scale = m_pScaleKeylock;
EngineBufferScale* vinyl_scale = m_pScaleVinyl;
if (bEnable && m_pScale != keylock_scale) {
if (m_speed_old != 0.0) {
// Crossfade if we are not paused.
// If we start from zero a ramping gain is
// applied later
readToCrossfadeBuffer(iBufferSize);
}
m_pScale = keylock_scale;
m_pScale->clear();
m_bScalerChanged = true;
} else if (!bEnable && m_pScale != vinyl_scale) {
if (m_speed_old != 0.0) {
// Crossfade if we are not paused
// (for slow speeds below 0.1 the vinyl_scale is used)
readToCrossfadeBuffer(iBufferSize);
}
m_pScale = vinyl_scale;
m_pScale->clear();
m_bScalerChanged = true;
}
}
double EngineBuffer::getBpm()
{
return m_pBpmControl->getBpm();
}
double EngineBuffer::getLocalBpm() {
return m_pBpmControl->getLocalBpm();
}
void EngineBuffer::setEngineMaster(EngineMaster* pEngineMaster) {
for (const auto& pControl: qAsConst(m_engineControls)) {
pControl->setEngineMaster(pEngineMaster);
}
}
void EngineBuffer::queueNewPlaypos(double newpos, enum SeekRequest seekType) {
// All seeks need to be done in the Engine thread so queue it up.
// Write the position before the seek type, to reduce a possible race
// condition effect
VERIFY_OR_DEBUG_ASSERT(seekType != SEEK_PHASE) {
// SEEK_PHASE with a position is not supported
// use SEEK_STANDARD for that
seekType = SEEK_STANDARD;
}
m_queuedSeek.setValue({newpos, seekType});
}
void EngineBuffer::requestSyncPhase() {
// Don't overwrite m_iSeekQueued
m_iSeekPhaseQueued = 1;
}
void EngineBuffer::requestEnableSync(bool enabled) {
// If we're not playing, the queued event won't get processed so do it now.
if (m_playButton->get() == 0.0) {
m_pEngineSync->requestEnableSync(m_pSyncControl, enabled);
return;
}
SyncRequestQueued enable_request =
static_cast<SyncRequestQueued>(atomicLoadRelaxed(m_iEnableSyncQueued));
if (enabled) {
m_iEnableSyncQueued = SYNC_REQUEST_ENABLE;
} else {
// If sync is enabled and disabled very quickly, it's is a one-shot
// sync event and needs to be handled specially. Otherwise the sync
// state will get stuck on or won't go on at all.
if (enable_request == SYNC_REQUEST_ENABLE) {
m_iEnableSyncQueued = SYNC_REQUEST_ENABLEDISABLE;
} else {
// Note that there is no DISABLEENABLE, because that's an irrelevant
// queuing. Moreover, ENABLEDISABLEENABLE is also redundant, so
// we don't have to handle any special cases.
m_iEnableSyncQueued = SYNC_REQUEST_DISABLE;
}
}
}
void EngineBuffer::requestSyncMode(SyncMode mode) {
// If we're not playing, the queued event won't get processed so do it now.
if (kLogger.traceEnabled()) {
kLogger.trace() << getGroup() << "EngineBuffer::requestSyncMode";
}
if (m_playButton->get() == 0.0) {
m_pEngineSync->requestSyncMode(m_pSyncControl, mode);
} else {
m_iSyncModeQueued = mode;
}
}
void EngineBuffer::requestClonePosition(EngineChannel* pChannel) {
atomicStoreRelaxed(m_pChannelToCloneFrom, pChannel);
}
void EngineBuffer::readToCrossfadeBuffer(const int iBufferSize) {
if (!m_bCrossfadeReady) {
// Read buffer, as if there where no parameter change
// (Must be called only once per callback)
m_pScale->scaleBuffer(m_pCrossfadeBuffer, iBufferSize);
// Restore the original position that was lost due to scaleBuffer() above
m_pReadAheadManager->notifySeek(m_filepos_play);
m_bCrossfadeReady = true;
}
}
void EngineBuffer::seekCloneBuffer(EngineBuffer* pOtherBuffer) {
doSeekPlayPos(pOtherBuffer->getExactPlayPos(), SEEK_EXACT);
}
// WARNING: This method is not thread safe and must not be called from outside
// the engine callback!
void EngineBuffer::setNewPlaypos(double newpos) {
if (kLogger.traceEnabled()) {
kLogger.trace() << m_group << "EngineBuffer::setNewPlaypos" << newpos;
}
m_filepos_play = newpos;
if (m_rate_old != 0.0) {
// Before seeking, read extra buffer for crossfading
// this also sets m_pReadAheadManager to newpos
readToCrossfadeBuffer(m_iLastBufferSize);
} else {
m_pReadAheadManager->notifySeek(m_filepos_play);
}
m_pScale->clear();
// Ensures that the playpos slider gets updated in next process call
m_iSamplesSinceLastIndicatorUpdate = 1000000;
// Must hold the engineLock while using m_engineControls
for (const auto& pControl: qAsConst(m_engineControls)) {
pControl->notifySeek(m_filepos_play);
}
verifyPlay(); // verify or update play button and indicator
}
QString EngineBuffer::getGroup() {
return m_group;
}
double EngineBuffer::getSpeed() {
return m_speed_old;
}
bool EngineBuffer::getScratching() {
return m_scratching_old;
}
// WARNING: Always called from the EngineWorker thread pool
void EngineBuffer::slotTrackLoading() {
// Pause EngineBuffer from processing frames
m_pause.lock();
// Setting m_iTrackLoading inside a m_pause.lock ensures that
// track buffer is not processed when starting to load a new one
m_iTrackLoading = 1;
m_pause.unlock();
// Set play here, to signal the user that the play command is adopted
m_playButton->set((double)m_bPlayAfterLoading);
m_pTrackSamples->set(0); // Stop renderer
}
void EngineBuffer::loadFakeTrack(TrackPointer pTrack, bool bPlay) {
if (bPlay) {
m_playButton->set((double)bPlay);
}
slotTrackLoaded(pTrack, pTrack->getSampleRate(),
pTrack->getSampleRate() * pTrack->getDurationInt());
}
// WARNING: Always called from the EngineWorker thread pool
void EngineBuffer::slotTrackLoaded(TrackPointer pTrack,
int iTrackSampleRate,
int iTrackNumSamples) {
if (kLogger.traceEnabled()) {
kLogger.trace() << getGroup() << "EngineBuffer::slotTrackLoaded";
}
TrackPointer pOldTrack = m_pCurrentTrack;
m_pause.lock();
m_visualPlayPos->setInvalid();
m_filepos_play = kInitialSamplePosition; // for execute seeks to 0.0
m_pCurrentTrack = pTrack;
m_pTrackSamples->set(iTrackNumSamples);
m_pTrackSampleRate->set(iTrackSampleRate);
// Reset slip mode
m_pSlipButton->set(0);
m_bSlipEnabledProcessing = false;
m_dSlipPosition = 0.;
m_dSlipRate = 0;
m_pTrackLoaded->forceSet(1);
// Reset the pitch value for the new track.
m_pause.unlock();
notifyTrackLoaded(pTrack, pOldTrack);
// Start buffer processing after all EngineContols are up to date
// with the current track e.g track is seeked to Cue
m_iTrackLoading = 0;
}
// WARNING: Always called from the EngineWorker thread pool
void EngineBuffer::slotTrackLoadFailed(TrackPointer pTrack,
const QString& reason) {
m_iTrackLoading = 0;
// Loading of a new track failed.
// eject the currently loaded track (the old Track) as well
ejectTrack();
emit trackLoadFailed(pTrack, reason);
}
TrackPointer EngineBuffer::getLoadedTrack() const {
return m_pCurrentTrack;
}
bool EngineBuffer::isReverse() {
return m_reverse_old;
}
void EngineBuffer::ejectTrack() {
// clear track values in any case, this may fix Bug #1450424
if (kLogger.traceEnabled()) {
kLogger.trace() << "EngineBuffer::ejectTrack()";
}
m_pause.lock();
m_iTrackLoading = 0;
m_pTrackLoaded->forceSet(0);
m_pTrackSamples->set(0);
m_pTrackSampleRate->set(0);
m_visualPlayPos->set(0.0, 0.0, 0.0, 0.0, 0.0);
TrackPointer pTrack = m_pCurrentTrack;
m_pCurrentTrack.reset();
m_playButton->set(0.0);
m_playposSlider->set(0);
m_pCueControl->resetIndicators();
doSeekPlayPos(0.0, SEEK_EXACT);
m_pause.unlock();
// Close open file handles by unloading the current track
m_pReader->newTrack(TrackPointer());
if (pTrack) {
notifyTrackLoaded(TrackPointer(), pTrack);
}
}
void EngineBuffer::slotPassthroughChanged(double enabled) {
if (enabled != 0) {
// If passthrough was enabled, stop playing the current track.
slotControlStop(1.0);
// Disable CUE and Play indicators
m_pCueControl->resetIndicators();
} else {
// Update CUE and Play indicators. Note: m_pCueControl->updateIndicators()
// is not sufficient.
updateIndicatorsAndModifyPlay(false, false);
}
}
// WARNING: This method runs in both the GUI thread and the Engine Thread
void EngineBuffer::slotControlSeek(double fractionalPos) {
doSeekFractional(fractionalPos, SEEK_STANDARD);
}
// WARNING: This method runs from SyncWorker and Engine Worker
void EngineBuffer::slotControlSeekAbs(double playPosition) {
doSeekPlayPos(playPosition, SEEK_STANDARD);
}
// WARNING: This method runs from SyncWorker and Engine Worker
void EngineBuffer::slotControlSeekExact(double playPosition) {
doSeekPlayPos(playPosition, SEEK_EXACT);
}
void EngineBuffer::doSeekFractional(double fractionalPos, enum SeekRequest seekType) {
// Prevent NaN's from sneaking into the engine.
VERIFY_OR_DEBUG_ASSERT(!util_isnan(fractionalPos)) {
return;
}
double newSamplePosition = fractionalPos * m_pTrackSamples->get();
doSeekPlayPos(newSamplePosition, seekType);
}
void EngineBuffer::doSeekPlayPos(double new_playpos, enum SeekRequest seekType) {
#ifdef __VINYLCONTROL__
// Notify the vinyl control that a seek has taken place in case it is in
// absolute mode and needs be switched to relative.
if (m_pVinylControlControl) {
m_pVinylControlControl->notifySeekQueued();
}
#endif
queueNewPlaypos(new_playpos, seekType);
}
bool EngineBuffer::updateIndicatorsAndModifyPlay(bool newPlay, bool oldPlay) {
// If no track is currently loaded, turn play off. If a track is loading
// allow the set since it might apply to a track we are loading due to the
// asynchrony.
bool playPossible = true;
const QueuedSeek queuedSeek = m_queuedSeek.getValue();
if ((!m_pCurrentTrack && atomicLoadRelaxed(m_iTrackLoading) == 0) ||
(m_pCurrentTrack && atomicLoadRelaxed(m_iTrackLoading) == 0 &&
m_filepos_play >= m_pTrackSamples->get() &&
queuedSeek.seekType == SEEK_NONE) ||
m_pPassthroughEnabled->toBool()) {
// play not possible
playPossible = false;
}
return m_pCueControl->updateIndicatorsAndModifyPlay(newPlay, oldPlay, playPossible);
}
void EngineBuffer::verifyPlay() {
bool play = m_playButton->toBool();
bool verifiedPlay = updateIndicatorsAndModifyPlay(play, play);
if (play != verifiedPlay) {
m_playButton->setAndConfirm(verifiedPlay ? 1.0 : 0.0);
}
}
void EngineBuffer::slotControlPlayRequest(double v) {
bool oldPlay = m_playButton->toBool();
bool verifiedPlay = updateIndicatorsAndModifyPlay(v > 0.0, oldPlay);
if (!oldPlay && verifiedPlay) {
if (m_pQuantize->toBool()
#ifdef __VINYLCONTROL__
&& m_pVinylControlControl && !m_pVinylControlControl->isEnabled()
#endif
) {
requestSyncPhase();
}
}
// set and confirm must be called here in any case to update the widget toggle state
m_playButton->setAndConfirm(verifiedPlay ? 1.0 : 0.0);
}
void EngineBuffer::slotControlStart(double v)
{
if (v > 0.0) {
doSeekFractional(0., SEEK_EXACT);
}
}
void EngineBuffer::slotControlEnd(double v)
{
if (v > 0.0) {
doSeekFractional(1., SEEK_EXACT);
}
}
void EngineBuffer::slotControlPlayFromStart(double v)
{
if (v > 0.0) {
doSeekFractional(0., SEEK_EXACT);
m_playButton->set(1);
}
}
void EngineBuffer::slotControlJumpToStartAndStop(double v)
{
if (v > 0.0) {
doSeekFractional(0., SEEK_EXACT);
m_playButton->set(0);
}
}
void EngineBuffer::slotControlStop(double v)
{
if (v > 0.0) {
m_playButton->set(0);
}
}
void EngineBuffer::slotKeylockEngineChanged(double dIndex) {
if (m_bScalerOverride) {
return;
}
// static_cast<KeylockEngine>(dIndex); direct cast produces a "not used" warning with gcc
int iEngine = static_cast<int>(dIndex);
KeylockEngine engine = static_cast<KeylockEngine>(iEngine);
if (engine == SOUNDTOUCH) {
m_pScaleKeylock = m_pScaleST;
} else {
m_pScaleKeylock = m_pScaleRB;
}
}
void EngineBuffer::processTrackLocked(
CSAMPLE* pOutput, const int iBufferSize, int sample_rate) {
ScopedTimer t("EngineBuffer::process_pauselock");
m_trackSampleRateOld = m_pTrackSampleRate->get();
m_trackSamplesOld = m_pTrackSamples->get();
double baserate = 0.0;
if (sample_rate > 0) {
baserate = m_trackSampleRateOld / sample_rate;
}
// Sync requests can affect rate, so process those first.
processSyncRequests();
// Note: play is also active during cue preview
bool paused = !m_playButton->toBool();
KeyControl::PitchTempoRatio pitchTempoRatio = m_pKeyControl->getPitchTempoRatio();
// The pitch adjustment in Ratio (1.0 being normal
// pitch. 2.0 is a full octave shift up).
double pitchRatio = pitchTempoRatio.pitchRatio;
double tempoRatio = pitchTempoRatio.tempoRatio;
const bool keylock_enabled = pitchTempoRatio.keylock;
bool is_scratching = false;
bool is_reverse = false;
// Update the slipped position and seek if it was disabled.
processSlip(iBufferSize);
// Note: This may effects the m_filepos_play, play, scaler and crossfade buffer
processSeek(paused);
// speed is the ratio between track-time and real-time
// (1.0 being normal rate. 2.0 plays at 2x speed -- 2 track seconds
// pass for every 1 real second). Depending on whether
// keylock is enabled, this is applied to either the rate or the tempo.
double speed = m_pRateControl->calculateSpeed(
baserate,
tempoRatio,
paused,
iBufferSize,
&is_scratching,
&is_reverse);
bool useIndependentPitchAndTempoScaling = false;
// TODO(owen): Maybe change this so that rubberband doesn't disable
// keylock on scratch. (just check m_pScaleKeylock == m_pScaleST)
if (is_scratching || fabs(speed) > 1.9) {
// Scratching and high speeds with always disables keylock
// because Soundtouch sounds terrible in these conditions. Rubberband
// sounds better, but still has some problems (it may reallocate in
// a party-crashing manner at extremely slow speeds).
// High seek speeds also disables keylock. Our pitch slider could go
// to 90%, so that's the cutoff point.
// Force pitchRatio to the linear pitch set by speed
pitchRatio = speed;
// This is for the natural speed pitch found on turn tables
} else if (fabs(speed) < 0.1) {
// We have pre-allocated big buffers in Rubberband and Soundtouch for
// a minimum speed of 0.1. Slower speeds will re-allocate much bigger
// buffers which may cause underruns.
// Disable keylock under these conditions.
// Force pitchRatio to the linear pitch set by speed
pitchRatio = speed;
} else if (keylock_enabled) {
// always use IndependentPitchAndTempoScaling
// to avoid clicks when crossing the linear pitch
// in this case it is most likely that the user
// will have an non linear pitch
// Note: We have undesired noise when cossfading between scalers
useIndependentPitchAndTempoScaling = true;
} else {
// We might have have temporary speed change, so adjust pitch if not locked
// Note: This will not update key and tempo widgets
if (tempoRatio != 0) {
pitchRatio *= (speed / tempoRatio);
}
// Check if we are off-linear (musical key has been adjusted
// independent from speed) to determine if the keylock scaler
// should be used even though keylock is disabled.
if (speed != 0.0) {
double offlinear = pitchRatio / speed;
if (offlinear > kLinearScalerElipsis ||
offlinear < 1 / kLinearScalerElipsis) {
// only enable keylock scaler if pitch adjustment is at
// least 1 cent. Everything below is not hear-able.
useIndependentPitchAndTempoScaling = true;
}
}
}
if (speed != 0.0) {
// Do not switch scaler when we have no transport
enableIndependentPitchTempoScaling(useIndependentPitchAndTempoScaling,
iBufferSize);
} else if (m_speed_old != 0 && !is_scratching) {
// we are stopping, collect samples for fade out
readToCrossfadeBuffer(iBufferSize);
// Clear the scaler information
m_pScale->clear();
}
// How speed/tempo/pitch are related:
// Processing is done in two parts, the first part is calculated inside
// the KeyKontrol class and effects the visual key/pitch widgets.
// The Speed slider controls the tempoRatio and a speedSliderPitchRatio,
// the pitch amount caused by it.
// By default the speed slider controls pitch and tempo with the same
// value.
// If key lock is enabled, the speedSliderPitchRatio is decoupled from
// the speed slider (const).
//
// With preference mode KeylockMode = kLockOriginalKey
// the speedSliderPitchRatio is reset to 1 and back to the tempoRatio
// (natural vinyl Pitch) when keylock is disabled and enabled.
//
// With preference mode KeylockMode = kCurrentKey
// the speedSliderPitchRatio is not reset when keylock is enabled.
// This mode allows to enable keylock
// while the track is already played. You can reset to the tracks
// original pitch by resetting the pitch knob to center. When disabling
// keylock the pitch is reset to the linear vinyl pitch.
// The Pitch knob turns if the speed slider is moved without keylock.
// This is useful to get always an analog impression of current pitch,
// and its distance to the original track pitch
//
// The Pitch_Adjust knob does not reflect the speedSliderPitchRatio.
// So it is is useful for controller mappings, because it is not
// changed by the speed slider or keylock.
// In the second part all other speed changing controls are processed.
// They may produce an additional pitch if keylock is disabled or
// override the pitch in scratching case.
// If pitch ratio and tempo ratio are equal, a linear scaler is used,
// otherwise tempo and pitch are processed individual
// If we were scratching, and scratching is over, and we're a follower,
// and we're quantized, and not paused,
// we need to sync phase or we'll be totally out of whack and the sync
// adjuster will kick in and push the track back in to sync with the
// master.
if (m_scratching_old && !is_scratching && m_pQuantize->toBool()
&& m_pSyncControl->getSyncMode() == SYNC_FOLLOWER && !paused) {
// TODO() The resulting seek is processed in the following callback
// That is to late
requestSyncPhase();
}
double rate = 0;
// If the baserate, speed, or pitch has changed, we need to update the
// scaler. Also, if we have changed scalers then we need to update the
// scaler.
if (baserate != m_baserate_old || speed != m_speed_old ||
pitchRatio != m_pitch_old || tempoRatio != m_tempo_ratio_old ||
m_bScalerChanged) {
// The rate returned by the scale object can be different from the
// wanted rate! Make sure new scaler has proper position. This also
// crossfades between the old scaler and new scaler to prevent
// clicks.
// Handle direction change.
// The linear scaler supports ramping though zero.
// This is used for scratching, but not for reverse
// For the other, crossfade forward and backward samples
if ((m_speed_old * speed < 0) && // Direction has changed!
(m_pScale != m_pScaleVinyl || // only m_pScaleLinear supports going though 0
m_reverse_old != is_reverse)) { // no pitch change when reversing
//XXX: Trying to force RAMAN to read from correct
// playpos when rate changes direction - Albert
readToCrossfadeBuffer(iBufferSize);
// Clear the scaler information
m_pScale->clear();
}
m_baserate_old = baserate;
m_speed_old = speed;
m_pitch_old = pitchRatio;
m_tempo_ratio_old = tempoRatio;
m_reverse_old = is_reverse;
// Now we need to update the scaler with the master sample rate, the
// base rate (ratio between sample rate of the source audio and the
// master samplerate), the deck speed, the pitch shift, and whether
// the deck speed should affect the pitch.
m_pScale->setScaleParameters(baserate,
&speed,
&pitchRatio);
// The way we treat rate inside of EngineBuffer is actually a
// description of "sample consumption rate" or percentage of samples
// consumed relative to playing back the track at its native sample
// rate and normal speed. pitch_adjust does not change the playback
// rate.
rate = baserate * speed;
// Scaler is up to date now.
m_bScalerChanged = false;
} else {
// Scaler did not need updating. By definition this means we are at
// our old rate.
rate = m_rate_old;
}
bool at_end = m_filepos_play >= m_trackSamplesOld;
bool backwards = rate < 0;
bool bCurBufferPaused = false;
if (at_end && !backwards) {
// do not play past end
bCurBufferPaused = true;
} else if (rate == 0 && !is_scratching) {
// do not process samples if have no transport
// the linear scaler supports ramping down to 0
// this is used for pause by scratching only
bCurBufferPaused = true;
}
m_rate_old = rate;
// If the buffer is not paused, then scale the audio.
if (!bCurBufferPaused) {
// Perform scaling of Reader buffer into buffer.
double framesRead =
m_pScale->scaleBuffer(pOutput, iBufferSize);
// TODO(XXX): The result framesRead might not be an integer value.
// Converting to samples here does not make sense. All positional
// calculations should be done in frames instead of samples! Otherwise
// rounding errors might occur when converting from samples back to
// frames later.
double samplesRead = framesRead * kSamplesPerFrame;
if (m_bScalerOverride) {
// If testing, we don't have a real log so we fake the position.
m_filepos_play += samplesRead;
} else {
// Adjust filepos_play by the amount we processed.
m_filepos_play =
m_pReadAheadManager->getFilePlaypositionFromLog(
m_filepos_play, samplesRead);
}
// Note: The last buffer of a track is padded with silence.
// This silence is played together with the last samples in the last
// callback and the m_filepos_play is advanced behind the end of the track.
if (m_bCrossfadeReady) {
// Bring pOutput with the new parameters in and fade out the old one,
// stored with the old parameters in m_pCrossfadeBuffer
SampleUtil::linearCrossfadeBuffersIn(
pOutput, m_pCrossfadeBuffer, iBufferSize);
}
// Note: we do not fade here if we pass the end or the start of
// the track in reverse direction
// because we assume that the track samples itself start and stop
// towards zero.
// If it turns out that ramping is required be aware that the end
// or start may pass in the middle of the buffer.
} else {
// Pause
if (m_bCrossfadeReady) {
// We don't ramp here, since EnginePregain handles fades
// from and to speed == 0
SampleUtil::copy(pOutput, m_pCrossfadeBuffer, iBufferSize);
} else {
SampleUtil::clear(pOutput, iBufferSize);
}
}
for (const auto& pControl: qAsConst(m_engineControls)) {