VACoreImpl.cpp 131 KB
Newer Older
Jonas Stienen's avatar
Jonas Stienen committed
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
/*
 *    VVV        VVV A
 *     VVV      VVV AAA        Virtual Acoustics
 *      VVV    VVV   AAA       Real-time auralisation for virtual reality    
 *       VVV  VVV     AAA
 *        VVVVVV       AAA     (c) Copyright Institut fr Technische Akustik (ITA)
 *         VVVV         AAA        RWTH Aachen (http://www.akustik.rwth-aachen.de)
 *
 */
  
// $Id: VACoreImpl.cpp 4647 2016-03-11 18:15:50Z stienen $

#include "VACoreImpl.h"

// VA base
#include <VABaseDefinitions.h>
#include <VAStruct.h>
#include <VACoreVersion.h>

// VA includes
#include "Audiosignals/VAAudioSignalSourceManager.h"
#include "Audiosignals/VAAudiofileSignalSource.h"
#include "Audiosignals/VAAudiofileSignalSource.h"
#include "Audiosignals/VAEngineSignalSource.h"
#include "Audiosignals/VAMachineSignalSource.h"
#include "Audiosignals/VASequencerSignalSource.h"
#include "Data/VAHRIRManager.h"
#include "Drivers/Audio/VAASIOBackend.h"
#include "Drivers/Audio/VAPortaudioBackend.h"
#include "Rendering/VAAudioRenderer.h"
#include "Rendering/VAAudioRendererRegistry.h"
#include "Reproduction/VAAudioReproductionModule.h"
#include "Reproduction/VAAudioReproductionModuleRegistry.h"
#include "Scene/VAScene.h"
#include "Scene/VASoundSourceDesc.h"
#include "Scene/VAListenerDesc.h"
#include "Utils/VADebug.h"
#include "Utils/VAUtils.h"
#include "VAAudiostreamTracker.h"
#include "VABaseDefinitions.h"
#include "VADirectivityManager.h"
#include <VAException.h>
#include "VALog.h"
#include "VACoreEventManager.h"
#include "VACoreFactory.h"
#include "VACoreThread.h"
#include "VASourceListenerMetrics.h"

// ITA includes
#include <ITAASCIITable.h>
#include <ITAClock.h>
#include <ITAException.h>
#include <ITAFilesystemUtils.h>
#include <ITAFunctors.h>
#include <ITAPeakDetector.h>
#include <ITASoundSample.h>
#include <ITASoundSampler.h>
#include <ITASoundSamplePool.h>
#include <ITAStreamAmplifier.h>
#include <ITAStreamPatchbay.h>
#include <ITAStreamProbe.h>
#include <ITAStringUtils.h>
#include <ITATimer.h>

// Vista includes
#include <VistaTools/VistaFileSystemFile.h>
#include <VistaTools/VistaFileSystemDirectory.h>

// 3rdParty includes
#include <DAFF.h>

// STL includes
#include <algorithm>
74
#include <iomanip>
Jonas Stienen's avatar
Jonas Stienen committed
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
#include <iostream>

/*

	Informationen
	=-=-=-=-=-=-=

	Thread-safety & locking

	Alle durch die Schnittstelle nach aussen angebotenen Funktionen, werden
	gegen Reentrance grob-granular mittels eines kritischen Bereiches gesperrt.
	Damit sind auch parallele Calls auf unterschiedliche Methoden der Klasse
	unterbunden. Sollte dies zu Performance-Problemen fhren, kann ein 
	verfeinerter Locking-Mechanismus entwickelt werden. Zunchst mal aber so.


	TODO: berall sicherstellen, das ITAExceptions zu VAExceptions umgebaut werden!!!

*/

// --= Globale Definitionen =--

#define DO_SEND_MEASURE_UPDATE_EVENTS 1


// --= Hilfsmakros =--

// berprfung ob Initialisiert
#define VA_CHECK_INITIALIZED \
{ if (m_iState != VA_CORESTATE_READY) VA_EXCEPT2(MODAL_ERROR, "Core not initialized"); }

// Mutex-Lock welches parallelen Methoden-Mehrfracheintritt (reentrance) im Methoden-Scope verhindert
#define VA_NO_REENTRANCE \
ITACriticalSectionLock oReentranceLock(m_csReentrance)

// Manuelles das Lock gegen parallelen Methoden-Mehrfracheintritt (reentrance) holen
#define VA_LOCK_REENTRANCE \
m_csReentrance.enter()

// Manuelle das Lock gegen parallelen Methoden-Mehrfracheintritt (reentrance) freigeben 
#define VA_UNLOCK_REENTRANCE \
m_csReentrance.leave()

/*

	Sichere Ausnahmebehandlung

	Problem: Intern knnen auch andere Typen von Ausnahmen als
			 CVAException geworfen werden. Nach aussen hin drfen
			 aber NUR CVAExceptions geworfen werden (Konsistent)

	Lsung: TRY-/CATCH-Makros fr abgesicherte Bereiche in allen Methoden
			der externen Schnittstelle. Zweistufiger Aufbau.
			1. (innen) Fange alle Exception-Typen und konvertiere sie in CVAExceptions
			2. (aussen) Fange die einzig mgl. CVAExceptions und biete
			   gemeinsamen Catch-Weg zur Problemlsung (Aufrumen) an

			   try {
				   try {
					   // Code ...
				   } catch (ITAException& e) {
					   // Konvertiere zu CVAException
				   } catch (VistaExceptionBase& e) {
					   // Konvertiere zu CVAException
				   } catch (...)
					  // Generiere unerwartete CVAException
				   }
			   } catch (CVAException& e) {
				   // Gemeinsames Aufrumen
			   }

	Beispiel:
			
			VA_TRY {
				// Code ..
			} VA_CATCH {
				// Mach was ...
			}

	Hinweis: Initiale/finale Geschweifte Klammer fehlen, da diese hinter die Makros geschrieben werden

*/

#define VA_TRY \
	try { \
		try

#define VA_CATCH(EXPR) \
		  catch (CVAException& e) { \
			throw e; \
		} catch (ITAException& e) { \
			throw convert2VAException(e); \
		} catch (VistaExceptionBase& e) { \
			throw convert2VAException(e); \
		} catch (...) { \
			throw getDefaultUnexpectedVAException(); \
		} \
	} catch (CVAException& EXPR)

#define VA_FINALLY \
		  catch (CVAException& e) { \
			throw e; \
		} catch (ITAException& e) { \
			throw convert2VAException(e); \
		} catch (VistaExceptionBase& e) { \
			throw convert2VAException(e); \
		} catch (...) { \
			throw getDefaultUnexpectedVAException(); \
		} \
	} catch (...)

#define VA_RETHROW \
		  catch (CVAException& e) { \
			throw e; \
		} catch (ITAException& e) { \
			throw convert2VAException(e); \
		} catch (VistaExceptionBase& e) { \
			throw convert2VAException(e); \
		} catch (...) { \
			throw getDefaultUnexpectedVAException(); \
		} \
	} catch (...) { throw; }


IVACore* VACore::CreateCoreInstance( const CVAStruct& oArgs )
{
	VA_TRACE( "CoreConfig", oArgs );
	return new CVACoreImpl( oArgs );
}

IVACore* VACore::CreateCoreInstance( const std::string& sConfigFile )
206
{	
Jonas Stienen's avatar
Jonas Stienen committed
207
208
209
210
211
	CVAStruct oFinalCoreConfigStruct, oCurrentConfig;
	std::list< VistaFileSystemFile > voConfigFiles;
	std::vector< VistaFileSystemDirectory > voIncludePaths;
	voConfigFiles.push_back( VistaFileSystemFile( sConfigFile ) );

212
213
	VA_PRINT( "VA working directory: '" << VistaFileSystemDirectory::GetCurrentWorkingDirectory() << "'" );

Jonas Stienen's avatar
Jonas Stienen committed
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
	while( voConfigFiles.empty() == false )
	{
		VistaFileSystemFile oCurrentConfigFile( voConfigFiles.front() );
		voConfigFiles.pop_front();

		if( oCurrentConfigFile.Exists() == false )
		{
			for( size_t n=0; n<voIncludePaths.size(); n++ )
			{
				std::string sCombinedFilePath = voIncludePaths[n].GetName() + PATH_SEPARATOR + oCurrentConfigFile.GetLocalName();
				oCurrentConfigFile.SetName( sCombinedFilePath );
				if( oCurrentConfigFile.Exists() && oCurrentConfigFile.IsFile() )
				{
					VA_INFO( "CoreConfig", "Including further configuration file '" +  oCurrentConfigFile.GetLocalName() + 
						"' from include path '" + voIncludePaths[n].GetName() + "'" );
					break;
				}
			}

			if( !oCurrentConfigFile.Exists() )
			{
				VA_EXCEPT2( FILE_NOT_FOUND, "Configuration file '" + oCurrentConfigFile.GetLocalName() + "' not found, aborting." );
			}
		}
		
		VA_VERBOSE( "CoreConfig", std::string( "Reading INI file '") + oCurrentConfigFile.GetLocalName() + "'" );
		readINIFileAsStruct( oCurrentConfigFile.GetName(), oCurrentConfig );
				
		if( oCurrentConfig.HasKey( "paths" ) )
		{
			const CVAStruct& oPaths( oCurrentConfig[ "paths" ] );
			CVAStruct::const_iterator it = oPaths.Begin();
			while( it != oPaths.End() )
			{
				const CVAStructValue& oIncludePath( (it++)->second );
				VistaFileSystemDirectory oNewPathDir( oIncludePath );
				if( oNewPathDir.Exists() && oNewPathDir.IsDirectory() )
					voIncludePaths.push_back( oNewPathDir );
			}
		}

		if( oCurrentConfig.HasKey( "files" ) )
		{
			const CVAStruct& oPaths( oCurrentConfig[ "files" ] );
			CVAStruct::const_iterator it = oPaths.Begin();
			while( it != oPaths.End() )
			{
261
262
				const CVAStructValue& oIncludeFile( (it++)->second );
				
Jonas Stienen's avatar
Jonas Stienen committed
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
				voConfigFiles.push_back( VistaFileSystemFile( oIncludeFile ) );
			}
		}

		oCurrentConfig.RemoveKey( "files" );

		// Merge structs (check for uniqueness)
		oFinalCoreConfigStruct.Merge( oCurrentConfig, true );
	}

	return CreateCoreInstance( oFinalCoreConfigStruct );
}

// Trick um DLL-Pfad zu ermitteln
EXTERN_C IMAGE_DOS_HEADER __ImageBase;

279
std::string VACore::GetCoreLibFilePath()
Jonas Stienen's avatar
Jonas Stienen committed
280
{
281
282
	CHAR pszPath[ MAX_PATH + 1 ] = { 0 };
#ifdef WIN32
Jonas Stienen's avatar
Jonas Stienen committed
283
	GetModuleFileNameA( (HINSTANCE) &__ImageBase, pszPath, _countof(pszPath) );
284
285
286
287
#else
	VA_EXCEPT2( NOT_IMPLEMENTED, "This function is not implemented for your platform. Sorry." );
#endif // WIN32
	return std::string( pszPath );
Jonas Stienen's avatar
Jonas Stienen committed
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
}

CVACoreImpl::CVACoreImpl(const CVAStruct& oArgs)
: m_pAudioDriverBackend(nullptr),
  m_pGlobalSamplePool(nullptr),
  m_pGlobalSampler(nullptr),
  m_pSignalSourceMan(nullptr),
  m_pDirMan(nullptr),
  m_pHRIRMan(nullptr),
  m_pSceneMan(nullptr),
  m_pNewSceneState(nullptr),
  m_iCurActiveListener(-1),
  m_iNewActiveListener(-1),
  m_iUpdActiveListener(-1),
  m_pCoreEventMan(nullptr),
  m_pCoreThread(nullptr),
  m_pInputAmp(nullptr),
  m_pR2RPatchbay(nullptr),
  m_pOutputPatchbay(nullptr),
  m_pInputPeakDetector(nullptr),
  m_pOutputPeakDetector(nullptr),
  m_pOutputTracker(nullptr),
  m_pStreamProbeDeviceInput(nullptr),
  m_pStreamProbeFinal(nullptr),
  m_pCurSceneState(nullptr),
  m_pClock(ITAClock::getDefaultClock()),
  m_pTimer(nullptr),
  m_lSyncModOwner(-1),
  m_lSyncModSpinCount(0),
  m_iState(VA_CORESTATE_CREATED),

  // TODO: Welche Default-Wert mssen erst in Initialize gesetzt werden?
  m_iGlobalAuralizationMode(IVACore::VA_AURAMODE_ALL),
  m_dOutputGain(1), m_dInputGain(1),
  m_bOutputMuted(false), m_bInputMuted(false),
  m_dStreamClockOffset(0), m_fCoreClockOffset(0),

  // --= Profiling =--
  m_pmCoreThreadLoopTotalDuration("Core thread loop")
{
	VA_NO_REENTRANCE;

330
331
332
333
	VA_TRY
	{
		// read configuration
		m_oCoreConfig.Init( oArgs );
Jonas Stienen's avatar
Jonas Stienen committed
334

335
		// register core itself as a module
Jonas Stienen's avatar
Jonas Stienen committed
336
337
338
339
340
341
342
343
344
345
		SetObjectName( "VACore" );
		m_oModules.RegisterObject( this );
		VA_VERBOSE( "VACore", "Registered core module with name '" << GetObjectName() << "'" );

		// Der Event-Manager muss immer verfgbar sein,
		// unabhnging davon ob der Core initialisiert wurde oder nicht.
		m_pCoreEventMan = new CVACoreEventManager;
		
		m_iState = VA_CORESTATE_CREATED;

346
		VA_TRACE( "VACore", "CVACoreImpl instance created [" << this << "]" );
Jonas Stienen's avatar
Jonas Stienen committed
347
348
349
350

	} VA_RETHROW;
}

351
352
CVACoreImpl::~CVACoreImpl()
{
Jonas Stienen's avatar
Jonas Stienen committed
353
354
355
	VA_NO_REENTRANCE;

	// Implizit finalisieren, falls dies nicht durch den Benutzer geschah
356
357
358
359
	if( m_iState == VA_CORESTATE_READY )
	{
		VA_TRY
		{
Jonas Stienen's avatar
Jonas Stienen committed
360
			Finalize();
361
362
363
		}
		VA_FINALLY
		{
Jonas Stienen's avatar
Jonas Stienen committed
364
365
366
367
368
369
370
371
			// Fehler beim Finalisieren ignorieren
		};
	}

	// Nachricht senden [blocking], das die Kerninstanz gelscht wird.
	CVACoreEvent ev;
	ev.iEventType = CVACoreEvent::VA_COREEVENT_DESTROY;
	ev.pSender = this;
372
	m_pCoreEventMan->BroadcastEvent( ev );
Jonas Stienen's avatar
Jonas Stienen committed
373
374
375
376
377

	// Module deregistrieren
	m_oModules.Clear();

	// Nachrichten-Manager freigeben
378
379
	VA_TRY
	{
Jonas Stienen's avatar
Jonas Stienen committed
380
		delete m_pCoreEventMan;
381
382
	}
	VA_RETHROW;
Jonas Stienen's avatar
Jonas Stienen committed
383

384
	VA_TRACE( "Core", "CVACoreImpl instance deleted [" << this << "]" );
Jonas Stienen's avatar
Jonas Stienen committed
385
386

	// Profiling ausgeben
387
	VA_VERBOSE( "Core", m_pmCoreThreadLoopTotalDuration.ToString() );
Jonas Stienen's avatar
Jonas Stienen committed
388
389
390
391
392
393
394
395
396
397
398
399
400
}

void CVACoreImpl::SetDebugStream(std::ostream* posDebug) {
	VALog_setOutputStream(posDebug);
	VALog_setErrorStream(posDebug);
}

void CVACoreImpl::GetVersionInfo(CVACoreVersionInfo* pVersionInfo) const
{
	if( !pVersionInfo )
		return;

	std::stringstream ss;
401
	ss << VACORE_VERSION_MAJOR << "." << VACORE_VERSION_MINOR;
Jonas Stienen's avatar
Jonas Stienen committed
402
	pVersionInfo->sVersion = ss.str();
403
404
405
406
407
408
409
	ss.clear();
#ifdef VACORE_CMAKE_DATE
	ss << VACORE_CMAKE_DATE;
#else
		ss << "Unkown date";
#endif
	pVersionInfo->sDate = ss.str();
Jonas Stienen's avatar
Jonas Stienen committed
410
411
412
	pVersionInfo->sFlags = "";
	
#ifdef DEBUG
413
	pVersionInfo->sComments = "debug";
Jonas Stienen's avatar
Jonas Stienen committed
414
#else
415
	pVersionInfo->sComments = "release";
Jonas Stienen's avatar
Jonas Stienen committed
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
#endif
}

void CVACoreImpl::AttachCoreEventHandler(IVACoreEventHandler* pCoreEventHandler) {
	VA_TRY
	{
		// Immer mglich. Unabhngig vom Zustand. Thread-safety wird im Manager geregelt.
		m_pCoreEventMan->AttachHandler(pCoreEventHandler);
	} VA_RETHROW;
}

void CVACoreImpl::DetachCoreEventHandler(IVACoreEventHandler* pCoreEventHandler) {
	VA_TRY {
		// Immer mglich. Unabhngig vom Zustand. Thread-safety wird im Manager geregelt.
		m_pCoreEventMan->DetachHandler(pCoreEventHandler);
	} VA_RETHROW;
}

int CVACoreImpl::GetState() const {
	return m_iState;
}

void CVACoreImpl::Initialize() {
	VA_NO_REENTRANCE;

	// TODO: Prfen ob im Fehlerfall zurck in den sauberen Grundzustand [WICHTIG!]

443
	VA_VERBOSE("Core", "Initializing core");
Jonas Stienen's avatar
Jonas Stienen committed
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463

	VA_TRY {

		// Zustand berprfen
		if (m_iState == VA_CORESTATE_READY)
			VA_EXCEPT2(MODAL_ERROR, "Core already initialized.");

		if (m_iState == VA_CORESTATE_FAIL)
			VA_EXCEPT2(MODAL_ERROR, "Core corrupted, reinitialization impossible");

		// Hauptthread erzeugen
		m_pCoreThread = new CVACoreThread(this);

		// TODO: Initialize gains?!

		// Audio-Hardware initialisieren
		SetProgress("Setting up audio hardware", "", 1);
		InitializeAudioDriver();

		// Create the intemediate patchbay [temporary]
464
		m_pR2RPatchbay = new ITAStreamPatchbay( m_oCoreConfig.oAudioDriverConfig.dSampleRate, m_oCoreConfig.oAudioDriverConfig.iBuffersize );
Jonas Stienen's avatar
Jonas Stienen committed
465
466

		// Create output patch bay with a single output that uses all available physical audio outputs from sound card
467
		m_pOutputPatchbay = new ITAStreamPatchbay( m_oCoreConfig.oAudioDriverConfig.dSampleRate, m_oCoreConfig.oAudioDriverConfig.iBuffersize );
Jonas Stienen's avatar
Jonas Stienen committed
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
		int iPhysicalHardwareOutput = m_pOutputPatchbay->AddOutput( m_oCoreConfig.oAudioDriverConfig.iOutputChannels );
		m_pOutputPatchbay->SetOutputGain( iPhysicalHardwareOutput, m_dOutputGain );

		// Standardwerte setzen
		m_iGlobalAuralizationMode = VA_AURAMODE_ALL;

		// Eingangs-Streamkette aufbauen
		ITADatasource* pInputTail = nullptr;
		if (m_oCoreConfig.oAudioDriverConfig.iInputChannels > 0) {
			pInputTail = m_pAudioDriverBackend->getInputStreamDatasource();
			if (pInputTail) {
				m_pInputAmp = new ITAStreamAmplifier(pInputTail, (float) m_dInputGain);
				m_pInputPeakDetector = new ITAPeakDetector(m_pInputAmp);
				pInputTail = m_pInputPeakDetector;
			}

			if (!m_oCoreConfig.sDumpDeviceInputFilename.empty()) {
				m_pStreamProbeDeviceInput = new ITAStreamProbe(pInputTail, m_oCoreConfig.sDumpDeviceInputFilename);
				pInputTail = m_pStreamProbeDeviceInput;
			}
		}

		// Interne Manager und Resourcen erzeugen und konfigurieren
		SetProgress("Setting up resource managers", "", 2);

		m_pSignalSourceMan = new CVAAudioSignalSourceManager(this, m_oCoreConfig.oAudioDriverConfig, pInputTail);
494
495
		m_pGlobalSamplePool = ITASoundSamplePool::Create(1, m_oCoreConfig.oAudioDriverConfig.dSampleRate);
		m_pGlobalSampler = ITASoundSampler::Create(1, m_oCoreConfig.oAudioDriverConfig.dSampleRate, m_oCoreConfig.oAudioDriverConfig.iBuffersize, m_pGlobalSamplePool);
Jonas Stienen's avatar
Jonas Stienen committed
496
497
498
499
500
		m_pGlobalSampler->AddMonoTrack();
		
		m_pDirMan = new CVADirectivityManager;
		m_pDirMan->Initialize();

501
		m_pHRIRMan = new CVAHRIRManager(m_oCoreConfig.oAudioDriverConfig.dSampleRate);
Jonas Stienen's avatar
Jonas Stienen committed
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
		m_pHRIRMan->Initialize();

		// Interne Manager und Resourcen erzeugen und konfigurieren
		SetProgress("Setting up scene management", "", 3);

		m_pSceneMan = new CVASceneManager(m_pClock);
		m_pSceneMan->Initialize();
		m_pCurSceneState = m_pSceneMan->GetHeadSceneState();

		// TOOD: Verschnern...
		m_oListenerRealWorldCoords.px = 0;
		m_oListenerRealWorldCoords.py = 0;
		m_oListenerRealWorldCoords.pz = 0;
		m_oListenerRealWorldCoords.vx = 0;
		m_oListenerRealWorldCoords.vy = 0;
		m_oListenerRealWorldCoords.vz = -1;
		m_oListenerRealWorldCoords.ux = 0;
		m_oListenerRealWorldCoords.uy = 1;
		m_oListenerRealWorldCoords.uz = 0;

522
		// Register all renderers and initialize
523
		CVAAudioRendererRegistry::GetInstance()->RegisterInternalCoreFactoryMethods();
Jonas Stienen's avatar
Jonas Stienen committed
524
525
526
527
528
529
		InitializeAudioRenderers();

		if( m_vRenderers.empty() )
			VA_EXCEPT1( "No audio renderers created" );

		SetProgress("Initializing reproduction modules", "", 6);
530

531
532
		// Register all reproductions and initialize
		CVAAudioReproductionModuleRegistry::GetInstance()->RegisterInternalCoreFactoryMethods();
Jonas Stienen's avatar
Jonas Stienen committed
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
		InitializeReproductionModules();

		if( m_vReproductionModules.empty() )
			VA_EXCEPT1( "No audio reproduction modules created" );
		
		// Patch renderer and reproduction modules
		PatchRendererToReproductionModules();

		// Patch audio reproduction to output
		// TODO:
		//SetProgress( "Patching audio modules", "", 7 );
		PatchReproductionModulesToOutput();

		/* Wire the global sampler (1:N)
		int iGlobalSamplerInput = m_pOutputPatchbay->AddInput( m_pGlobalSampler );
		int iNumPhysicalOutputChannels = m_pOutputPatchbay->GetOutputNumChannels( iPhysicalHardwareOutput );
		for( int i=0; i<iNumPhysicalOutputChannels; i++ )
			m_pOutputPatchbay->ConnectChannels( iGlobalSamplerInput, 0, iPhysicalHardwareOutput, i );
		*/

		// Create output peak detector that uses patch bay output stream
		m_pOutputPeakDetector = new ITAPeakDetector( m_pOutputPatchbay->GetOutputDatasource( iPhysicalHardwareOutput ) );
		
		// Setup output dump (if set)
		ITADatasource* pOutputTail = m_pOutputPeakDetector;
		if( !m_oCoreConfig.sDumpFinalOutputFilename.empty() )
		{
			m_pStreamProbeFinal = new ITAStreamProbe( pOutputTail, m_oCoreConfig.sDumpFinalOutputFilename );
			pOutputTail = m_pStreamProbeFinal;
		}

		// Attach the stream tracker
		m_pOutputTracker = new CVAAudiostreamTracker( pOutputTail, m_pClock, &m_fCoreClockOffset, &m_lSyncModOwner, m_pSignalSourceMan );
		pOutputTail = m_pOutputTracker;

		// Give output stream datasource to audio driver
		m_pAudioDriverBackend->setOutputStreamDatasource( pOutputTail );

		// Core-Clock auf 0 initialisieren
		double dNow = m_pClock->getTime();
		m_fCoreClockOffset = (float) dNow;
		m_dStreamClockOffset = -1;

		// Timer erzeugen und konfigurieren (wird fr Peak-Events benutzt)
		m_pTimer = new ITATimer( 0.1f, true );
		m_pTimer->attach( this );

		// Audio-Streaming starten
		SetProgress( "Starting audio streaming", "", 7 );
		m_pAudioDriverBackend->startStreaming();

		// Timer fr Peak-Events starten
		m_pTimer->start();

		// Initialisierung erfolgreich!
		m_iState = VA_CORESTATE_READY;

		SetProgress( "Initialization finished", "", 8 );
		FinishProgress();

	} VA_FINALLY {
		// Aufrumen und Exception weiterwerfen
		Tidyup();
		throw;
	}
}

void CVACoreImpl::Reset()
{
	VA_CHECK_INITIALIZED;

	// Wait for core thread
	while( !m_pCoreThread->TryBreak() )
		VASleep( 20 );

	VA_NO_REENTRANCE;

	if( IsSceneLocked() )
	{
		VA_WARN( "Core", "Encountered locked scene during reset. Please unlock before resetting, skipping." );
		m_pCoreThread->Continue();
	}

	VA_TRY
	{
		VA_INFO( "Core", "Resetting core" );

		// Reset audio renderers
		std::vector< CVAAudioRendererDesc >::iterator it = m_vRenderers.begin();
		while( it != m_vRenderers.end() )
		{
			CVAAudioRendererDesc& oRend( *it++ );
			oRend.pInstance->Reset();
		}
		
		if( m_pCurSceneState )
		{
			// Referenz entfernen welche in CoreThreadLoop hinzugefgt wurde
			m_pCurSceneState->RemoveReference(); 
			m_pCurSceneState = nullptr;
		}

		// Alle Szenenobjekte lschen
		m_pSceneMan->Reset();
		m_pSignalSourceMan->Reset();
		m_pDirMan->Reset();
		m_pHRIRMan->Reset();

		// TODO: Check if the pool and sampler must really be recreated
		/*
		delete m_pGlobalSamplePool;
		m_pGlobalSamplePool = nullptr;
		m_pGlobalSamplePool = ITASoundSamplePool::Create(1, m_oCoreConfig.oAudioDriverConfig.dSamplerate);

		// This causes a crash in patch bay
		delete m_pGlobalSampler;
		m_pGlobalSampler = nullptr;
		m_pGlobalSampler = ITASoundSampler::Create(1, m_oCoreConfig.oAudioDriverConfig.dSamplerate, m_oCoreConfig.oAudioDriverConfig.iBuffersize, m_pGlobalSamplePool);
		m_pGlobalSampler->AddMonoTrack();
		*/
		//m_pGlobalSampler->RemoveAllPlaybacks();

		// Werte neusetzen
		m_pCurSceneState = m_pSceneMan->GetHeadSceneState();
		m_iCurActiveListener = -1;
		m_iNewActiveListener = -1;

		m_pCoreThread;

		// Core-Thread fortsetzen
		m_pCoreThread->Continue();

		// Ereignis generieren, wenn Operation erfolgreich
		CVACoreEvent ev;
		ev.iEventType = CVACoreEvent::VA_COREEVENT_RESET;
		ev.pSender = this;
		m_pCoreEventMan->BroadcastEvent(ev);

	}
	VA_FINALLY
	{
		Tidyup();
		throw;
	}
}

void CVACoreImpl::Tidyup() {
	/*
	 *  Hinweis: Diese Hilfsmethode wird nur innerhalb des Reentrance-Locks 
	 *           aufgerufen - daher keine weiter Absicherung ntig.
	 */
	
	VA_TRY
	{
		if( m_pTimer )
			m_pTimer->stop();

		FinalizeAudioDriver();

		delete m_pTimer;
		m_pTimer = nullptr;

		delete m_pCoreThread;
		m_pCoreThread = nullptr;

		delete m_pInputAmp;
		m_pInputAmp = nullptr;

		delete m_pInputPeakDetector;
		m_pInputPeakDetector = nullptr;

		delete m_pR2RPatchbay;
		m_pR2RPatchbay = nullptr;

		delete m_pOutputPatchbay;
		m_pOutputPatchbay = nullptr;

		delete m_pOutputPeakDetector;
		m_pOutputPeakDetector = nullptr;

		delete m_pOutputTracker;
		m_pOutputTracker = nullptr;
		
		delete m_pStreamProbeDeviceInput;
		m_pStreamProbeDeviceInput = nullptr;

		delete m_pStreamProbeFinal;
		m_pStreamProbeFinal = nullptr;

		delete m_pSignalSourceMan;
		m_pSignalSourceMan = nullptr;

		delete m_pGlobalSampler;
		m_pGlobalSampler = nullptr;

		delete m_pGlobalSamplePool;
		m_pGlobalSamplePool = nullptr;

		if (m_pDirMan) m_pDirMan->Finalize();
		delete m_pDirMan;
		m_pDirMan = nullptr;

		if (m_pHRIRMan) m_pHRIRMan->Finalize();
		delete m_pHRIRMan;
		m_pHRIRMan = nullptr;

		if (m_pSceneMan) m_pSceneMan->Finalize();
		delete m_pSceneMan;
		m_pSceneMan = nullptr;

		m_iState = VA_CORESTATE_CREATED;

	}
	VA_FINALLY
	{
		m_iState = VA_CORESTATE_FAIL;
	}
}

void CVACoreImpl::Finalize() {
	VA_NO_REENTRANCE;

	//VA_TRACE("Core", __FUNCTION__ << " entry");
	VA_INFO("Core", "Finalizing core");

	VA_TRY {
		// Mehrfaches Finialisieren fhrt nicht zu Fehlern
		if (m_iState == VA_CORESTATE_CREATED) return;
	
		if (m_iState == VA_CORESTATE_FAIL)
			VA_EXCEPT2(MODAL_ERROR, "Core corrupted, finalization impossible");

		// Core-Thread anhalten (wenn frei ist)
		while( !m_pCoreThread->TryBreak() )
			VASleep( 10 );
		//m_pCoreThread->Break(); << deadlock

		// Alle Filterketten lschen und warten bis Zustand sicher bernommen
		// Wichtig: Dies muss vor dem Beenden des Streamings geschehen
		
		// Reset audio renderers
		for (std::vector<CVAAudioRendererDesc>::iterator it=m_vRenderers.begin(); it!=m_vRenderers.end(); ++it)
			it->pInstance->Reset();

		// Peak-Nachrichten stoppen
		m_pTimer->stop();

		// Audio-Streaming beenden
		m_pAudioDriverBackend->stopStreaming();

		InitProgress("Stopping auralization threads", "", 2);

		// Timer beenden
		delete m_pTimer;
		m_pTimer = nullptr;

		// Hauptthread beenden und freigeben
		delete m_pCoreThread;
		m_pCoreThread = nullptr;

		SetProgress("Releasing audio hardware", "", 1);
		FinalizeAudioDriver();

		SetProgress("Cleaning up resources", "", 2);
		delete m_pInputAmp;
		m_pInputAmp = nullptr;

		delete m_pInputPeakDetector;
		m_pInputPeakDetector = nullptr;

		m_vReproductionModules.clear();

		delete m_pR2RPatchbay;
		m_pR2RPatchbay = nullptr;

		delete m_pOutputPatchbay;
		m_pOutputPatchbay = nullptr;

		delete m_pOutputPeakDetector;
		m_pOutputPeakDetector = nullptr;

		delete m_pOutputTracker;
		m_pOutputTracker = nullptr;

		delete m_pStreamProbeDeviceInput;
		m_pStreamProbeDeviceInput = nullptr;

		delete m_pStreamProbeFinal;
		m_pStreamProbeFinal = nullptr;

		delete m_pSignalSourceMan;
		m_pSignalSourceMan = nullptr;

		delete m_pGlobalSampler;
		m_pGlobalSampler = nullptr;

		delete m_pGlobalSamplePool;
		m_pGlobalSamplePool = nullptr;

		m_pDirMan->Finalize();
		delete m_pDirMan;
		m_pDirMan = nullptr;

		m_pHRIRMan->Finalize();
		delete m_pHRIRMan;
		m_pHRIRMan = nullptr;

		m_pSceneMan->Finalize();
		delete m_pSceneMan;
		m_pSceneMan = nullptr;

		// Finalisierung erfolgreich. Nun wieder im Grundzustand!
		m_iState = VA_CORESTATE_CREATED;

		FinishProgress();

	} VA_FINALLY {
		// Nochmals versuchen aufzurumen
		Tidyup();

		// Allgemein: Fehler beim Finalisieren? => Core im Sack
		m_iState = VA_CORESTATE_FAIL;

		// VAExceptions unverndert nach aussen leiten
		throw;
	}
}

/* +----------------------------------------------------------+ *
 * |                                                          | *
 * |   Module interface                                       | *
 * |                                                          | *
 * +----------------------------------------------------------+ */

void CVACoreImpl::RegisterModule(CVAObject* pModule)
{
	m_oModules.RegisterObject(pModule);
}


873
874
void CVACoreImpl::EnumerateModules( std::vector<CVAModuleInfo>& viModuleInfos )const
{
Jonas Stienen's avatar
Jonas Stienen committed
875
876
877
	VA_NO_REENTRANCE;
	VA_CHECK_INITIALIZED;

878
#if ( VACORE_MODULE_INTERFACE_ENABLED == 1 )
879
880
	VA_TRY
	{
Jonas Stienen's avatar
Jonas Stienen committed
881
		std::vector<CVAObjectInfo> v;
882
		m_oModules.GetObjectInfos( v );
Jonas Stienen's avatar
Jonas Stienen committed
883

884
		VA_PRINT( "Available modules (" << v.size() << ")" );
Jonas Stienen's avatar
Jonas Stienen committed
885
886
887

		viModuleInfos.clear();
		viModuleInfos.resize( v.size() );
888
889
890
891
892
		for( size_t i = 0; i < v.size(); i++ )
		{
			VA_PRINT( "'" << v[ i ].sName << "'\t\t\t" << v[ i ].sDesc );
			viModuleInfos[ i ].sName = v[ i ].sName;
			viModuleInfos[ i ].sDesc = v[ i ].sDesc;
Jonas Stienen's avatar
Jonas Stienen committed
893
		}
894
895
896
	}
	VA_RETHROW;

897
#else // VACORE_MODULE_INTERFACE_ENABLED
898
899
900
	
	VA_EXCEPT1( "This VACore version does not provide modules" );

901
#endif // VACORE_MODULE_INTERFACE_ENABLED
902

Jonas Stienen's avatar
Jonas Stienen committed
903
904
}

905
906
void CVACoreImpl::CallModule( const std::string& sModuleName, const CVAStruct& oArgs, CVAStruct& oReturn )
{
Jonas Stienen's avatar
Jonas Stienen committed
907
908
909
	VA_NO_REENTRANCE;
	VA_CHECK_INITIALIZED;

910
#if ( VACORE_MODULE_INTERFACE_ENABLED == 1 )
911
912
913

	VA_TRY
	{
Jonas Stienen's avatar
Jonas Stienen committed
914
		CVAObject* pModule = m_oModules.FindObjectByName(sModuleName);
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
		if( !pModule )
			VA_EXCEPT2( INVALID_PARAMETER, "Module not found" );

#ifdef VACORE_MODULE_INTERFACE_MECHANISM_EVENT_BASED

		CVACoreEvent ev;
		ev.iEventType = CVACoreEvent::VA_COREEVENT_SIGNALSOURCE_STATE_CHANGED;
		ev.pSender = this;
		ev.sObjectID = sModuleName;
		ev;
		m_pCoreEventMan->BroadcastEvent( ev );
		m_pCoreEventMan->

#else // not VACORE_MODULE_INTERFACE_MECHANISM_EVENT_BASED

		pModule->CallObject( oArgs, oReturn );

#endif // VACORE_MODULE_INTERFACE_MECHANISM_EVENT_BASED
Jonas Stienen's avatar
Jonas Stienen committed
933
934

	} VA_RETHROW;
935

936
#else // VACORE_MODULE_INTERFACE_ENABLED
937
938
939
940
941
942
943
944
   
#if ( VACORE_NO_MODULE_INTERFACE_THROW_EXCEPTION == 1 )
		VA_EXCEPT1( "This VACore version does not provide modules" );
#else
	// Ignore. No return values.
	oReturn.Clear();
#endif // VACORE_NO_MODULE_INTERFACE_THROW_EXCEPTION

945
#endif // VACORE_MODULE_INTERFACE_ENABLED
Jonas Stienen's avatar
Jonas Stienen committed
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
}

/* +----------------------------------------------------------+ *
 * |                                                          | *
 * |   Richtcharakteristiken (directivities)                  | *
 * |                                                          | *
 * +----------------------------------------------------------+ */

int CVACoreImpl::LoadDirectivity( const std::string& sFilename, const std::string& sName )
{
	VA_NO_REENTRANCE;
	VA_CHECK_INITIALIZED;

	VA_TRY
	{
		std::string sDestFilePath = FindFilePath( sFilename );
		if( sDestFilePath.empty() )
			VA_EXCEPT2( INVALID_PARAMETER, "Looked everywhere, but could not find file '" + sFilename + "'" );

		int iDirID = m_pDirMan->LoadDirectivity( sDestFilePath , sName );

		assert( iDirID != -1 );

		CVACoreEvent ev;
		ev.iEventType = CVACoreEvent::VA_COREEVENT_DIRECTIVITY_LOADED;
		ev.pSender = this;
		ev.iObjectID = iDirID;
		m_pCoreEventMan->BroadcastEvent( ev );

		VA_INFO( "VACore", "Directivity \"" << sDestFilePath << "\" successfully loaded, assigned directivity ID " << iDirID );

		return iDirID;

	} VA_RETHROW;
}

bool CVACoreImpl::FreeDirectivity(int iDirID) {
	VA_NO_REENTRANCE;
	VA_CHECK_INITIALIZED;

	VA_TRY {
		bool bSuccess = m_pDirMan->FreeDirectivity(iDirID);
		//assert( bSuccess );

		// Ereignis generieren, wenn Operation erfolgreich
		CVACoreEvent ev;
		ev.iEventType = CVACoreEvent::VA_COREEVENT_DIRECTIVITY_FREED;
		ev.pSender = this;
		ev.iObjectID = iDirID;
		m_pCoreEventMan->BroadcastEvent(ev);

		VA_INFO("Core", "FreeDirectivity successful, freed directivity " << iDirID);

		return bSuccess;