forked from Arakula/vsthost
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vsthost.cpp
1483 lines (1289 loc) · 48.1 KB
/
vsthost.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
/*****************************************************************************/
/* vsthost.cpp : Defines the class behaviors for the application. */
/*****************************************************************************/
/******************************************************************************
Copyright (C) 2006 Hermann Seib
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
******************************************************************************/
#include "stdafx.h"
#include "vsthost.h"
#include "MainFrm.h"
#include "ChildFrm.h"
#include "specmidi.h"
#include "mididev.h"
#include "specwave.h"
#include "wavedev.h"
#include "WorkThread.h"
#include "SpecDSound.h"
#include "ShellSelDlg.h"
#include "midikeybdlg.h"
#ifdef __ASIO_H
#include "SpecAsioHost.h"
#include "AsioChannelSelectDialog.h"
#endif
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/*****************************************************************************/
/* CAboutDlg dialog used for App About */
/*****************************************************************************/
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// Dialog Data
//{{AFX_DATA(CAboutDlg)
enum { IDD = IDD_ABOUTBOX };
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CAboutDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
//{{AFX_MSG(CAboutDlg)
// No message handlers
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
//{{AFX_DATA_INIT(CAboutDlg)
//}}AFX_DATA_INIT
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CAboutDlg)
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
//{{AFX_MSG_MAP(CAboutDlg)
// No message handlers
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/*===========================================================================*/
/* CMyCommandLineInfo : command line information class */
/*===========================================================================*/
class CMyCommandLineInfo : public CCommandLineInfo
{
public:
CMyCommandLineInfo()
{
bNoLoad = FALSE;
bNoSave = FALSE;
}
virtual void ParseParam(LPCTSTR lpszParam, BOOL bFlag, BOOL bLast);
BOOL bNoLoad;
BOOL bNoSave;
};
/*****************************************************************************/
/* ParseParam : called to parse parameters */
/*****************************************************************************/
void CMyCommandLineInfo::ParseParam(LPCTSTR lpszParam, BOOL bFlag, BOOL bLast)
{
if (bFlag)
{
CString sParam(lpszParam);
if (!sParam.CompareNoCase("noload"))
bNoLoad = TRUE;
else if (!sParam.CompareNoCase("nosave"))
bNoSave = TRUE;
}
CCommandLineInfo::ParseParam(lpszParam, bFlag, bLast);
}
/*===========================================================================*/
/* CVsthostApp class members */
/*===========================================================================*/
/*****************************************************************************/
/* CVsthostApp message map */
/*****************************************************************************/
BEGIN_MESSAGE_MAP(CVsthostApp, CWinApp)
//{{AFX_MSG_MAP(CVsthostApp)
ON_COMMAND(ID_APP_ABOUT, OnAppAbout)
ON_COMMAND(ID_FILE_NEW, OnFileNew)
ON_COMMAND(IDM_MIDIDEV, OnMididev)
ON_COMMAND(IDM_WAVEDEV, OnWavedev)
ON_COMMAND(IDM_ENG_START, OnEngStart)
ON_UPDATE_COMMAND_UI(IDM_ENG_START, OnUpdateEngStart)
ON_COMMAND(IDM_ENGINE_RESTART, OnEngineRestart)
ON_UPDATE_COMMAND_UI(IDM_ENGINE_RESTART, OnUpdateEngineRestart)
ON_COMMAND(IDM_ASIO_CPL, OnAsioCpl)
ON_UPDATE_COMMAND_UI(IDM_ASIO_CPL, OnUpdateAsioCpl)
ON_COMMAND(IDM_MIDIKEYB, OnMidikeyb)
ON_UPDATE_COMMAND_UI(IDM_MIDIKEYB, OnUpdateMidikeyb)
ON_COMMAND(IDM_MIDIKEYB_PROPERTIES, OnMidikeybProperties)
ON_UPDATE_COMMAND_UI(IDM_MIDIKEYB_PROPERTIES, OnUpdateMidikeybProperties)
ON_COMMAND(IDM_ASIO_CHN, OnAsioChn)
ON_UPDATE_COMMAND_UI(IDM_ASIO_CHN, OnUpdateAsioChn)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/*****************************************************************************/
/* CVsthostApp : constructor */
/*****************************************************************************/
CVsthostApp::CVsthostApp()
{
bEngRunning = FALSE;
nTypeWIn = nTypeWOut = -1;
pMidiKeyb = 0;
}
/*****************************************************************************/
/* The one and only CVsthostApp object */
/*****************************************************************************/
CVsthostApp theApp;
/*****************************************************************************/
/* InitInstance : application initialization */
/*****************************************************************************/
BOOL CVsthostApp::InitInstance()
{
// Allow XP Look & Feel
InitCommonControls();
CWinApp::InitInstance();
if (FAILED(CoInitialize(NULL)))
return FALSE;
AfxEnableControlContainer();
#if 0
SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
#endif
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need.
#ifdef _AFXDLL
Enable3dControls(); // Call this when using MFC in a shared DLL
#else
Enable3dControlsStatic(); // Call this when linking to MFC statically
#endif
// Change the registry key under which our settings are stored.
SetRegistryKey(_T("Seib"));
CMyCommandLineInfo cmdInfo;
ParseCommandLine(cmdInfo);
bNoSave = cmdInfo.bNoSave;
#if 0 /* change for dynamic profiles! */
// dynamic profile based on application name
char szAppName[_MAX_PATH];
::GetModuleFileName(NULL,szAppName,sizeof(szAppName));
char *absl = strrchr(szAppName, '\\');
char *extn = strrchr(szAppName, '.');
if (extn > absl)
*extn = '\0';
free((void *)m_pszProfileName); /* generate profile section */
m_pszProfileName = strdup(absl ? absl + 1 : szAppName);
free((void *)m_pszAppName); /* and application name */
m_pszAppName = strdup(m_pszProfileName);
// from now on, Get/SetProfile can be used
#endif
#ifdef __ASIO_H
pAsioHost = new CSpecAsioHost;
#else
pAsioHost = 0;
#endif
// To create the main window, this code creates a new frame window
// object and then sets it as the application's main window object.
CMDIFrameWnd* pFrame = new CMainFrame;
m_pMainWnd = pFrame;
// create main MDI frame window
if (!pFrame->LoadFrame(IDR_MAINFRAME))
return FALSE;
// try to load shared MDI menus and accelerator table
//TODO: add additional member variables and load calls for
// additional menu types your application may need.
HINSTANCE hInst = AfxGetResourceHandle();
m_hMDIMenu = ::LoadMenu(hInst, MAKEINTRESOURCE(IDR_VSTHOSTYPE));
m_hMDIAccel = ::LoadAccelerators(hInst, MAKEINTRESOURCE(IDR_VSTHOSTYPE));
// The main window has been initialized, so show and update it.
pFrame->ShowWindow(m_nCmdShow);
pFrame->UpdateWindow();
wTID = 0; /* reset HR timer ID */
timeGetDevCaps(&tc, sizeof(tc)); /* get timer capabilities */
for (int i = 0; i < 2; i++) /* prepare empty buffers */
{
emptyBuf[i] = new float[44100];
if (emptyBuf[i])
for (int j = 0; j < 44100; j++)
emptyBuf[i][j] = 0.f;
}
CWaveOutDeviceList ol;
sWaveMapper = CString("MME: ") + ol[0];
/* create work thread */
pWorkThread = new CWorkThread(&vstHost);
int nBufSz = GetProfileInt("Settings", "WaveOutBufSize", 4410);
/* open outputs device */
MidiOut.Open(GetProfileString("Settings", "MidiOut"));
LoadWaveOutDevice(GetProfileString("Settings", "WaveOut", sWaveMapper),
nBufSz);
#ifdef __ASIO_H
if (pAsioHost) /* if ASIO host there, pass thread */
{
pAsioHost->SetWorkThread(pWorkThread);
if (pAsioHost->IsLoaded())
SetAsioChannels(GetProfileString("Settings", "AsioChnIn"),
GetProfileString("Settings", "AsioChnOut"));
}
#endif
/* open input devices */
MidiIn.Open(GetProfileString("Settings", "MidiIn"),
OPENDEFAULT,
OPENDEFAULT,
CALLBACK_FUNCTION);
MidiIn.SetMidiThru(GetProfileInt("Settings", "MidiThru", FALSE));
if (GetProfileString("Settings", "WaveOut", sWaveMapper).
Left(6).CompareNoCase("ASIO: "))
LoadWaveInDevice(GetProfileString("Settings", "WaveIn", sWaveMapper),
nBufSz);
if (!cmdInfo.bNoLoad) /* if not disabled, */
LoadSetup(); /* load setup */
/* if called with effect name, open */
if (cmdInfo.m_nShellCommand == CCommandLineInfo::FileOpen)
LoadEffect(cmdInfo.m_strFileName);
if (GetProfileInt("Settings", "Engine", 0))
EngineStart();
return TRUE;
}
/*****************************************************************************/
/* ExitInstance : called when the application terminates */
/*****************************************************************************/
int CVsthostApp::ExitInstance()
{
FullStop(); /* stop engine and close devices */
if (!bNoSave) /* if not disabled, */
SaveSetup(); /* save current setup */
vstHost.RemoveAll(); /* remove all loaded effects */
if (pMidiKeyb) /* if MIDI keyboard there */
delete pMidiKeyb; /* delete it */
for (int i = 0; i < 2; i++) /* delete empty buffers */
if (emptyBuf[i])
delete[] emptyBuf[i];
#ifdef __ASIO_H
if (pAsioHost) /* remove ASIO Host */
delete pAsioHost;
#endif
if (pWorkThread) /* remove work thread */
delete pWorkThread;
if (m_hMDIMenu != NULL) /* free resources */
FreeResource(m_hMDIMenu);
if (m_hMDIAccel != NULL)
FreeResource(m_hMDIAccel);
TRACE0("VSTHost ended.\n");
return CWinApp::ExitInstance();
}
/*****************************************************************************/
/* OnFileNew : called when File / New is selected */
/*****************************************************************************/
void CVsthostApp::OnFileNew()
{
CMainFrame* pFrame = STATIC_DOWNCAST(CMainFrame, m_pMainWnd);
CString sStartAt;
sStartAt = GetProfileString("Load", "Path");
if (sStartAt.GetLength())
sStartAt += "\\*.*";
CFileDialog dlg(TRUE, NULL, sStartAt);
if (dlg.DoModal() == IDOK)
{
sStartAt = dlg.GetPathName();
sStartAt = sStartAt.Left(sStartAt.ReverseFind('\\'));
WriteProfileString("Load", "Path", sStartAt);
LoadEffect(dlg.GetPathName());
}
}
/*****************************************************************************/
/* OnAppAbout : called to display the About... dialog */
/*****************************************************************************/
void CVsthostApp::OnAppAbout()
{
CAboutDlg aboutDlg;
aboutDlg.DoModal();
}
/*****************************************************************************/
/* FillPopup : fills a popup menu with an effect's programs */
/*****************************************************************************/
void CVsthostApp::FillPopup(CMenu* pPopupMenu, int nEffect)
{
int i, j;
CEffect *pEffect = vstHost.GetAt(nEffect);
/* remove all old items */
for (i = pPopupMenu->GetMenuItemCount() - 1; i >= 2; i--)
{
if ((pPopupMenu->GetSubMenu(i)) ||
(pPopupMenu->GetMenuItemID(i) ==
IDM_EFF_PROGRAM_0))
pPopupMenu->RemoveMenu(i, MF_BYPOSITION);
}
if ((pEffect) &&
(pEffect->pEffect->numPrograms > 1))
{
long lProg = pEffect->EffGetProgram();
bool bProgSet = false;
int nClass = (pEffect->pEffect->flags & effFlagsIsSynth) ?
kPlugCategSynth :
kPlugCategUnknown;
for (i = 0; i < pEffect->pEffect->numPrograms; i += 16)
{
CMenu popup;
popup.CreatePopupMenu();
for (j = i; (j < i + 16) && (j < pEffect->pEffect->numPrograms); j++)
{
CString sProg;
char szPgName[256] = "";
if (!pEffect->EffGetProgramNameIndexed(nClass, j, szPgName))
{
bProgSet = true;
pEffect->EffSetProgram(j);
pEffect->EffGetProgramName(szPgName);
if (!*szPgName)
sprintf(szPgName, "Program %d", j);
}
sProg.Format("%d. %s", j, szPgName);
popup.AppendMenu(MF_STRING, IDM_EFF_PROGRAM_0 + j, sProg);
}
CString sSub;
sSub.Format("Programs %d-%d", i, j-1);
pPopupMenu->AppendMenu(MF_POPUP | MF_STRING,
(UINT)popup.Detach(),
sSub);
}
if (bProgSet)
pEffect->EffSetProgram(lProg);
pPopupMenu->CheckMenuItem(IDM_EFF_PROGRAM_0 + lProg,
MF_CHECKED | MF_BYCOMMAND);
}
}
/*****************************************************************************/
/* LoadEffect : loads a new effect */
/*****************************************************************************/
BOOL CVsthostApp::LoadEffect(LPCSTR lpszFileName, int *pnEffect, int nUniqueId)
{
BOOL bWasRunning = bEngRunning; /* get current engine state */
EngineStop(); /* stop engine */
if (pnEffect) /* initialize effect ID if necessary */
*pnEffect = -1;
int nEffect = vstHost.LoadPlugin(lpszFileName, nUniqueId);
if (nEffect >= 0) /* look whether shell category */
{
CSmpEffect *pEffect = (CSmpEffect *)vstHost.GetAt(nEffect);
/* if that's a shell plugin */
if ((pEffect->EffGetPlugCategory() == kPlugCategShell) &&
(!nUniqueId)) /* and not yet specified */
{ /* enumerate the contained effects */
CStringArray saNames;
CDWordArray dwaIDs;
char szName[_MAX_PATH];
unsigned long ulID;
while ((ulID = pEffect->EffGetNextShellPlugin(szName)))
{
if (saNames.Add(szName) < 0)
break;
if (dwaIDs.Add(ulID) < 0)
{
saNames.RemoveAt(saNames.GetUpperBound());
break;
}
}
vstHost.RemoveAt(nEffect); /* delete shell effect */
nEffect = -1;
CShellSelDlg dlg; /* get plugin ID to use */
dlg.saNames.Append(saNames);
if (dlg.DoModal() == IDOK) /* and eventually re-load for that */
nEffect = vstHost.LoadPlugin(lpszFileName, dwaIDs[dlg.nSelID]);
}
}
if (bWasRunning) /* if it was running before, */
EngineStart(); /* restart engine */
if (nEffect >= 0)
{
// create a new MDI child window
CChildFrame *pChild = (CChildFrame *)CreateChild(RUNTIME_CLASS(CChildFrame),
IDR_VSTHOSTYPE);
if (pChild)
{
pChild->SetEffect(nEffect);
ERect *pRect = NULL;
vstHost.GetAt(nEffect)->EffEditGetRect(&pRect);
if (pnEffect)
*pnEffect = nEffect;
return TRUE;
}
}
return FALSE;
}
/*****************************************************************************/
/* CreateChild : creats a new MDI child window */
/*****************************************************************************/
CMDIChildWnd * CVsthostApp::CreateChild
(
CRuntimeClass *pClass,
UINT nResource,
HMENU hMenu,
HACCEL hAccel
)
{
if (!hMenu)
hMenu = m_hMDIMenu;
if (!hAccel)
hAccel = m_hMDIAccel;
CMDIFrameWnd *pMain = (CMDIFrameWnd*)m_pMainWnd;
CMDIChildWnd *pChild = pMain->CreateNewChild(pClass,
nResource,
hMenu,
hAccel);
if (pChild)
pMain->MDIActivate(pChild);
return pChild;
}
/*****************************************************************************/
/* OnMididev : called to determine the used MIDI devices */
/*****************************************************************************/
void CVsthostApp::OnMididev()
{
CMidiDeviceDialog dlg(AfxGetMainWnd());
dlg.InName = GetProfileString("Settings", "MidiIn");
dlg.OutName = GetProfileString("Settings", "MidiOut");
dlg.bPassThru = GetProfileInt("Settings", "MidiThru", FALSE);
if (dlg.DoModal() == IDOK)
{
CWaitCursor wc; /* display wait cursor */
BOOL bWasRunning = bEngRunning; /* remember old setting */
EngineStop(); /* stop input engine */
if (!MidiIn.Open(dlg.InName, /* open input device */
OPENDEFAULT,
OPENDEFAULT,
CALLBACK_FUNCTION))
dlg.InName = "";
if (!MidiOut.Open(dlg.OutName)) /* open output device */
dlg.OutName = "";
MidiIn.SetMidiThru(dlg.bPassThru); /* set midi thru */
WriteProfileString("Settings", "MidiIn", dlg.InName);
WriteProfileString("Settings", "MidiOut", dlg.OutName);
WriteProfileInt("Settings", "MidiThru", dlg.bPassThru);
if (bWasRunning) /* if it was running before, */
EngineStart(); /* start input engine */
}
}
/*****************************************************************************/
/* TimerCallback : high-resolution timer entry point */
/*****************************************************************************/
void CALLBACK CVsthostApp::TimerCallback
(
UINT uID,
UINT uMsg,
DWORD dwUser,
DWORD dw1,
DWORD dw2
)
{
if (dwUser) /* pass it on to real app. object */
((CVsthostApp *)dwUser)->HRTimer();
}
/*****************************************************************************/
/* SetTimer : starts / stops a high-resolution timer if no Wave In device */
/*****************************************************************************/
BOOL CVsthostApp::SetTimer(UINT nMSecs)
{
if ((!nMSecs) && (wTID)) /* if killing a running timer */
{
timeKillEvent(wTID);
wTID = 0;
timeEndPeriod(tc.wPeriodMin);
nTimerMSecs = 0;
return TRUE;
}
else /* if starting a HR timer */
{
if (nMSecs < tc.wPeriodMin) /* look whether possible */
return FALSE;
nTimerMSecs = nMSecs; /* remember requested period */
nMSecs /= 10; /* set HR timer to 1/10 of that */
if (nMSecs < tc.wPeriodMin) /* prohibit going TOO low */
nMSecs = tc.wPeriodMin;
timeBeginPeriod(nMSecs); /* start using timer services */
dwLastTime = timeGetTime(); /* setup for correct start */
dwRest = 0;
wTID = timeSetEvent( /* start the timer procedure */
nMSecs,
(nMSecs > 1) ? nMSecs / 2 : 1,
TimerCallback,
(DWORD)this,
TIME_PERIODIC);
return !!wTID; /* return whether started */
}
}
/*****************************************************************************/
/* HRTimer : called when the high-res timer ticks */
/*****************************************************************************/
void CVsthostApp::HRTimer()
{
static DWORD dwCurTime; /* current time */
static DWORD dwOffset; /* time offset */
static WORD wClocks; /* # clock ticks to send */
static WORD i; /* clock tick counter */
dwCurTime = timeGetTime(); /* get current time */
dwOffset = dwCurTime - /* calculate #msecs since last msg */
dwLastTime;
if (dwOffset > dwCurTime) /* if overflow */
{
dwLastTime = 0; /* reset start tick */
dwOffset = dwCurTime; /* this may cause one hiccup every */
} /* 49 days... horrible... */
dwOffset += dwRest; /* add eventual rest */
if (dwOffset > nTimerMSecs) /* if another timer tick's due */
{
dwLastTime = dwCurTime; /* remember this tick */
dwRest = dwOffset - nTimerMSecs; /* calculate new rest */
pWorkThread->Process(emptyBuf, /* process empty samples */
(44100 * nTimerMSecs / 1000),
2,
dwCurTime - dwStartStamp);
}
}
/*****************************************************************************/
/* LoadWaveInDevice : loads a Wave In device */
/*****************************************************************************/
BOOL CVsthostApp::LoadWaveInDevice(CString sDevice, int nBufSz)
{
BOOL bRC = FALSE;
int nDevType = 0;
TRACE2("LoadWaveInDevice(\"%s\",%d)\n", (LPCSTR)sDevice, nBufSz);
/* either run with Wave In */
if (!sDevice.Left(5).CompareNoCase("MME: "))
sDevice = sDevice.Mid(5);
else if (!sDevice.Left(4).CompareNoCase("DS: "))
{
nDevType = 1;
sDevice = sDevice.Mid(4);
}
else if (!sDevice.Left(6).CompareNoCase("ASIO: "))
{
nDevType = 2;
sDevice = sDevice.Mid(6);
}
nTypeWIn = nDevType;
switch (nDevType)
{
case 0 : /* MME ? */
WaveIn.SetupAllocSize(44100 / nBufSz, nBufSz);
bRC = WaveIn.Open(sDevice,
NULL,
WAVEOPENDEFAULT,
WAVEOPENDEFAULT,
CALLBACK_EVENT);
WaveIn.SetWorkThread(pWorkThread);
break;
case 1 : /* DirectSound ? */
#pragma message("DirectSound Input Device not fully coded!")
bRC = DSoundIn.Open((LPCSTR)sDevice, DSCBCAPS_WAVEMAPPED, nBufSz, NULL);
DSoundIn.SetWorkThread(pWorkThread);
break;
case 2 : /* ASIO ? */
// done in LoadWaveOutDevice()
break;
}
TRACE1(" -> %sOK\n", bRC?"":"NOT ");
return bRC;
}
/*****************************************************************************/
/* LoadWaveOutDevice : loads a Wave Out device */
/*****************************************************************************/
BOOL CVsthostApp::LoadWaveOutDevice
(
CString sDevice,
int &nBufSz
)
{
BOOL bRC = FALSE;
int nDevType = 0;
TRACE2("LoadWaveOutDevice(\"%s\",%d)\n", (LPCSTR)sDevice, nBufSz);
if (!sDevice.Left(5).CompareNoCase("MME: "))
sDevice = sDevice.Mid(5);
else if (!sDevice.Left(4).CompareNoCase("DS: "))
{
nDevType = 1;
sDevice = sDevice.Mid(4);
}
else if (!sDevice.Left(6).CompareNoCase("ASIO: "))
{
nDevType = 2;
sDevice = sDevice.Mid(6);
}
nTypeWOut = nDevType;
switch (nDevType)
{
case 0 : /* MME ? */
DSoundOut.Close();
#ifdef __ASIO_H
if ((pAsioHost) && (pAsioHost->IsLoaded()))
pAsioHost->UnloadDriver();
#endif
bRC = WaveOut.Open(sDevice,
NULL,
WAVEOPENDEFAULT,
WAVEOPENDEFAULT,
CALLBACK_EVENT);
WaveOut.AllocateBuffers(44100 / nBufSz);
break;
case 1 : /* DirectSound ? */
WaveOut.Close();
#ifdef __ASIO_H
if ((pAsioHost) && (pAsioHost->IsLoaded()))
pAsioHost->UnloadDriver();
#endif
bRC = DSoundOut.Open(sDevice,
// DSBCAPS_CTRLDEFAULT |
DSBCAPS_CTRLFREQUENCY |
DSBCAPS_CTRLPAN |
DSBCAPS_CTRLVOLUME |
DSBCAPS_CTRLPOSITIONNOTIFY |
DSBCAPS_GETCURRENTPOSITION2 |
DSBCAPS_GLOBALFOCUS,
nBufSz, NULL);
break;
case 2 : /* ASIO ? */
WaveOut.Close();
DSoundOut.Close();
#ifdef __ASIO_H
if (pAsioHost)
bRC = pAsioHost->LoadDriver((char *)(LPCSTR)sDevice, nBufSz);
if (bRC) /* if load went OK, */
{ /* make sure to use the correct */
ASIOSampleRate cRate; /* sample rate... */
pAsioHost->GetSampleRate(&cRate);
vstHost.SetSampleRate((float)cRate);
}
#endif
break;
}
TRACE2(" -> %sOK, buffer size=%d\n", bRC?"":"NOT ", nBufSz);
vstHost.SetBlockSize(nBufSz);
return bRC;
}
/*****************************************************************************/
/* SetAsioChannels : sets stereo channels */
/*****************************************************************************/
bool CVsthostApp::SetAsioChannels(LPCSTR lpszChnIn, LPCSTR lpszChnOut)
{
#ifdef __ASIO_H
if ((pAsioHost) && (pAsioHost->IsLoaded()))
{
CString sIn(lpszChnIn), sOut(lpszChnOut);
long i, lIn = 0, lOut = 0, lCur = -1;
pAsioHost->GetChannels(&lIn, &lOut);
ASIOChannelInfo info = {0};
long lCurIn = -1, lCurOut = -1;
info.isInput = ASIOTrue;
for (i = 0; i < lIn; i++)
{
info.channel = i;
pAsioHost->GetChannelInfo(&info);
if (lCurIn < 0) /* if not started yet */
{
if (sIn.IsEmpty()) /* if simply going for default */
pAsioHost->SetActiveChannel(i, true);
else if (!sIn.CompareNoCase(info.name))
{
pAsioHost->SetActiveChannel(i, true);
lCurIn++;
}
else
pAsioHost->SetActiveChannel(i, false);
}
else if (lCurIn >= 1) /* if already found all */
pAsioHost->SetActiveChannel(i, false);
else /* if one of the selected channels */
{
pAsioHost->SetActiveChannel(i, true);
lCurIn++;
}
}
info.isInput = ASIOFalse;
for (i = 0; i < lOut; i++)
{
info.channel = i;
pAsioHost->GetChannelInfo(&info);
if (lCurOut < 0) /* if not started yet */
{
if (sOut.IsEmpty()) /* if simply going for default */
pAsioHost->SetActiveChannel(lIn + i, true);
else if (!sOut.CompareNoCase(info.name))
{
pAsioHost->SetActiveChannel(lIn + i, true);
lCurOut++;
}
else
pAsioHost->SetActiveChannel(lIn + i, false);
}
else if (lCurOut >= 1) /* if already found all */
pAsioHost->SetActiveChannel(lIn + i, false);
else /* if one of the selected channels */
{
pAsioHost->SetActiveChannel(lIn + i, true);
lCurOut++;
}
}
return true;
}
return false;
#endif
}
/*****************************************************************************/
/* OnWavedev : called to configure the wave devices */
/*****************************************************************************/
void CVsthostApp::OnWavedev()
{
CWaveDeviceDialog dlg(AfxGetMainWnd());
dlg.InName = GetProfileString("Settings", "WaveIn", sWaveMapper);
dlg.OutName = GetProfileString("Settings", "WaveOut", sWaveMapper);
dlg.nBufSize = GetProfileInt("Settings", "WaveOutBufSize", 4410);
if (dlg.DoModal() == IDOK)
{
CWaitCursor wc; /* display wait cursor */
BOOL bWasRunning = bEngRunning; /* remember old setting */
EngineStop(); /* stop input engine */
if (dlg.OutName.Left(6).CompareNoCase("ASIO: "))
{
TRACE0("#(re-)Open Wave Input Device\n");
/* open input device */
if (!LoadWaveInDevice(dlg.InName, dlg.nBufSize))
dlg.InName = ""; /* upon error reset name */
}
else
{
WaveIn.Close();
DSoundIn.Close();
}
WriteProfileString("Settings", "WaveIn", dlg.InName);
TRACE0("#(re-)Open Wave Output Device\n");
/* open output device */
if (!LoadWaveOutDevice(dlg.OutName, dlg.nBufSize))
dlg.OutName = "";
WriteProfileString("Settings", "WaveOut", dlg.OutName);
WriteProfileInt("Settings", "WaveOutBufSize", dlg.nBufSize);
if (bWasRunning) /* if it was running before, */
EngineStart(); /* start input engine */
}
}
/*****************************************************************************/
/* SetupLatency : we need some latency to make the system work without hiccup*/
/*****************************************************************************/
void CVsthostApp::SetupLatency()
{
if (!WaveOut.IsOpen()) /* only do if output open */
return;
#if 0
// works without that as well.
for (int i = 0; i < 2; i++) /* prepare a bit */
pWorkThread->Process(emptyBuf, 2205); /* of empty samples */
#endif
}
/*****************************************************************************/
/* EngineStop : stops eventual running input engine */
/*****************************************************************************/
void CVsthostApp::EngineStop()
{
if (!bEngRunning)
return;
TRACE0("Stopping VSTHost engine\n");
SetTimer(0); /* close eventually opened HR timer */
WaveIn.Stop(); /* stop eventual record mode */
DSoundIn.Stop();
MidiIn.Stop();
TRACE0("# Resetting Wave input device\n");
WaveIn.Reset(); /* and make sure it doesn't pump on */
TRACE0("# Resetting MIDI input device\n");
MidiIn.Reset();
TRACE0("# Both devices reset.\n");
#ifdef __ASIO_H
if (pAsioHost)
{
TRACE0("# Stopping ASIO Host\n");
pAsioHost->Stop();
}
#endif
int nSleeps = 0;
int nWaitIn = WaveIn.WaitingBuffers();
int nWaitOut = WaveOut.WaitingBuffers();
while (nWaitIn || nWaitOut) /* wait until all work done */
{
TRACE2("# Waiting for buffer completion (%d in, %d out)\n",
WaveIn.WaitingBuffers(),
WaveOut.WaitingBuffers());
Sleep (50);
nWaitIn = WaveIn.WaitingBuffers();
nWaitOut = WaveOut.WaitingBuffers();
if (++nSleeps > 20)
{
TRACE("# Waited over a second; wait aborted.\n");
break;
}
}
TRACE0("#VSTHost Engine stopped.\n");
bEngRunning = FALSE;
}
/*****************************************************************************/
/* EngineStart : restarts input engine */
/*****************************************************************************/
void CVsthostApp::EngineStart()
{
if (bEngRunning)
return;
TRACE0("Starting VSTHost engine\n");
int nTimer = WaveOut.AllocatedBuffers();
if (nTimer)
nTimer = 1000 / nTimer;
else
nTimer = 44100 / GetProfileInt("Settings", "WaveOutBufSize", 4410);
#ifdef __ASIO_H
if ((nTypeWOut == 2) && /* if ASIO Host Output */
pAsioHost &&
pAsioHost->IsLoaded())
{
TRACE0(" Starting ASIO Host\n");
pAsioHost->Start();
dwStartStamp = timeGetTime(); /* put common timestamp reference */
}
else
{
#endif
SetupLatency(); /* setup latency */