GigPlayer.cpp 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399
  1. /*
  2. * GigPlayer.cpp - a GIG player using libgig (based on Sf2 player plugin)
  3. *
  4. * Copyright (c) 2008 Paul Giblock <drfaygo/at/gmail/dot/com>
  5. * Copyright (c) 2009-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
  6. *
  7. * A few lines of code taken from LinuxSampler (also GPLv2) where noted:
  8. * Copyright (C) 2003,2004 by Benno Senoner and Christian Schoenebeck
  9. * Copyright (C) 2005-2008 Christian Schoenebeck
  10. * Copyright (C) 2009-2010 Christian Schoenebeck and Grigor Iliev
  11. *
  12. * This file is part of LMMS - https://lmms.io
  13. *
  14. * This program is free software; you can redistribute it and/or
  15. * modify it under the terms of the GNU General Public
  16. * License as published by the Free Software Foundation; either
  17. * version 2 of the License, or (at your option) any later version.
  18. *
  19. * This program is distributed in the hope that it will be useful,
  20. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  21. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  22. * General Public License for more details.
  23. *
  24. * You should have received a copy of the GNU General Public
  25. * License along with this program (see COPYING); if not, write to the
  26. * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
  27. * Boston, MA 02110-1301 USA.
  28. *
  29. */
  30. #include <cstring>
  31. #include <QDebug>
  32. #include <QLayout>
  33. #include <QLabel>
  34. #include <QDomDocument>
  35. #include "FileDialog.h"
  36. #include "GigPlayer.h"
  37. #include "Engine.h"
  38. #include "InstrumentTrack.h"
  39. #include "InstrumentPlayHandle.h"
  40. #include "Mixer.h"
  41. #include "NotePlayHandle.h"
  42. #include "Knob.h"
  43. #include "SampleBuffer.h"
  44. #include "Song.h"
  45. #include "ConfigManager.h"
  46. #include "endian_handling.h"
  47. #include "PatchesDialog.h"
  48. #include "ToolTip.h"
  49. #include "LcdSpinBox.h"
  50. #include "embed.h"
  51. #include "plugin_export.h"
  52. extern "C"
  53. {
  54. Plugin::Descriptor PLUGIN_EXPORT gigplayer_plugin_descriptor =
  55. {
  56. STRINGIFY( PLUGIN_NAME ),
  57. "GIG Player",
  58. QT_TRANSLATE_NOOP( "pluginBrowser", "Player for GIG files" ),
  59. "Garrett Wilson <g/at/floft/dot/net>",
  60. 0x0100,
  61. Plugin::Instrument,
  62. new PluginPixmapLoader( "logo" ),
  63. "gig",
  64. NULL
  65. } ;
  66. }
  67. GigInstrument::GigInstrument( InstrumentTrack * _instrument_track ) :
  68. Instrument( _instrument_track, &gigplayer_plugin_descriptor ),
  69. m_instance( NULL ),
  70. m_instrument( NULL ),
  71. m_filename( "" ),
  72. m_bankNum( 0, 0, 999, this, tr( "Bank" ) ),
  73. m_patchNum( 0, 0, 127, this, tr( "Patch" ) ),
  74. m_gain( 1.0f, 0.0f, 5.0f, 0.01f, this, tr( "Gain" ) ),
  75. m_interpolation( SRC_LINEAR ),
  76. m_RandomSeed( 0 ),
  77. m_currentKeyDimension( 0 )
  78. {
  79. InstrumentPlayHandle * iph = new InstrumentPlayHandle( this, _instrument_track );
  80. Engine::mixer()->addPlayHandle( iph );
  81. updateSampleRate();
  82. connect( &m_bankNum, SIGNAL( dataChanged() ), this, SLOT( updatePatch() ) );
  83. connect( &m_patchNum, SIGNAL( dataChanged() ), this, SLOT( updatePatch() ) );
  84. connect( Engine::mixer(), SIGNAL( sampleRateChanged() ), this, SLOT( updateSampleRate() ) );
  85. }
  86. GigInstrument::~GigInstrument()
  87. {
  88. Engine::mixer()->removePlayHandlesOfTypes( instrumentTrack(),
  89. PlayHandle::TypeNotePlayHandle
  90. | PlayHandle::TypeInstrumentPlayHandle );
  91. freeInstance();
  92. }
  93. void GigInstrument::saveSettings( QDomDocument & _doc, QDomElement & _this )
  94. {
  95. _this.setAttribute( "src", m_filename );
  96. m_patchNum.saveSettings( _doc, _this, "patch" );
  97. m_bankNum.saveSettings( _doc, _this, "bank" );
  98. m_gain.saveSettings( _doc, _this, "gain" );
  99. }
  100. void GigInstrument::loadSettings( const QDomElement & _this )
  101. {
  102. openFile( _this.attribute( "src" ), false );
  103. m_patchNum.loadSettings( _this, "patch" );
  104. m_bankNum.loadSettings( _this, "bank" );
  105. m_gain.loadSettings( _this, "gain" );
  106. updatePatch();
  107. }
  108. void GigInstrument::loadFile( const QString & _file )
  109. {
  110. if( !_file.isEmpty() && QFileInfo( _file ).exists() )
  111. {
  112. openFile( _file, false );
  113. updatePatch();
  114. updateSampleRate();
  115. }
  116. }
  117. AutomatableModel * GigInstrument::childModel( const QString & _modelName )
  118. {
  119. if( _modelName == "bank" )
  120. {
  121. return &m_bankNum;
  122. }
  123. else if( _modelName == "patch" )
  124. {
  125. return &m_patchNum;
  126. }
  127. qCritical() << "requested unknown model " << _modelName;
  128. return NULL;
  129. }
  130. QString GigInstrument::nodeName() const
  131. {
  132. return gigplayer_plugin_descriptor.name;
  133. }
  134. void GigInstrument::freeInstance()
  135. {
  136. QMutexLocker synthLock( &m_synthMutex );
  137. QMutexLocker notesLock( &m_notesMutex );
  138. if( m_instance != NULL )
  139. {
  140. delete m_instance;
  141. m_instance = NULL;
  142. // If we're changing instruments, we got to make sure that we
  143. // remove all pointers to the old samples and don't try accessing
  144. // that instrument again
  145. m_instrument = NULL;
  146. m_notes.clear();
  147. }
  148. }
  149. void GigInstrument::openFile( const QString & _gigFile, bool updateTrackName )
  150. {
  151. emit fileLoading();
  152. // Remove the current instrument if one is selected
  153. freeInstance();
  154. {
  155. QMutexLocker locker( &m_synthMutex );
  156. try
  157. {
  158. m_instance = new GigInstance( SampleBuffer::tryToMakeAbsolute( _gigFile ) );
  159. m_filename = SampleBuffer::tryToMakeRelative( _gigFile );
  160. }
  161. catch( ... )
  162. {
  163. m_instance = NULL;
  164. m_filename = "";
  165. }
  166. }
  167. emit fileChanged();
  168. if( updateTrackName == true )
  169. {
  170. instrumentTrack()->setName( QFileInfo( _gigFile ).baseName() );
  171. updatePatch();
  172. }
  173. }
  174. void GigInstrument::updatePatch()
  175. {
  176. if( m_bankNum.value() >= 0 && m_patchNum.value() >= 0 )
  177. {
  178. getInstrument();
  179. }
  180. }
  181. QString GigInstrument::getCurrentPatchName()
  182. {
  183. QMutexLocker locker( &m_synthMutex );
  184. if( m_instance == NULL )
  185. {
  186. return "";
  187. }
  188. int iBankSelected = m_bankNum.value();
  189. int iProgSelected = m_patchNum.value();
  190. gig::Instrument * pInstrument = m_instance->gig.GetFirstInstrument();
  191. while( pInstrument != NULL )
  192. {
  193. int iBank = pInstrument->MIDIBank;
  194. int iProg = pInstrument->MIDIProgram;
  195. if( iBank == iBankSelected && iProg == iProgSelected )
  196. {
  197. QString name = QString::fromStdString( pInstrument->pInfo->Name );
  198. if( name == "" )
  199. {
  200. name = "<no name>";
  201. }
  202. return name;
  203. }
  204. pInstrument = m_instance->gig.GetNextInstrument();
  205. }
  206. return "";
  207. }
  208. // A key has been pressed
  209. void GigInstrument::playNote( NotePlayHandle * _n, sampleFrame * )
  210. {
  211. const float LOG440 = 2.643452676f;
  212. const f_cnt_t tfp = _n->totalFramesPlayed();
  213. int midiNote = (int) floor( 12.0 * ( log2( _n->unpitchedFrequency() ) - LOG440 ) - 4.0 );
  214. // out of range?
  215. if( midiNote <= 0 || midiNote >= 128 )
  216. {
  217. return;
  218. }
  219. if( tfp == 0 )
  220. {
  221. GIGPluginData * pluginData = new GIGPluginData;
  222. pluginData->midiNote = midiNote;
  223. _n->m_pluginData = pluginData;
  224. const int baseVelocity = instrumentTrack()->midiPort()->baseVelocity();
  225. const uint velocity = _n->midiVelocity( baseVelocity );
  226. QMutexLocker locker( &m_notesMutex );
  227. m_notes.push_back( GigNote( midiNote, velocity, _n->unpitchedFrequency(), pluginData ) );
  228. }
  229. }
  230. // Process the notes and output a certain number of frames (e.g. 256, set in
  231. // the preferences)
  232. void GigInstrument::play( sampleFrame * _working_buffer )
  233. {
  234. const fpp_t frames = Engine::mixer()->framesPerPeriod();
  235. const int rate = Engine::mixer()->processingSampleRate();
  236. // Initialize to zeros
  237. std::memset( &_working_buffer[0][0], 0, DEFAULT_CHANNELS * frames * sizeof( float ) );
  238. m_synthMutex.lock();
  239. m_notesMutex.lock();
  240. if( m_instance == NULL || m_instrument == NULL )
  241. {
  242. m_synthMutex.unlock();
  243. m_notesMutex.unlock();
  244. return;
  245. }
  246. for( QList<GigNote>::iterator it = m_notes.begin(); it != m_notes.end(); ++it )
  247. {
  248. // Process notes in the KeyUp state, adding release samples if desired
  249. if( it->state == KeyUp )
  250. {
  251. // If there are no samples, we're done
  252. if( it->samples.empty() )
  253. {
  254. it->state = Completed;
  255. }
  256. else
  257. {
  258. it->state = PlayingKeyUp;
  259. // Notify each sample that the key has been released
  260. for( QList<GigSample>::iterator sample = it->samples.begin();
  261. sample != it->samples.end(); ++sample )
  262. {
  263. sample->adsr.keyup();
  264. }
  265. // Add release samples if available
  266. if( it->release == true )
  267. {
  268. addSamples( *it, true );
  269. }
  270. }
  271. }
  272. // Process notes in the KeyDown state, adding samples for the notes
  273. else if( it->state == KeyDown )
  274. {
  275. it->state = PlayingKeyDown;
  276. addSamples( *it, false );
  277. }
  278. // Delete ended samples
  279. for( QList<GigSample>::iterator sample = it->samples.begin();
  280. sample != it->samples.end(); ++sample )
  281. {
  282. // Delete if the ADSR for a sample is complete for normal
  283. // notes, or if a release sample, then if we've reached
  284. // the end of the sample
  285. if( sample->sample == NULL || sample->adsr.done() ||
  286. ( it->isRelease == true &&
  287. sample->pos >= sample->sample->SamplesTotal - 1 ) )
  288. {
  289. sample = it->samples.erase( sample );
  290. if( sample == it->samples.end() )
  291. {
  292. break;
  293. }
  294. }
  295. }
  296. // Delete ended notes (either in the completed state or all the samples ended)
  297. if( it->state == Completed || it->samples.empty() )
  298. {
  299. it = m_notes.erase( it );
  300. if( it == m_notes.end() )
  301. {
  302. break;
  303. }
  304. }
  305. }
  306. // Fill buffer with portions of the note samples
  307. for( QList<GigNote>::iterator it = m_notes.begin(); it != m_notes.end(); ++it )
  308. {
  309. // Only process the notes if we're in a playing state
  310. if( !( it->state == PlayingKeyDown ||
  311. it->state == PlayingKeyUp ) )
  312. {
  313. continue;
  314. }
  315. for( QList<GigSample>::iterator sample = it->samples.begin();
  316. sample != it->samples.end(); ++sample )
  317. {
  318. if( sample->sample == NULL || sample->region == NULL )
  319. {
  320. continue;
  321. }
  322. // Will change if resampling
  323. bool resample = false;
  324. f_cnt_t samples = frames; // How many to grab
  325. f_cnt_t used = frames; // How many we used
  326. float freq_factor = 1.0; // How to resample
  327. // Resample to be the correct pitch when the sample provided isn't
  328. // solely for this one note (e.g. one or two samples per octave) or
  329. // we are processing at a different sample rate
  330. if( sample->region->PitchTrack == true || rate != sample->sample->SamplesPerSecond )
  331. {
  332. resample = true;
  333. // Factor just for resampling
  334. freq_factor = 1.0 * rate / sample->sample->SamplesPerSecond;
  335. // Factor for pitch shifting as well as resampling
  336. if( sample->region->PitchTrack == true )
  337. {
  338. freq_factor *= sample->freqFactor;
  339. }
  340. // We need a bit of margin so we don't get glitching
  341. samples = frames / freq_factor + MARGIN[m_interpolation];
  342. }
  343. // Load this note's data
  344. sampleFrame sampleData[samples];
  345. loadSample( *sample, sampleData, samples );
  346. // Apply ADSR using a copy so if we don't use these samples when
  347. // resampling, the ADSR doesn't get messed up
  348. ADSR copy = sample->adsr;
  349. for( f_cnt_t i = 0; i < samples; ++i )
  350. {
  351. float amplitude = copy.value();
  352. sampleData[i][0] *= amplitude;
  353. sampleData[i][1] *= amplitude;
  354. }
  355. // Output the data resampling if needed
  356. if( resample == true )
  357. {
  358. sampleFrame convertBuf[frames];
  359. // Only output if resampling is successful (note that "used" is output)
  360. if( sample->convertSampleRate( *sampleData, *convertBuf, samples, frames,
  361. freq_factor, used ) )
  362. {
  363. for( f_cnt_t i = 0; i < frames; ++i )
  364. {
  365. _working_buffer[i][0] += convertBuf[i][0];
  366. _working_buffer[i][1] += convertBuf[i][1];
  367. }
  368. }
  369. }
  370. else
  371. {
  372. for( f_cnt_t i = 0; i < frames; ++i )
  373. {
  374. _working_buffer[i][0] += sampleData[i][0];
  375. _working_buffer[i][1] += sampleData[i][1];
  376. }
  377. }
  378. // Update note position with how many samples we actually used
  379. sample->pos += used;
  380. sample->adsr.inc( used );
  381. }
  382. }
  383. m_notesMutex.unlock();
  384. m_synthMutex.unlock();
  385. // Set gain properly based on volume control
  386. for( f_cnt_t i = 0; i < frames; ++i )
  387. {
  388. _working_buffer[i][0] *= m_gain.value();
  389. _working_buffer[i][1] *= m_gain.value();
  390. }
  391. instrumentTrack()->processAudioBuffer( _working_buffer, frames, NULL );
  392. }
  393. void GigInstrument::loadSample( GigSample& sample, sampleFrame* sampleData, f_cnt_t samples )
  394. {
  395. if( sampleData == NULL || samples < 1 )
  396. {
  397. return;
  398. }
  399. // Determine if we need to loop part of this sample
  400. bool loop = false;
  401. gig::loop_type_t loopType = gig::loop_type_normal;
  402. f_cnt_t loopStart = 0;
  403. f_cnt_t loopLength = 0;
  404. if( sample.region->pSampleLoops != NULL )
  405. {
  406. for( uint32_t i = 0; i < sample.region->SampleLoops; ++i )
  407. {
  408. loop = true;
  409. loopType = static_cast<gig::loop_type_t>( sample.region->pSampleLoops[i].LoopType );
  410. loopStart = sample.region->pSampleLoops[i].LoopStart;
  411. loopLength = sample.region->pSampleLoops[i].LoopLength;
  412. // Currently only support at max one loop
  413. break;
  414. }
  415. }
  416. unsigned long allocationsize = samples * sample.sample->FrameSize;
  417. int8_t buffer[allocationsize];
  418. // Load the sample in different ways depending on if we're looping or not
  419. if( loop == true && ( sample.pos >= loopStart || sample.pos + samples > loopStart ) )
  420. {
  421. // Calculate the new position based on the type of loop
  422. if( loopType == gig::loop_type_bidirectional )
  423. {
  424. sample.pos = getPingPongIndex( sample.pos, loopStart, loopStart + loopLength );
  425. }
  426. else
  427. {
  428. sample.pos = getLoopedIndex( sample.pos, loopStart, loopStart + loopLength );
  429. // TODO: also implement loop_type_backward support
  430. }
  431. sample.sample->SetPos( sample.pos );
  432. // Load the samples (based on gig::Sample::ReadAndLoop) even around the end
  433. // of a loop boundary wrapping to the beginning of the loop region
  434. long samplestoread = samples;
  435. long samplestoloopend = 0;
  436. long readsamples = 0;
  437. long totalreadsamples = 0;
  438. long loopEnd = loopStart + loopLength;
  439. do
  440. {
  441. samplestoloopend = loopEnd - sample.sample->GetPos();
  442. readsamples = sample.sample->Read( &buffer[totalreadsamples * sample.sample->FrameSize],
  443. min( samplestoread, samplestoloopend ) );
  444. samplestoread -= readsamples;
  445. totalreadsamples += readsamples;
  446. if( readsamples >= samplestoloopend )
  447. {
  448. sample.sample->SetPos( loopStart );
  449. }
  450. }
  451. while( samplestoread > 0 && readsamples > 0 );
  452. }
  453. else
  454. {
  455. sample.sample->SetPos( sample.pos );
  456. unsigned long size = sample.sample->Read( &buffer, samples ) * sample.sample->FrameSize;
  457. std::memset( (int8_t*) &buffer + size, 0, allocationsize - size );
  458. }
  459. // Convert from 16 or 24 bit into 32-bit float
  460. if( sample.sample->BitDepth == 24 ) // 24 bit
  461. {
  462. uint8_t * pInt = reinterpret_cast<uint8_t*>( &buffer );
  463. for( f_cnt_t i = 0; i < samples; ++i )
  464. {
  465. // libgig gives 24-bit data as little endian, so we must
  466. // convert if on a big endian system
  467. int32_t valueLeft = swap32IfBE(
  468. ( pInt[ 3 * sample.sample->Channels * i ] << 8 ) |
  469. ( pInt[ 3 * sample.sample->Channels * i + 1 ] << 16 ) |
  470. ( pInt[ 3 * sample.sample->Channels * i + 2 ] << 24 ) );
  471. // Store the notes to this buffer before saving to output
  472. // so we can fade them out as needed
  473. sampleData[i][0] = 1.0 / 0x100000000 * sample.attenuation * valueLeft;
  474. if( sample.sample->Channels == 1 )
  475. {
  476. sampleData[i][1] = sampleData[i][0];
  477. }
  478. else
  479. {
  480. int32_t valueRight = swap32IfBE(
  481. ( pInt[ 3 * sample.sample->Channels * i + 3 ] << 8 ) |
  482. ( pInt[ 3 * sample.sample->Channels * i + 4 ] << 16 ) |
  483. ( pInt[ 3 * sample.sample->Channels * i + 5 ] << 24 ) );
  484. sampleData[i][1] = 1.0 / 0x100000000 * sample.attenuation * valueRight;
  485. }
  486. }
  487. }
  488. else // 16 bit
  489. {
  490. int16_t * pInt = reinterpret_cast<int16_t*>( &buffer );
  491. for( f_cnt_t i = 0; i < samples; ++i )
  492. {
  493. sampleData[i][0] = 1.0 / 0x10000 *
  494. pInt[ sample.sample->Channels * i ] * sample.attenuation;
  495. if( sample.sample->Channels == 1 )
  496. {
  497. sampleData[i][1] = sampleData[i][0];
  498. }
  499. else
  500. {
  501. sampleData[i][1] = 1.0 / 0x10000 *
  502. pInt[ sample.sample->Channels * i + 1 ] * sample.attenuation;
  503. }
  504. }
  505. }
  506. }
  507. // These two loop index functions taken from SampleBuffer.cpp
  508. f_cnt_t GigInstrument::getLoopedIndex( f_cnt_t index, f_cnt_t startf, f_cnt_t endf ) const
  509. {
  510. if( index < endf )
  511. {
  512. return index;
  513. }
  514. return startf + ( index - startf )
  515. % ( endf - startf );
  516. }
  517. f_cnt_t GigInstrument::getPingPongIndex( f_cnt_t index, f_cnt_t startf, f_cnt_t endf ) const
  518. {
  519. if( index < endf )
  520. {
  521. return index;
  522. }
  523. const f_cnt_t looplen = endf - startf;
  524. const f_cnt_t looppos = ( index - endf ) % ( looplen * 2 );
  525. return ( looppos < looplen )
  526. ? endf - looppos
  527. : startf + ( looppos - looplen );
  528. }
  529. // A key has been released
  530. void GigInstrument::deleteNotePluginData( NotePlayHandle * _n )
  531. {
  532. GIGPluginData * pluginData = static_cast<GIGPluginData *>( _n->m_pluginData );
  533. QMutexLocker locker( &m_notesMutex );
  534. // Mark the note as being released, but only if it was playing or was just
  535. // pressed (i.e., not if the key was already released)
  536. for( QList<GigNote>::iterator i = m_notes.begin(); i != m_notes.end(); ++i )
  537. {
  538. // Find the note by matching pointers to the plugin data
  539. if( i->handle == pluginData &&
  540. ( i->state == KeyDown || i->state == PlayingKeyDown ) )
  541. {
  542. i->state = KeyUp;
  543. }
  544. }
  545. // TODO: not sample exact? What about in the middle of us writing out the sample?
  546. delete pluginData;
  547. }
  548. PluginView * GigInstrument::instantiateView( QWidget * _parent )
  549. {
  550. return new GigInstrumentView( this, _parent );
  551. }
  552. // Add the desired samples (either the normal samples or the release samples)
  553. // to the GigNote
  554. //
  555. // Note: not thread safe since libgig stores current region position data in
  556. // the instrument object
  557. void GigInstrument::addSamples( GigNote & gignote, bool wantReleaseSample )
  558. {
  559. // Change key dimension, e.g. change samples based on what key is pressed
  560. // in a certain range. From LinuxSampler
  561. if( wantReleaseSample == true &&
  562. gignote.midiNote >= m_instrument->DimensionKeyRange.low &&
  563. gignote.midiNote <= m_instrument->DimensionKeyRange.high )
  564. {
  565. m_currentKeyDimension = float( gignote.midiNote -
  566. m_instrument->DimensionKeyRange.low ) / (
  567. m_instrument->DimensionKeyRange.high -
  568. m_instrument->DimensionKeyRange.low + 1 );
  569. }
  570. gig::Region* pRegion = m_instrument->GetFirstRegion();
  571. while( pRegion != NULL )
  572. {
  573. Dimension dim = getDimensions( pRegion, gignote.velocity, wantReleaseSample );
  574. gig::DimensionRegion * pDimRegion = pRegion->GetDimensionRegionByValue( dim.DimValues );
  575. gig::Sample * pSample = pDimRegion->pSample;
  576. // If this is a release sample, the note won't ever be
  577. // released, so we handle it differently
  578. gignote.isRelease = wantReleaseSample;
  579. // Does this note have release samples? Set this only on the original
  580. // notes and not when we get the release samples.
  581. if( wantReleaseSample != true )
  582. {
  583. gignote.release = dim.release;
  584. }
  585. if( pSample != NULL && pSample->SamplesTotal != 0 )
  586. {
  587. int keyLow = pRegion->KeyRange.low;
  588. int keyHigh = pRegion->KeyRange.high;
  589. if( gignote.midiNote >= keyLow && gignote.midiNote <= keyHigh )
  590. {
  591. float attenuation = pDimRegion->GetVelocityAttenuation( gignote.velocity );
  592. float length = (float) pSample->SamplesTotal / Engine::mixer()->processingSampleRate();
  593. // TODO: sample panning? crossfade different layers?
  594. if( wantReleaseSample == true )
  595. {
  596. // From LinuxSampler, not sure how it was created
  597. attenuation *= 1 - 0.01053 * ( 256 >> pDimRegion->ReleaseTriggerDecay ) * length;
  598. }
  599. else
  600. {
  601. attenuation *= pDimRegion->SampleAttenuation;
  602. }
  603. gignote.samples.push_back( GigSample( pSample, pDimRegion,
  604. attenuation, m_interpolation, gignote.frequency ) );
  605. }
  606. }
  607. pRegion = m_instrument->GetNextRegion();
  608. }
  609. }
  610. // Based on our input parameters, generate a "dimension" that specifies which
  611. // note we wish to select from the GIG file with libgig. libgig will use this
  612. // information to select the sample.
  613. Dimension GigInstrument::getDimensions( gig::Region * pRegion, int velocity, bool release )
  614. {
  615. Dimension dim;
  616. if( pRegion == NULL )
  617. {
  618. return dim;
  619. }
  620. for( int i = pRegion->Dimensions - 1; i >= 0; --i )
  621. {
  622. switch( pRegion->pDimensionDefinitions[i].dimension )
  623. {
  624. case gig::dimension_layer:
  625. // TODO: implement this
  626. dim.DimValues[i] = 0;
  627. break;
  628. case gig::dimension_velocity:
  629. dim.DimValues[i] = velocity;
  630. break;
  631. case gig::dimension_releasetrigger:
  632. dim.release = true;
  633. dim.DimValues[i] = (uint) release;
  634. break;
  635. case gig::dimension_keyboard:
  636. dim.DimValues[i] = (uint) ( m_currentKeyDimension * pRegion->pDimensionDefinitions[i].zones );
  637. break;
  638. case gig::dimension_roundrobin:
  639. case gig::dimension_roundrobinkeyboard:
  640. // TODO: implement this
  641. dim.DimValues[i] = 0;
  642. break;
  643. case gig::dimension_random:
  644. // From LinuxSampler, untested
  645. m_RandomSeed = m_RandomSeed * 1103515245 + 12345;
  646. dim.DimValues[i] = uint(
  647. m_RandomSeed / 4294967296.0f * pRegion->pDimensionDefinitions[i].bits );
  648. break;
  649. case gig::dimension_samplechannel:
  650. case gig::dimension_channelaftertouch:
  651. case gig::dimension_modwheel:
  652. case gig::dimension_breath:
  653. case gig::dimension_foot:
  654. case gig::dimension_portamentotime:
  655. case gig::dimension_effect1:
  656. case gig::dimension_effect2:
  657. case gig::dimension_genpurpose1:
  658. case gig::dimension_genpurpose2:
  659. case gig::dimension_genpurpose3:
  660. case gig::dimension_genpurpose4:
  661. case gig::dimension_sustainpedal:
  662. case gig::dimension_portamento:
  663. case gig::dimension_sostenutopedal:
  664. case gig::dimension_softpedal:
  665. case gig::dimension_genpurpose5:
  666. case gig::dimension_genpurpose6:
  667. case gig::dimension_genpurpose7:
  668. case gig::dimension_genpurpose8:
  669. case gig::dimension_effect1depth:
  670. case gig::dimension_effect2depth:
  671. case gig::dimension_effect3depth:
  672. case gig::dimension_effect4depth:
  673. case gig::dimension_effect5depth:
  674. case gig::dimension_none:
  675. default:
  676. dim.DimValues[i] = 0;
  677. break;
  678. }
  679. }
  680. return dim;
  681. }
  682. // Get the selected instrument from the GIG file we opened if we haven't gotten
  683. // it already. This is based on the bank and patch numbers.
  684. void GigInstrument::getInstrument()
  685. {
  686. // Find instrument
  687. int iBankSelected = m_bankNum.value();
  688. int iProgSelected = m_patchNum.value();
  689. QMutexLocker locker( &m_synthMutex );
  690. if( m_instance != NULL )
  691. {
  692. gig::Instrument * pInstrument = m_instance->gig.GetFirstInstrument();
  693. while( pInstrument != NULL )
  694. {
  695. int iBank = pInstrument->MIDIBank;
  696. int iProg = pInstrument->MIDIProgram;
  697. if( iBank == iBankSelected && iProg == iProgSelected )
  698. {
  699. break;
  700. }
  701. pInstrument = m_instance->gig.GetNextInstrument();
  702. }
  703. m_instrument = pInstrument;
  704. }
  705. }
  706. // Since the sample rate changes when we start an export, clear all the
  707. // currently-playing notes when we get this signal. Then, the export won't
  708. // include leftover notes that were playing in the program.
  709. void GigInstrument::updateSampleRate()
  710. {
  711. QMutexLocker locker( &m_notesMutex );
  712. m_notes.clear();
  713. }
  714. class gigKnob : public Knob
  715. {
  716. public:
  717. gigKnob( QWidget * _parent ) :
  718. Knob( knobBright_26, _parent )
  719. {
  720. setFixedSize( 31, 38 );
  721. }
  722. } ;
  723. GigInstrumentView::GigInstrumentView( Instrument * _instrument, QWidget * _parent ) :
  724. InstrumentViewFixedSize( _instrument, _parent )
  725. {
  726. GigInstrument * k = castModel<GigInstrument>();
  727. connect( &k->m_bankNum, SIGNAL( dataChanged() ), this, SLOT( updatePatchName() ) );
  728. connect( &k->m_patchNum, SIGNAL( dataChanged() ), this, SLOT( updatePatchName() ) );
  729. // File Button
  730. m_fileDialogButton = new PixmapButton( this );
  731. m_fileDialogButton->setCursor( QCursor( Qt::PointingHandCursor ) );
  732. m_fileDialogButton->setActiveGraphic( PLUGIN_NAME::getIconPixmap( "fileselect_on" ) );
  733. m_fileDialogButton->setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "fileselect_off" ) );
  734. m_fileDialogButton->move( 223, 68 );
  735. connect( m_fileDialogButton, SIGNAL( clicked() ), this, SLOT( showFileDialog() ) );
  736. ToolTip::add( m_fileDialogButton, tr( "Open GIG file" ) );
  737. // Patch Button
  738. m_patchDialogButton = new PixmapButton( this );
  739. m_patchDialogButton->setCursor( QCursor( Qt::PointingHandCursor ) );
  740. m_patchDialogButton->setActiveGraphic( PLUGIN_NAME::getIconPixmap( "patches_on" ) );
  741. m_patchDialogButton->setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "patches_off" ) );
  742. m_patchDialogButton->setEnabled( false );
  743. m_patchDialogButton->move( 223, 94 );
  744. connect( m_patchDialogButton, SIGNAL( clicked() ), this, SLOT( showPatchDialog() ) );
  745. ToolTip::add( m_patchDialogButton, tr( "Choose patch" ) );
  746. // LCDs
  747. m_bankNumLcd = new LcdSpinBox( 3, "21pink", this );
  748. m_bankNumLcd->move( 111, 150 );
  749. m_patchNumLcd = new LcdSpinBox( 3, "21pink", this );
  750. m_patchNumLcd->move( 161, 150 );
  751. // Next row
  752. m_filenameLabel = new QLabel( this );
  753. m_filenameLabel->setGeometry( 61, 70, 156, 14 );
  754. m_patchLabel = new QLabel( this );
  755. m_patchLabel->setGeometry( 61, 94, 156, 14 );
  756. // Gain
  757. m_gainKnob = new gigKnob( this );
  758. m_gainKnob->setHintText( tr( "Gain:" ) + " ", "" );
  759. m_gainKnob->move( 32, 140 );
  760. setAutoFillBackground( true );
  761. QPalette pal;
  762. pal.setBrush( backgroundRole(), PLUGIN_NAME::getIconPixmap( "artwork" ) );
  763. setPalette( pal );
  764. updateFilename();
  765. }
  766. GigInstrumentView::~GigInstrumentView()
  767. {
  768. }
  769. void GigInstrumentView::modelChanged()
  770. {
  771. GigInstrument * k = castModel<GigInstrument>();
  772. m_bankNumLcd->setModel( &k->m_bankNum );
  773. m_patchNumLcd->setModel( &k->m_patchNum );
  774. m_gainKnob->setModel( &k->m_gain );
  775. connect( k, SIGNAL( fileChanged() ), this, SLOT( updateFilename() ) );
  776. connect( k, SIGNAL( fileLoading() ), this, SLOT( invalidateFile() ) );
  777. updateFilename();
  778. }
  779. void GigInstrumentView::updateFilename()
  780. {
  781. GigInstrument * i = castModel<GigInstrument>();
  782. QFontMetrics fm( m_filenameLabel->font() );
  783. QString file = i->m_filename.endsWith( ".gig", Qt::CaseInsensitive ) ?
  784. i->m_filename.left( i->m_filename.length() - 4 ) :
  785. i->m_filename;
  786. m_filenameLabel->setText( fm.elidedText( file, Qt::ElideLeft, m_filenameLabel->width() ) );
  787. m_patchDialogButton->setEnabled( !i->m_filename.isEmpty() );
  788. updatePatchName();
  789. update();
  790. }
  791. void GigInstrumentView::updatePatchName()
  792. {
  793. GigInstrument * i = castModel<GigInstrument>();
  794. QFontMetrics fm( font() );
  795. QString patch = i->getCurrentPatchName();
  796. m_patchLabel->setText( fm.elidedText( patch, Qt::ElideLeft, m_patchLabel->width() ) );
  797. update();
  798. }
  799. void GigInstrumentView::invalidateFile()
  800. {
  801. m_patchDialogButton->setEnabled( false );
  802. }
  803. void GigInstrumentView::showFileDialog()
  804. {
  805. GigInstrument * k = castModel<GigInstrument>();
  806. FileDialog ofd( NULL, tr( "Open GIG file" ) );
  807. ofd.setFileMode( FileDialog::ExistingFiles );
  808. QStringList types;
  809. types << tr( "GIG Files (*.gig)" );
  810. ofd.setNameFilters( types );
  811. if( k->m_filename != "" )
  812. {
  813. QString f = SampleBuffer::tryToMakeAbsolute( k->m_filename );
  814. ofd.setDirectory( QFileInfo( f ).absolutePath() );
  815. ofd.selectFile( QFileInfo( f ).fileName() );
  816. }
  817. else
  818. {
  819. ofd.setDirectory( ConfigManager::inst()->gigDir() );
  820. }
  821. m_fileDialogButton->setEnabled( false );
  822. if( ofd.exec() == QDialog::Accepted && !ofd.selectedFiles().isEmpty() )
  823. {
  824. QString f = ofd.selectedFiles()[0];
  825. if( f != "" )
  826. {
  827. k->openFile( f );
  828. Engine::getSong()->setModified();
  829. }
  830. }
  831. m_fileDialogButton->setEnabled( true );
  832. }
  833. void GigInstrumentView::showPatchDialog()
  834. {
  835. GigInstrument * k = castModel<GigInstrument>();
  836. PatchesDialog pd( this );
  837. pd.setup( k->m_instance, 1, k->instrumentTrack()->name(), &k->m_bankNum, &k->m_patchNum, m_patchLabel );
  838. pd.exec();
  839. }
  840. // Store information related to playing a sample from the GIG file
  841. GigSample::GigSample( gig::Sample * pSample, gig::DimensionRegion * pDimRegion,
  842. float attenuation, int interpolation, float desiredFreq )
  843. : sample( pSample ), region( pDimRegion ), attenuation( attenuation ),
  844. pos( 0 ), interpolation( interpolation ), srcState( NULL ),
  845. sampleFreq( 0 ), freqFactor( 1 )
  846. {
  847. if( sample != NULL && region != NULL )
  848. {
  849. // Note: we don't create the libsamplerate object here since we always
  850. // also call the copy constructor when appending to the end of the
  851. // QList. We'll create it only in the copy constructor so we only have
  852. // to create it once.
  853. // Calculate note pitch and frequency factor only if we're actually
  854. // going to be changing the pitch of the notes
  855. if( region->PitchTrack == true )
  856. {
  857. // Calculate what frequency the provided sample is
  858. sampleFreq = 440.0 * powf( 2, 1.0 / 12 * (
  859. 1.0 * region->UnityNote - 69 -
  860. 0.01 * region->FineTune ) );
  861. freqFactor = sampleFreq / desiredFreq;
  862. }
  863. // The sample rate we pass in is affected by how we are going to be
  864. // resampling the note so that a 1.5 second release ends up being 1.5
  865. // seconds after resampling
  866. adsr = ADSR( region, sample->SamplesPerSecond / freqFactor );
  867. }
  868. }
  869. GigSample::~GigSample()
  870. {
  871. if( srcState != NULL )
  872. {
  873. src_delete( srcState );
  874. }
  875. }
  876. GigSample::GigSample( const GigSample& g )
  877. : sample( g.sample ), region( g.region ), attenuation( g.attenuation ),
  878. adsr( g.adsr ), pos( g.pos ), interpolation( g.interpolation ),
  879. srcState( NULL ), sampleFreq( g.sampleFreq ), freqFactor( g.freqFactor )
  880. {
  881. // On the copy, we want to create the object
  882. updateSampleRate();
  883. }
  884. GigSample& GigSample::operator=( const GigSample& g )
  885. {
  886. sample = g.sample;
  887. region= g.region;
  888. attenuation = g.attenuation;
  889. adsr = g.adsr;
  890. pos = g.pos;
  891. interpolation = g.interpolation;
  892. srcState = NULL;
  893. sampleFreq = g.sampleFreq;
  894. freqFactor = g.freqFactor;
  895. if( g.srcState != NULL )
  896. {
  897. updateSampleRate();
  898. }
  899. return *this;
  900. }
  901. void GigSample::updateSampleRate()
  902. {
  903. if( srcState != NULL )
  904. {
  905. src_delete( srcState );
  906. }
  907. int error = 0;
  908. srcState = src_new( interpolation, DEFAULT_CHANNELS, &error );
  909. if( srcState == NULL || error != 0 )
  910. {
  911. qCritical( "error while creating libsamplerate data structure in GigSample" );
  912. }
  913. }
  914. bool GigSample::convertSampleRate( sampleFrame & oldBuf, sampleFrame & newBuf,
  915. f_cnt_t oldSize, f_cnt_t newSize, float freq_factor, f_cnt_t& used )
  916. {
  917. if( srcState == NULL )
  918. {
  919. return false;
  920. }
  921. SRC_DATA src_data;
  922. src_data.data_in = &oldBuf[0];
  923. src_data.data_out = &newBuf[0];
  924. src_data.input_frames = oldSize;
  925. src_data.output_frames = newSize;
  926. src_data.src_ratio = freq_factor;
  927. src_data.end_of_input = 0;
  928. // We don't need to lock this assuming that we're only outputting the
  929. // samples in one thread
  930. int error = src_process( srcState, &src_data );
  931. used = src_data.input_frames_used;
  932. if( error != 0 )
  933. {
  934. qCritical( "GigInstrument: error while resampling: %s", src_strerror( error ) );
  935. return false;
  936. }
  937. if( oldSize != 0 && src_data.output_frames_gen == 0 )
  938. {
  939. qCritical( "GigInstrument: could not resample, no frames generated" );
  940. return false;
  941. }
  942. if( src_data.output_frames_gen > 0 && src_data.output_frames_gen < newSize )
  943. {
  944. qCritical() << "GigInstrument: not enough frames, wanted"
  945. << newSize << "generated" << src_data.output_frames_gen;
  946. return false;
  947. }
  948. return true;
  949. }
  950. ADSR::ADSR()
  951. : preattack( 0 ), attack( 0 ), decay1( 0 ), decay2( 0 ), infiniteSustain( false ),
  952. sustain( 0 ), release( 0 ),
  953. amplitude( 0 ), isAttack( true ), isRelease( false ), isDone( false ),
  954. attackPosition( 0 ), attackLength( 0 ), decayLength( 0 ),
  955. releasePosition( 0 ), releaseLength( 0 )
  956. {
  957. }
  958. // Create the ADSR envelope from the settings in the GIG file
  959. ADSR::ADSR( gig::DimensionRegion * region, int sampleRate )
  960. : preattack( 0 ), attack( 0 ), decay1( 0 ), decay2( 0 ), infiniteSustain( false ),
  961. sustain( 0 ), release( 0 ),
  962. amplitude( 0 ), isAttack( true ), isRelease( false ), isDone( false ),
  963. attackPosition( 0 ), attackLength( 0 ), decayLength( 0 ),
  964. releasePosition( 0 ), releaseLength( 0 )
  965. {
  966. if( region != NULL )
  967. {
  968. // Parameters from GIG file
  969. preattack = 1.0 * region->EG1PreAttack / 1000; // EG1PreAttack is 0-1000 permille
  970. attack = region->EG1Attack;
  971. decay1 = region->EG1Decay1;
  972. decay2 = region->EG1Decay2;
  973. infiniteSustain = region->EG1InfiniteSustain;
  974. sustain = 1.0 * region->EG1Sustain / 1000; // EG1Sustain is 0-1000 permille
  975. release = region->EG1Release;
  976. // Simple ADSR using positions in sample
  977. amplitude = preattack;
  978. attackLength = attack * sampleRate;
  979. decayLength = decay1 * sampleRate; // TODO: ignoring decay2 for now
  980. releaseLength = release * sampleRate;
  981. // If there is no attack or decay, start at the sustain amplitude
  982. if( attackLength == 0 && decayLength == 0 )
  983. {
  984. amplitude = sustain;
  985. }
  986. // If there is no attack, start at the full amplitude
  987. else if( attackLength == 0 )
  988. {
  989. amplitude = 1.0;
  990. }
  991. }
  992. }
  993. // Next time we get the amplitude, we'll be releasing the note
  994. void ADSR::keyup()
  995. {
  996. isRelease = true;
  997. }
  998. // Can we delete the sample now?
  999. bool ADSR::done()
  1000. {
  1001. return isDone;
  1002. }
  1003. // Return the current amplitude and increment internal positions
  1004. float ADSR::value()
  1005. {
  1006. float currentAmplitude = amplitude;
  1007. // If we're done, don't output any signal
  1008. if( isDone == true )
  1009. {
  1010. return 0;
  1011. }
  1012. // If we're still in the attack phase, release from the current volume
  1013. // instead of jumping to the sustain volume and fading out
  1014. else if( isAttack == true && isRelease == true )
  1015. {
  1016. sustain = amplitude;
  1017. isAttack = false;
  1018. }
  1019. // If we're in the attack phase, start at the preattack amplitude and
  1020. // increase to the full before decreasing to sustain
  1021. if( isAttack == true )
  1022. {
  1023. if( attackPosition < attackLength )
  1024. {
  1025. amplitude = preattack + ( 1.0 - preattack ) / attackLength * attackPosition;
  1026. }
  1027. else if( attackPosition < attackLength + decayLength )
  1028. {
  1029. amplitude = 1.0 - ( 1.0 - sustain ) / decayLength * ( attackPosition - attackLength );
  1030. }
  1031. else
  1032. {
  1033. isAttack = false;
  1034. }
  1035. ++attackPosition;
  1036. }
  1037. // If we're in the sustain phase, decrease from sustain to zero
  1038. else if( isRelease == true )
  1039. {
  1040. // Maybe not the best way of doing this, but it appears to be about right
  1041. // Satisfies f(0) = sustain and f(releaseLength) = very small
  1042. amplitude = ( sustain + 1e-3 ) * expf( -5.0 / releaseLength * releasePosition ) - 1e-3;
  1043. // Don't have an infinite exponential decay
  1044. if( amplitude <= 0 || releasePosition >= releaseLength )
  1045. {
  1046. amplitude = 0;
  1047. isDone = true;
  1048. }
  1049. ++releasePosition;
  1050. }
  1051. return currentAmplitude;
  1052. }
  1053. // Increment internal positions a certain number of times
  1054. void ADSR::inc( f_cnt_t num )
  1055. {
  1056. for( f_cnt_t i = 0; i < num; ++i )
  1057. {
  1058. value();
  1059. }
  1060. }
  1061. extern "C"
  1062. {
  1063. // necessary for getting instance out of shared lib
  1064. PLUGIN_EXPORT Plugin * lmms_plugin_main( Model *m, void * )
  1065. {
  1066. return new GigInstrument( static_cast<InstrumentTrack *>( m ) );
  1067. }
  1068. }