VAPTGenericPathAudioRenderer.cpp 30.8 KB
Newer Older
Jonas Stienen's avatar
Jonas Stienen committed
1
2
3
4
5
6
// $Id:  $
#include "VAPTGenericPathAudioRenderer.h"

#if( VACORE_RENDERER_PROTOTYPE_GENERIC_PATH == 1 )

// VA includes
7
8
9
10
11
#include "../../../Scene/VAScene.h"
#include "../../../Utils/VAUtils.h"
#include "../../../VALog.h"
#include "../../../VACoreImpl.h"
#include "../../../VACoreConfig.h"
Jonas Stienen's avatar
Jonas Stienen committed
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
#include <VAReferenceableObject.h>

// ITA includes
#include <DSMBCConvolver.h>
#include <DSMBCFilter.h>
#include <DSMBCFilterPool.h>
#include <ITAAtomicPrimitives.h>
#include <ITADatasourceRealization.h>

// Vista includes
#include <VistaInterProcComm/Concurrency/VistaThreadEvent.h>

// STL includes
#include <assert.h>
#include <vector>

// 3rdParty includes
#include <tbb/concurrent_queue.h>

//! Binaural Freefield sound path
class CVAPTGenericSoundPath : public CVAPoolObject
{
public:
	virtual ~CVAPTGenericSoundPath();
	CVAPTGenericPathAudioRenderer::CVAPTGPSource* pSource;
	CVAPTGenericPathAudioRenderer::CVAPTGPListener* pListener;
	ITAAtomicBool bDelete;

	std::vector< DSMBCConvolver* > vpFIRConvolver; // N-channel convolver
	void PreRequest()
	{	
		pSource = nullptr;
		pListener = nullptr;
		for( size_t n=0; n < vpFIRConvolver.size(); n++ )
			vpFIRConvolver[n]->clear();
	};

private:
	CVAPTGenericSoundPath();
	CVAPTGenericSoundPath( double dSamplerate, int iBlocklength, int iNumChannels, int iIRFilterLength );
	
	friend class CVAPTGenericSoundPathFactory;
};

class CVAPTGenericSoundPathFactory : public IVAPoolObjectFactory
{
public: 
	CVAPTGenericSoundPathFactory( double dSampleRate, int iBlockLength, int iNumChannels, int iIRFilterLength )
	: m_dSampleRate( dSampleRate )
	, m_iBlockLength( iBlockLength )
	, m_iNumChannels( iNumChannels )
63
	, m_iIRFilterLengthSamples( iIRFilterLength )
Jonas Stienen's avatar
Jonas Stienen committed
64
65
66
67
	{}

	CVAPoolObject* CreatePoolObject()
	{
68
		return new CVAPTGenericSoundPath( m_dSampleRate, m_iBlockLength, m_iNumChannels, m_iIRFilterLengthSamples );
Jonas Stienen's avatar
Jonas Stienen committed
69
70
71
72
73
	}

private:
	double m_dSampleRate;
	int m_iBlockLength;
74
	int m_iIRFilterLengthSamples;
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
	int m_iNumChannels;
};

class CVAPTGPListenerPoolFactory : public IVAPoolObjectFactory
{
public:
	CVAPTGPListenerPoolFactory( CVACoreImpl* pCore )
	: m_pCore( pCore )
	{
	};

	CVAPoolObject* CreatePoolObject()
	{
		CVAPTGenericPathAudioRenderer::CVAPTGPListener* pListener;
		pListener = new CVAPTGenericPathAudioRenderer::CVAPTGPListener();
		pListener->pCore = m_pCore;
		return pListener;
	};

private:
	CVACoreImpl* m_pCore;
};

class CVAPTGPSourcePoolFactory : public IVAPoolObjectFactory
{
public:
	CVAPTGPSourcePoolFactory()
	{
	};

	CVAPoolObject* CreatePoolObject()
	{
		CVAPTGenericPathAudioRenderer::CVAPTGPSource* pSource;
		pSource = new CVAPTGenericPathAudioRenderer::CVAPTGPSource();
		return pSource;
	};
};


// Class CVAPTGenericSoundPath

CVAPTGenericSoundPath::CVAPTGenericSoundPath( double dSamplerate, int iBlocklength, int iNumChannels, int iIRFilterLength )
{
	if( iNumChannels < 1 )
		ITA_EXCEPT1( INVALID_PARAMETER, "Number of channels must be positive" );

	for( int n=0; n<iNumChannels; n++ )
	{
		DSMBCConvolver* pFIRConvolver = new DSMBCConvolver( iBlocklength, iIRFilterLength );
		pFIRConvolver->setFilterExchangeMode( DSMBCConvolver::CROSSFADE_COSINE_SQUARE );
		pFIRConvolver->setFilterCrossfadeLength( (std::min)( iBlocklength, 32 ) );
		pFIRConvolver->setGain( 1.0f, true );
		DSMBCFilter* pHRIRFilterChL = pFIRConvolver->requestFilter();
		pHRIRFilterChL->zeros();
		pFIRConvolver->exchangeFilter( pHRIRFilterChL );
		pFIRConvolver->releaseFilter( pHRIRFilterChL );

		vpFIRConvolver.push_back( pFIRConvolver );		
	}	
}

CVAPTGenericSoundPath::~CVAPTGenericSoundPath() 
{
	for( size_t n=0; n<vpFIRConvolver.size(); n++ )
		delete vpFIRConvolver[n];
}


// Renderer

CVAPTGenericPathAudioRenderer::CVAPTGenericPathAudioRenderer( const CVAAudioRendererInitParams& oParams )
: CVAObject( oParams.sClass + ":" + oParams.sID )
, m_pCore( oParams.pCore )
, m_pCurSceneState( nullptr )
149
, m_iIRFilterLengthSamples( -1 )
Jonas Stienen's avatar
Jonas Stienen committed
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
, m_iNumChannels( -1 )
, m_oParams( oParams )
{
	// read config
	Init( *oParams.pConfig );
	
	m_pOutput = new ITADatasourceRealization( m_iNumChannels, oParams.pCore->GetCoreConfig()->oAudioDriverConfig.dSamplerate, oParams.pCore->GetCoreConfig()->oAudioDriverConfig.iBuffersize );
	m_pOutput->SetStreamEventHandler( this );

	IVAPoolObjectFactory* pListenerFactory = new CVAPTGPListenerPoolFactory( m_pCore );
	m_pListenerPool = IVAObjectPool::Create( 16, 2, pListenerFactory, true );

	IVAPoolObjectFactory* pSourceFactory = new CVAPTGPSourcePoolFactory();
	m_pSourcePool = IVAObjectPool::Create( 16, 2, pSourceFactory, true );

165
	m_pSoundPathFactory = new CVAPTGenericSoundPathFactory(	m_pOutput->GetSamplerate(), m_pOutput->GetBlocklength(), m_iNumChannels, m_iIRFilterLengthSamples );
Jonas Stienen's avatar
Jonas Stienen committed
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

	m_pSoundPathPool = IVAObjectPool::Create( 64, 8, m_pSoundPathFactory, true );

	m_pUpdateMessagePool = IVAObjectPool::Create( 2, 1, new CVAPoolObjectDefaultFactory< CVAPTGPUpdateMessage >, true );

	ctxAudio.m_iResetFlag = 0; // Normal operation mode
	ctxAudio.m_iStatus = 0; // Stopped

	m_iCurGlobalAuralizationMode = IVACore::VA_AURAMODE_DEFAULT;

	// Register the renderer as a module
	oParams.pCore->RegisterModule( this );
}

CVAPTGenericPathAudioRenderer::~CVAPTGenericPathAudioRenderer() 
{
	delete m_pSoundPathPool;
	delete m_pUpdateMessagePool;
}

void CVAPTGenericPathAudioRenderer::Init( const CVAStruct& oArgs )
{
	CVAConfigInterpreter conf( oArgs );

	conf.ReqInteger( "NumChannels", m_iNumChannels );

192
	conf.OptInteger( "IRFilterLengthSamples", m_iIRFilterLengthSamples, 1024 );
Jonas Stienen's avatar
Jonas Stienen committed
193

194
	conf.OptInteger( "FilterDelaySamples", m_iFilterDelaySamples, 0 );
Jonas Stienen's avatar
Jonas Stienen committed
195

196

197
	if( m_iIRFilterLengthSamples < 0 )
Jonas Stienen's avatar
Jonas Stienen committed
198
199
		ITA_EXCEPT1( INVALID_PARAMETER, "IR filter size must be positive" );

200
201
202
	if( m_iFilterDelaySamples >= m_iIRFilterLengthSamples )
		ITA_EXCEPT1( INVALID_PARAMETER, "IR filter delay samples must be smaller than IR filter length" );

203
204
	conf.OptBool( "OutputMonitoring", m_bOutputMonitoring, false );

Jonas Stienen's avatar
Jonas Stienen committed
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
	return;
}

void CVAPTGenericPathAudioRenderer::Reset() 
{
	ctxAudio.m_iResetFlag = 1; // Request reset

	if( ctxAudio.m_iStatus == 0 )
	{
		// if no streaming active, reset manually
		//SyncInternalData();
		ResetInternalData();
	}

	// Wait for last streaming block before internal reset
	while( ctxAudio.m_iResetFlag != 2 )
	{
		VASleep( 100 ); // Wait for acknowledge
	}
	
	// Iterate over sound pathes and free items
	std::list< CVAPTGenericSoundPath* >::iterator it = m_lSoundPaths.begin();
	while( it != m_lSoundPaths.end() )
	{
		CVAPTGenericSoundPath* pPath = *it;
		
		int iNumRefs = pPath->GetNumReferences();
		assert( iNumRefs == 1 );
		pPath->RemoveReference();

		++it;
	}
	m_lSoundPaths.clear();

	// Iterate over listener and free items
	std::map< int, CVAPTGPListener* >::const_iterator lcit = m_mListeners.begin();
	while( lcit != m_mListeners.end() )
	{
		CVAPTGPListener* pListener( lcit->second );
		pListener->pData->RemoveReference();
		assert( pListener->GetNumReferences() == 1 );
		pListener->RemoveReference();
		lcit++;
	}
	m_mListeners.clear();

	// Iterate over sources and free items
	std::map< int, CVAPTGPSource* >::const_iterator scit = m_mSources.begin();
	while( scit != m_mSources.end() )
	{
		CVAPTGPSource* pSource( scit->second );
		pSource->pData->RemoveReference();
		assert( pSource->GetNumReferences() == 1 );
		pSource->RemoveReference();
		scit++;
	}
	m_mSources.clear();

	// Scene frei geben
	if( m_pCurSceneState )
	{
		m_pCurSceneState->RemoveReference();
		m_pCurSceneState = nullptr;
	}

	ctxAudio.m_iResetFlag = 0; // Enter normal mode
}

void CVAPTGenericPathAudioRenderer::UpdateScene( CVASceneState* pNewSceneState )
{
	assert( pNewSceneState );

	m_pNewSceneState = pNewSceneState;
	if( m_pNewSceneState == m_pCurSceneState )
		return;

	// Neue Szene referenzieren (gegen Freigabe sperren)
	m_pNewSceneState->AddReference();

	// Unterschiede ermitteln: Neue Szene vs. alte Szene
	CVASceneStateDiff oDiff;
	pNewSceneState->Diff( m_pCurSceneState, &oDiff );

	// Leere Update-Nachricht zusammenstellen
	m_pUpdateMessage = dynamic_cast< CVAPTGPUpdateMessage* >( m_pUpdateMessagePool->RequestObject() );

	ManageSoundPaths( m_pCurSceneState, pNewSceneState, &oDiff );

	// Update-Nachricht an den Audiokontext schicken
	ctxAudio.m_qpUpdateMessages.push( m_pUpdateMessage );

	// Alte Szene freigeben (dereferenzieren)
	if( m_pCurSceneState )
		m_pCurSceneState->RemoveReference();

	m_pCurSceneState = m_pNewSceneState;
	m_pNewSceneState = nullptr;
}

ITADatasource* CVAPTGenericPathAudioRenderer::GetOutputDatasource()
{
	return m_pOutput;
}

void CVAPTGenericPathAudioRenderer::ManageSoundPaths( const CVASceneState* pCurScene,
														  const CVASceneState* pNewScene,
														  const CVASceneStateDiff* pDiff )
{
	// Iterate over current paths and mark deleted (will be removed within internal sync of audio context thread)
	std::list< CVAPTGenericSoundPath* >::iterator itp = m_lSoundPaths.begin();
	while( itp != m_lSoundPaths.end() ) 
	{
		CVAPTGenericSoundPath* pPath( *itp );
		int iSourceID = pPath->pSource->pData->iID;
		int iListenerID = pPath->pListener->pData->iID;
		bool bDeletetionRequired = false;

		// Source deleted?
		std::vector< int >::const_iterator cits = pDiff->viDelSoundSourceIDs.begin();
		while( cits != pDiff->viDelSoundSourceIDs.end() )
		{
			const int& iIDDeletedSource( *cits++ );
			if( iSourceID == iIDDeletedSource )
			{
				bDeletetionRequired = true; // Source removed, deletion required
				break;
			}
		}

		if( bDeletetionRequired == false )
		{
			// Receiver deleted?
			std::vector< int >::const_iterator citr = pDiff->viDelListenerIDs.begin();
			while( citr != pDiff->viDelListenerIDs.end() )
			{
				const int& iIDListenerDeleted( *citr++ );
				if( iListenerID == iIDListenerDeleted )
				{
					bDeletetionRequired = true; // Listener removed, deletion required
					break;
				}
			}
		}

		if( bDeletetionRequired )
		{
			DeleteSoundPath( pPath );
			itp = m_lSoundPaths.erase( itp ); // Increment via erase on path list
		}
		else
		{
			++itp; // no deletion detected, continue
		}
	}

	// Deleted sources
	std::vector< int >::const_iterator cits = pDiff->viDelSoundSourceIDs.begin();
	while( cits != pDiff->viDelSoundSourceIDs.end() )
	{
		const int& iID( *cits++ );
		DeleteSource( iID );
	}

	// Deleted receivers
	std::vector< int >::const_iterator citr = pDiff->viDelListenerIDs.begin();
	while( citr != pDiff->viDelListenerIDs.end() )
	{
		const int& iID( *citr++ );
		DeleteListener( iID );
	}

	// New sources
	cits = pDiff->viNewSoundSourceIDs.begin();
	while( cits != pDiff->viNewSoundSourceIDs.end() )
	{
		const int& iID( *cits++ );
		CVAPTGPSource* pSource = CreateSource( iID, pNewScene->GetSoundSourceState( iID ) );
	}

	// New receivers
	citr = pDiff->viNewListenerIDs.begin();
	while( citr != pDiff->viNewListenerIDs.end() )
	{
		const int& iID( *citr++ );
		CVAPTGPListener* pListener = CreateListener( iID, pNewScene->GetListenerState( iID ) );
	}

	// New paths: (1) new receivers, current sources
	citr = pDiff->viNewListenerIDs.begin();
	while( citr != pDiff->viNewListenerIDs.end() )
	{
		int iListenerID = ( *citr++ );
		CVAPTGPListener* pListener = m_mListeners[iListenerID];

		for( size_t i=0; i<pDiff->viComSoundSourceIDs.size(); i++ )
		{
			int iSourceID = pDiff->viComSoundSourceIDs[i];
			CVAPTGPSource* pSource = m_mSources[iSourceID];
			if( !pSource->bDeleted ) // only, if not marked for deletion
				CVAPTGenericSoundPath* pPath = CreateSoundPath( pSource, pListener );
		}
	}

	// New paths: (2) new sources, current receivers
	cits = pDiff->viNewSoundSourceIDs.begin();
	while(  cits != pDiff->viNewSoundSourceIDs.end() )
	{
		const int& iSourceID( *cits++ );
		CVAPTGPSource* pSource = m_mSources[iSourceID];

		for( size_t i=0; i<pDiff->viComListenerIDs.size(); i++ )
		{
			int iListenerID = pDiff->viComListenerIDs[i];
			CVAPTGPListener* pListener = m_mListeners[iListenerID];
			if( !pListener->bDeleted )
				CVAPTGenericSoundPath* pPath = CreateSoundPath( pSource, pListener );
		}
	}

	// New paths: (3) new sources, new receivers
	cits = pDiff->viNewSoundSourceIDs.begin();
	while( cits != pDiff->viNewSoundSourceIDs.end() )
	{
		const int& iSourceID( *cits++ );
		CVAPTGPSource* pSource = m_mSources[iSourceID];

		citr = pDiff->viNewListenerIDs.begin();
		while( citr != pDiff->viNewListenerIDs.end() )
		{
			const int& iListenerID( *citr++ );
			CVAPTGPListener* pListener = m_mListeners[iListenerID];
			CVAPTGenericSoundPath* pPath = CreateSoundPath( pSource, pListener );
		}
	}
	
	return;
}

CVAPTGenericSoundPath* CVAPTGenericPathAudioRenderer::CreateSoundPath( CVAPTGPSource* pSource, CVAPTGPListener* pListener ) 
{
	int iSourceID = pSource->pData->iID;
	int iListenerID = pListener->pData->iID;

	assert( !pSource->bDeleted && !pListener->bDeleted );

	VA_VERBOSE( "CVAPTGenericPathAudioRenderer", "Creating sound path from source " << iSourceID << " -> listener " << iListenerID);

	CVAPTGenericSoundPath* pPath = dynamic_cast<CVAPTGenericSoundPath*>( m_pSoundPathPool->RequestObject() );
	
	pPath->pSource = pSource;
	pPath->pListener = pListener;

	pPath->bDelete = false;

	m_lSoundPaths.push_back( pPath );
	m_pUpdateMessage->vNewPaths.push_back( pPath );

	return pPath;
}

void CVAPTGenericPathAudioRenderer::DeleteSoundPath( CVAPTGenericSoundPath* pPath )
{
	VA_VERBOSE( "CVAPTGenericPathAudioRenderer", "Marking sound path from source " << pPath->pSource->pData->iID << " -> listener " << pPath->pListener->pData->iID << " for deletion");

	pPath->bDelete = true;
	pPath->RemoveReference();
	m_pUpdateMessage->vDelPaths.push_back( pPath );
}

CVAPTGenericPathAudioRenderer::CVAPTGPListener* CVAPTGenericPathAudioRenderer::CreateListener( const int iID, const CVAListenerState* pListenerState )
{
	VA_VERBOSE( "CVAPTGenericPathAudioRenderer", "Creating listener with ID " << iID );

	CVAPTGPListener* pListener = dynamic_cast< CVAPTGPListener* >( m_pListenerPool->RequestObject() ); // Reference = 1

	pListener->pData = m_pCore->GetSceneManager()->GetListenerDesc( iID );
	pListener->pData->AddReference();

	// Move to prerequest of pool?
484
	pListener->psfOutput = new ITASampleFrame( m_iNumChannels,
Jonas Stienen's avatar
Jonas Stienen committed
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
											   m_pCore->GetCoreConfig()->oAudioDriverConfig.iBuffersize,
											   true ); 
	assert( pListener->pData );
	pListener->bDeleted = false;

	m_mListeners.insert( std::pair< int, CVAPTGenericPathAudioRenderer::CVAPTGPListener* >( iID, pListener ) );

	m_pUpdateMessage->vNewListeners.push_back( pListener );

	return pListener;
}

void CVAPTGenericPathAudioRenderer::DeleteListener( int iListenerID )
{
	VA_VERBOSE( "CVAPTGenericPathAudioRenderer", "Marking listener with ID " << iListenerID << " for removal" );
	std::map< int, CVAPTGPListener* >::iterator it = m_mListeners.find( iListenerID );
	CVAPTGPListener* pListener = it->second;
	m_mListeners.erase( it );
	pListener->bDeleted = true;
	pListener->pData->RemoveReference();
	pListener->RemoveReference();

	m_pUpdateMessage->vDelListeners.push_back( pListener );

	return;
}

CVAPTGenericPathAudioRenderer::CVAPTGPSource* CVAPTGenericPathAudioRenderer::CreateSource( int iID, const CVASoundSourceState* pSourceState )
{
	VA_VERBOSE( "CVAPTGenericPathAudioRenderer", "Creating source with ID " << iID );
	CVAPTGPSource* pSource = dynamic_cast< CVAPTGPSource* >( m_pSourcePool->RequestObject() );
	
	pSource->pData = m_pCore->GetSceneManager()->GetSoundSourceDesc(iID);
	pSource->pData->AddReference();

	pSource->bDeleted = false;

	m_mSources.insert( std::pair< int, CVAPTGPSource* >( iID, pSource ) );

	m_pUpdateMessage->vNewSources.push_back( pSource );

	return pSource;
}

void CVAPTGenericPathAudioRenderer::DeleteSource( int iSourceID )
{
	VA_VERBOSE( "CVAPTGenericPathAudioRenderer", "Marking source with ID " << iSourceID << " for removal" );
	std::map< int, CVAPTGPSource* >::iterator it = m_mSources.find( iSourceID );
	CVAPTGPSource* pSource = it->second;
	m_mSources.erase( it );
	pSource->bDeleted = true;
	pSource->pData->RemoveReference();
	pSource->RemoveReference();

	m_pUpdateMessage->vDelSources.push_back( pSource );
		
	return;
}

void CVAPTGenericPathAudioRenderer::SyncInternalData()
{
	CVAPTGPUpdateMessage* pUpdate;
	while( ctxAudio.m_qpUpdateMessages.try_pop( pUpdate ) )
	{
		std::list< CVAPTGenericSoundPath* >::const_iterator citp = pUpdate->vDelPaths.begin();
		while( citp != pUpdate->vDelPaths.end() )
		{
			CVAPTGenericSoundPath* pPath( *citp++ );
			ctxAudio.m_lSoundPaths.remove( pPath );
			pPath->RemoveReference();
		}

		citp = pUpdate->vNewPaths.begin();
		while( citp != pUpdate->vNewPaths.end() )
		{
			CVAPTGenericSoundPath* pPath( *citp++ );
			pPath->AddReference();
			ctxAudio.m_lSoundPaths.push_back( pPath );
		}

		std::list< CVAPTGPSource* >::const_iterator cits = pUpdate->vDelSources.begin();
		while( cits != pUpdate->vDelSources.end() )
		{
			CVAPTGPSource* pSource( *cits++ );
			ctxAudio.m_lSources.remove( pSource );
			pSource->pData->RemoveReference();
			pSource->RemoveReference();
		}

		cits = pUpdate->vNewSources.begin();
		while( cits != pUpdate->vNewSources.end() )
		{
			CVAPTGPSource* pSource( *cits++ );
			pSource->AddReference();
			pSource->pData->AddReference();
			ctxAudio.m_lSources.push_back( pSource );
		}

		std::list< CVAPTGPListener* >::const_iterator citl = pUpdate->vDelListeners.begin();
		while( citl != pUpdate->vDelListeners.end() )
		{
			CVAPTGPListener* pListener( *citl++ );
			ctxAudio.m_lListener.remove( pListener );
			pListener->pData->RemoveReference();
			pListener->RemoveReference();
		}

		citl = pUpdate->vNewListeners.begin();
		while( citl != pUpdate->vNewListeners.end() )
		{
			CVAPTGPListener* pListener( *citl++ );
			pListener->AddReference();
			pListener->pData->AddReference();
			ctxAudio.m_lListener.push_back( pListener );
		}

		pUpdate->RemoveReference();
	}

	return;
}

void CVAPTGenericPathAudioRenderer::ResetInternalData()
{
	std::list< CVAPTGenericSoundPath* >::const_iterator citp = ctxAudio.m_lSoundPaths.begin();
	while( citp != ctxAudio.m_lSoundPaths.end()  )
	{
		CVAPTGenericSoundPath* pPath( *citp++ );
		pPath->RemoveReference();
	}
	ctxAudio.m_lSoundPaths.clear();

	std::list< CVAPTGPListener* >::const_iterator itl=ctxAudio.m_lListener.begin();
	while( itl !=ctxAudio.m_lListener.end() )
	{
		CVAPTGPListener* pListener( *itl++ );
		pListener->pData->RemoveReference();
		pListener->RemoveReference();
	}
	ctxAudio.m_lListener.clear();

	std::list< CVAPTGPSource* >::const_iterator cits = ctxAudio.m_lSources.begin();
	while( cits != ctxAudio.m_lSources.end() )
	{
		CVAPTGPSource* pSource( *cits++ );
		pSource->pData->RemoveReference();
		pSource->RemoveReference();
	}
	ctxAudio.m_lSources.clear();

	ctxAudio.m_iResetFlag = 2; // set ack
}

void CVAPTGenericPathAudioRenderer::UpdateGenericSoundPath( int iListenerID, int iSourceID, const std::string& sIRFilePath )
{
	ITASampleFrame sfIR( sIRFilePath );
	if( sfIR.channels() != m_pOutput->GetNumberOfChannels() )
		ITA_EXCEPT1( INVALID_PARAMETER, "Filter has mismatching channels" );
	UpdateGenericSoundPath( iListenerID, iSourceID, sfIR );
}

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
void CVAPTGenericPathAudioRenderer::UpdateGenericSoundPath( int iListenerID, int iSourceID, int iChannelIndex, const std::string& sIRFilePath )
{
	if( iChannelIndex >= m_iNumChannels || iChannelIndex < 0 )
		ITA_EXCEPT1( INVALID_PARAMETER, "Requested filter channel greater than output channels or smaller than 1, can not update." );

	ITASampleFrame sfIR( sIRFilePath );
	if( sfIR.channels() != 1 )
	{
		if( sfIR.channels() != m_iNumChannels )
		{
			VA_ERROR( "CVAPTGenericPathAudioRenderer", "Filter has mismatching and more than one channel. Don't know what to do - refusing this update." );
		}
		else
		{
			VA_WARN( "CVAPTGenericPathAudioRenderer", "Filter has more than one channel, updating only requested channel index." );
			UpdateGenericSoundPath( iListenerID, iSourceID, iChannelIndex, sfIR[ iChannelIndex ] );
		}
	}
	else
	{
		UpdateGenericSoundPath( iListenerID, iSourceID, iChannelIndex, sfIR[ 0 ] );
	}

}

Jonas Stienen's avatar
Jonas Stienen committed
671
672
void CVAPTGenericPathAudioRenderer::UpdateGenericSoundPath( int iListenerID, int iSourceID, ITASampleFrame& sfIR )
{
673
	if( sfIR.length() > m_iIRFilterLengthSamples )
Jonas Stienen's avatar
Jonas Stienen committed
674
675
		VA_WARN( "CVAPTGenericPathAudioRenderer", "Filter length for generic sound path too long, cropping." );

676
677
	if( m_iFilterDelaySamples != 0 )
		sfIR.CyclicShift( m_iFilterDelaySamples );
Jonas Stienen's avatar
Jonas Stienen committed
678
679
680
681
682
683
684
685
686
687
688
689

	std::list< CVAPTGenericSoundPath* >::const_iterator spcit = m_lSoundPaths.begin();
	while( spcit != m_lSoundPaths.end() )
	{
		CVAPTGenericSoundPath* pPath( *spcit++ );
		if( pPath->pListener->pData->iID == iListenerID && pPath->pSource->pData->iID == iSourceID )
		{
			for( int n=0; n<m_iNumChannels; n++ )
			{
				DSMBCConvolver* pConvolver( pPath->vpFIRConvolver[n] );
				DSMBCFilter* pFilter = pConvolver->requestFilter();
				pFilter->zeros();
690
				int iLength = (std::min)( m_iIRFilterLengthSamples, sfIR.length() );
Jonas Stienen's avatar
Jonas Stienen committed
691
				pFilter->load( sfIR[n].data(), iLength );
692
				
Jonas Stienen's avatar
Jonas Stienen committed
693
694
695
696
697
698
699
700
701
702
703
				pConvolver->exchangeFilter( pFilter );
				pFilter->release();
			}
			return;
		}
	}

	VA_ERROR( "CVAPTGenericPathAudioRenderer", "Could not find sound path with given listener and source ID" );
}


704
void CVAPTGenericPathAudioRenderer::UpdateGenericSoundPath( int iListenerID, int iSourceID, int iChannelIndex, ITASampleBuffer& sbIR )
Jonas Stienen's avatar
Jonas Stienen committed
705
{
706
	if( iChannelIndex >= m_iNumChannels  || iChannelIndex < 0 )
Jonas Stienen's avatar
Jonas Stienen committed
707
708
		VA_EXCEPT2( INVALID_PARAMETER, "Requested filter channel index of generic sound path out of bounds" );

709
	if( sbIR.length() > m_iIRFilterLengthSamples )
Jonas Stienen's avatar
Jonas Stienen committed
710
711
		VA_WARN( "CVAPTGenericPathAudioRenderer", "Filter length for generic sound path channel too long, cropping." );

712
713
	if( m_iFilterDelaySamples != 0 ) 
		sbIR.CyclicShift( m_iFilterDelaySamples );
Jonas Stienen's avatar
Jonas Stienen committed
714
715
716
717
718
719
720
	
	std::list< CVAPTGenericSoundPath* >::const_iterator spcit = m_lSoundPaths.begin();
	while( spcit != m_lSoundPaths.end() )
	{
		CVAPTGenericSoundPath* pPath( *spcit++ );
		if( pPath->pListener->pData->iID == iListenerID && pPath->pSource->pData->iID == iSourceID )
		{
721
			DSMBCConvolver* pConvolver( pPath->vpFIRConvolver[iChannelIndex] );
Jonas Stienen's avatar
Jonas Stienen committed
722
723
			DSMBCFilter* pFilter = pConvolver->requestFilter();
			pFilter->zeros();
724
			int iLength = (std::min)( m_iIRFilterLengthSamples, sbIR.length() );
Jonas Stienen's avatar
Jonas Stienen committed
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
			pFilter->load( sbIR.data(), iLength );
			pConvolver->exchangeFilter( pFilter );
			pFilter->release();

			return;
		}
	}

	VA_ERROR( "CVAPTGenericPathAudioRenderer", "Could not find sound path with given listener and source ID" );
}

void CVAPTGenericPathAudioRenderer::UpdateGlobalAuralizationMode( int )
{
	return;
}

void CVAPTGenericPathAudioRenderer::HandleProcessStream( ITADatasourceRealization*, const ITAStreamInfo* pStreamInfo )
{
	// If streaming is active, set to 1
	ctxAudio.m_iStatus = 1;

	// Sync pathes
	SyncInternalData();
	
	const CVAAudiostreamState* pStreamState = dynamic_cast< const CVAAudiostreamState* >( pStreamInfo );
	double dListenerTime = pStreamState->dSysTime;
	
	// Check for reset request
	if( ctxAudio.m_iResetFlag == 1 )
	{
		ResetInternalData();

		return;
	}
	else if( ctxAudio.m_iResetFlag == 2 )
	{
		// Reset active, skip until finished
		return;
	}
	
	std::map< int, CVAPTGPListener* >::iterator lit = m_mListeners.begin();
	while( lit != m_mListeners.end() )
	{
		CVAPTGPListener* pListener( lit->second );
		pListener->psfOutput->zero();
		lit++;
	}

	// Update sound pathes
	std::list< CVAPTGenericSoundPath* >::iterator spit = ctxAudio.m_lSoundPaths.begin();
	while( spit != ctxAudio.m_lSoundPaths.end() )
	{
		CVAPTGenericSoundPath* pPath( *spit );
		CVAListenerState* pListenerState = ( m_pCurSceneState ? m_pCurSceneState->GetListenerState( pPath->pListener->pData->iID ) : NULL );
        CVASoundSourceState* pSourceState = ( m_pCurSceneState ? m_pCurSceneState->GetSoundSourceState( pPath->pSource->pData->iID ) : NULL );

		if( pListenerState == nullptr || pSourceState == nullptr )
		{
			// Skip if no data is present
			spit++;
			continue;
		}

		CVASoundSourceDesc* pSourceData = pPath->pSource->pData;
		ITASampleBuffer* psbInput = pSourceData->pSignalSourceInputBuf;

791
		float fSoundSourceGain = float( pSourceState->GetVolume() );
Jonas Stienen's avatar
Jonas Stienen committed
792
793
794
795
		
		for( int n=0; n < m_iNumChannels; n++ )
		{
			DSMBCConvolver* pConvolver = pPath->vpFIRConvolver[n];
796
			pConvolver->setGain( fSoundSourceGain );
Jonas Stienen's avatar
Jonas Stienen committed
797
798
799
800
801
802
803
804
805
806
807
808
			pConvolver->process( psbInput->data(), ( *pPath->pListener->psfOutput )[n].data(), DSMBCConvolver::OUTPUT_MIX );
		}

		spit++;
	}

	// TODO: Select active listener
	if( !m_mListeners.empty() )
	{
		CVAPTGPListener* pActiveListener = m_mListeners.begin()->second;
		for( int n=0; n< int( m_pOutput->GetNumberOfChannels() ); n++ )
			for( int i=0; i<int( m_pOutput->GetBlocklength() ); i++ )
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
				m_pOutput->GetWritePointer( n )[ i ] = ( *pActiveListener->psfOutput )[ n ][ i ];

		bool bDataPresent = false;
		std::vector< float > vfRMS( m_iNumChannels );
		for( int n = 0; n< int( m_pOutput->GetNumberOfChannels() ); n++ )
		{
			vfRMS[ n ] = 0.0f;
			for( int i = 0; i<int( m_pOutput->GetBlocklength() ); i++ )
				vfRMS[ n ] += pow( std::abs( m_pOutput->GetWritePointer( n )[ i ] ), 2 );
			vfRMS[ n ] = std::sqrtf( vfRMS[ n ] ) / m_pOutput->GetBlocklength();
			if( vfRMS[ n ] != 0.0f )
				bDataPresent = true;
		}

		if( m_bOutputMonitoring && int( pStreamInfo->nSamples / m_pOutput->GetBlocklength() ) % int( m_pOutput->GetSamplerate() / m_pOutput->GetBlocklength() * 2.0f ) == 0 )
		{
			if( bDataPresent )
			{
				VA_TRACE( GetObjectName(), "RMS at active listener: <Ch1," << vfRMS[ 0 ] << "> <Ch2," << vfRMS[ 1 ] << "> " );
			}
			else
			{
				VA_WARN( GetObjectName(), "Not data on output channel for active listener present (empty filters?)" );
			}
		}
Jonas Stienen's avatar
Jonas Stienen committed
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
	}
	else
	{
		for( int n=0; n< int( m_pOutput->GetNumberOfChannels() ); n++ )
			for( int i=0; i<int( m_pOutput->GetBlocklength() ); i++ )
				m_pOutput->GetWritePointer( n )[i] = 0.0f;
	}

	m_pOutput->IncrementWritePointer();

	return;
}

std::string CVAPTGenericPathAudioRenderer::HelpText() const
{
	std::stringstream ss;
	ss << std::endl;
	ss << " --- GenericPath renderer instance '" << GetObjectName() << "' ---" << std::endl;
	ss << std::endl;
	ss << "[help]" << std::endl;
	ss << "If the call module struct contains a key with the name 'help', this help text will be shown and the return struct will be returned with the key name 'help'." << std::endl;
	ss << std::endl;
	ss << "[info]" << std::endl;
	ss << "If the call module struct contains a key with the name 'info', information on the static configuration of the renderer will be returned." << std::endl;
	ss << std::endl;
	ss << "[update]" << std::endl;
	ss << "For every successful path update, the VA source and listener ID has to be passed like this:" << std::endl;
	ss << " listener: <int>, the number of the listener identifier" << std::endl;
	ss << " source: <int>, the number of the source identifier" << std::endl;
	ss << std::endl;
	ss << "Updating the path filter (impulse response in time domain) for a listener and a source can be performed in two ways:" << std::endl;
	ss << " a) using a path to a multi-channel WAV file:" << std::endl;
	ss << "    Provide a key with the name 'filepath' and the path to the WAV file (absolute or containing the macro '$(VADataDir)' or relative to the executable) [priority given to 'filepath' if b) also applies]" << std::endl;
	ss << " b) sending floating-point data for each channel" << std::endl;
	ss << "    Provide a key for each channel with the generic name 'ch#', where the hash is substituted by the actual number of channel (starting at 1), and the value to this key will contain floating point data (or a sample buffer). " <<
		  "The call parameter struct does not necessarily have to contain all channels, also single channels will be updated if key is given." << std::endl;
	ss << std::endl;
	ss << "Note: the existence of the key 'verbose' will print update information at server console and will provide the update info as an 'info' key in the returned struct." << std::endl;
	return ss.str();
}

int CVAPTGenericPathAudioRenderer::CallObject( const CVAStruct& oArgs, CVAStruct& oReturn )
{
	oReturn.Clear();

	if( oArgs.HasKey( "help" ) )
	{
		// Print and return help text
		VA_PRINT( HelpText() );
		oReturn["help"] = HelpText();
		return 1;
	}
	else if( oArgs.HasKey( "info" ) )
	{
888
889
890
891
		oReturn[ "numchannels" ] = m_iNumChannels;
		oReturn[ "irfilterlengthsamples" ] = m_iIRFilterLengthSamples;
		oReturn[ "numpaths" ] = int( m_lSoundPaths.size() );
		oReturn[ "filterdelaysamples" ] = m_iFilterDelaySamples;
Jonas Stienen's avatar
Jonas Stienen committed
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
		return 1;
	}
	else
	{
		// Update
		if( oArgs.HasKey( "listener" ) == false || oArgs.HasKey( "source" ) == false )
			VA_EXCEPT2( INVALID_PARAMETER, "GenericPath filter update requires a ListenerID and a SourceID" );

		int iListenerID = oArgs["listener"];
		int iSourceID = oArgs["source"];

		bool bVerbose = false;
		if( oArgs.HasKey( "verbose" ) )
			bVerbose = true;

		if( oArgs.HasKey( "filepath" ) )
		{
			const std::string& sFilePathRaw( oArgs[ "filepath" ] );
910
911
912
913
914
915
916
917
918
919
920
921
			std::string sFilePath = m_pCore->FindFilePath( sFilePathRaw );

			if( oArgs.HasKey( "channel" ) )
			{
				int iChannelNumber = oArgs[ "channel" ];
				UpdateGenericSoundPath( iListenerID, iSourceID, iChannelNumber - 1, sFilePath );
			}
			else
			{
				UpdateGenericSoundPath( iListenerID, iSourceID, sFilePath );

			}
Jonas Stienen's avatar
Jonas Stienen committed
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936

			std::stringstream ssVerboseText;
			if( bVerbose )
			{
				ssVerboseText << "Updated sound path <L" << iListenerID << ", S" << iSourceID << "> using (unrolled) file path '" << sFilePath << "'";
				VA_PRINT( ssVerboseText.str() );
				oReturn["info"] = ssVerboseText.str();

				return 1;
			}

			return 0;
		}
		else
		{
937
			ITASampleBuffer sbIR( m_iIRFilterLengthSamples );
Jonas Stienen's avatar
Jonas Stienen committed
938
939
940
941
942
943
944
945
946
947
948
949
950
951
			for( int n=0; n < int( m_pOutput->GetNumberOfChannels() ); n++ )
			{
				std::string sChKey = "ch" + IntToString( n + 1 );
				if( !oArgs.HasKey( sChKey ) )
					continue;
				
				const CVAStructValue& oValue( oArgs[sChKey] );
				int iNumSamples = 0;

				if( oValue.GetDatatype() == CVAStructValue::DATA )
				{
					int iBytes = oValue.GetDataSize();
					iNumSamples = iBytes / int( sizeof( float ) ); // crop overlapping bytes for safety (by integer division)

952
					if( iNumSamples > m_iIRFilterLengthSamples )
Jonas Stienen's avatar
Jonas Stienen committed
953
954
					{
						VA_WARN( "VAPTGenericPathAudioRenderer", "Given IR filter too long, cropping to fit internal filter length." );
955
						iNumSamples = m_iIRFilterLengthSamples;
Jonas Stienen's avatar
Jonas Stienen committed
956
957
958
					}

					const float* pfData = (const float*)( oValue.GetData() );
959
					sbIR.Zero();
Jonas Stienen's avatar
Jonas Stienen committed
960
961
962
963
964
965
966
967
					sbIR.write( pfData, iNumSamples );
				}
				else if( oValue.GetDatatype() == CVAStructValue::SAMPLEBUFFER )
				{
					const CVASampleBuffer& oSampleBuffer = oValue;

					iNumSamples = oSampleBuffer.GetNumSamples(); // crop overlapping bytes for safety (by integer division)

968
					if( iNumSamples > m_iIRFilterLengthSamples )
Jonas Stienen's avatar
Jonas Stienen committed
969
970
					{
						VA_WARN( "VAPTGenericPathAudioRenderer", "Given IR filter too long, cropping to fit internal filter length." );
971
						iNumSamples = m_iIRFilterLengthSamples;
Jonas Stienen's avatar
Jonas Stienen committed
972
973
					}

974
					sbIR.Zero();
Jonas Stienen's avatar
Jonas Stienen committed
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
1001
1002
					sbIR.write( oSampleBuffer.GetDataReadOnly(), iNumSamples );
				}

				UpdateGenericSoundPath( iListenerID, iSourceID, n, sbIR );

				std::stringstream ssVerboseText;
				if( bVerbose )
				{
					ssVerboseText << "Updated sound path <L" << iListenerID << ", S" << iSourceID << ", C" << n+1 << "> with " << iNumSamples << " new samples";
					VA_PRINT( ssVerboseText.str() );
					std::string sInfoKey = "info_"+sChKey;
					oReturn[sInfoKey] = ssVerboseText.str();
				}
			}

			if( bVerbose )
				return 1;

			return 0;
		}

		VA_EXCEPT2( INVALID_PARAMETER, "Invalid object call in module " + GetObjectName() );
		return -1;
	}
}

#endif // ( VACORE_RENDERER_PROTOTYPE_GENERIC_PATH == 1 )