GigPlayer.cpp 34 KB

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