GigPlayer.cpp 34 KB

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