RemotePlugin.h 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452
  1. /*
  2. * RemotePlugin.h - base class providing RPC like mechanisms
  3. *
  4. * Copyright (c) 2008-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
  5. *
  6. * This file is part of LMMS - https://lmms.io
  7. *
  8. * This program is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU General Public
  10. * License as published by the Free Software Foundation; either
  11. * version 2 of the License, or (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. * General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public
  19. * License along with this program (see COPYING); if not, write to the
  20. * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
  21. * Boston, MA 02110-1301 USA.
  22. *
  23. */
  24. #ifndef REMOTE_PLUGIN_H
  25. #define REMOTE_PLUGIN_H
  26. #include "export.h"
  27. #include "MidiEvent.h"
  28. #include "VstSyncData.h"
  29. #include <vector>
  30. #include <cstdio>
  31. #include <cstdlib>
  32. #include <cstring>
  33. #include <string>
  34. #include <cassert>
  35. #if !(defined(LMMS_HAVE_SYS_IPC_H) && defined(LMMS_HAVE_SEMAPHORE_H))
  36. #define SYNC_WITH_SHM_FIFO
  37. #define USE_QT_SEMAPHORES
  38. #ifdef LMMS_HAVE_PROCESS_H
  39. #include <process.h>
  40. #endif
  41. #include <QtCore/QtGlobal>
  42. #include <QtCore/QSystemSemaphore>
  43. #endif
  44. #ifdef LMMS_HAVE_SYS_SHM_H
  45. #include <sys/shm.h>
  46. #ifdef LMMS_HAVE_UNISTD_H
  47. #include <unistd.h>
  48. #endif
  49. #else
  50. #define USE_QT_SHMEM
  51. #include <QtCore/QtGlobal>
  52. #include <QtCore/QSharedMemory>
  53. #if !defined(LMMS_HAVE_SYS_TYPES_H) || defined(LMMS_BUILD_WIN32)
  54. typedef int32_t key_t;
  55. #endif
  56. #endif
  57. #ifdef LMMS_HAVE_LOCALE_H
  58. #include <locale.h>
  59. #endif
  60. #ifdef LMMS_HAVE_PTHREAD_H
  61. #include <pthread.h>
  62. #endif
  63. #ifdef BUILD_REMOTE_PLUGIN_CLIENT
  64. #undef EXPORT
  65. #define EXPORT
  66. #define COMPILE_REMOTE_PLUGIN_BASE
  67. #ifndef SYNC_WITH_SHM_FIFO
  68. #include <sys/socket.h>
  69. #include <sys/un.h>
  70. #endif
  71. #else
  72. #include <QtCore/QMutex>
  73. #include <QtCore/QProcess>
  74. #include <QtCore/QThread>
  75. #ifndef SYNC_WITH_SHM_FIFO
  76. #include <poll.h>
  77. #include <unistd.h>
  78. #endif
  79. #endif
  80. #ifdef SYNC_WITH_SHM_FIFO
  81. // sometimes we need to exchange bigger messages (e.g. for VST parameter dumps)
  82. // so set a usable value here
  83. const int SHM_FIFO_SIZE = 512*1024;
  84. // implements a FIFO inside a shared memory segment
  85. class shmFifo
  86. {
  87. // need this union to handle different sizes of sem_t on 32 bit
  88. // and 64 bit platforms
  89. union sem32_t
  90. {
  91. int semKey;
  92. char fill[32];
  93. } ;
  94. struct shmData
  95. {
  96. sem32_t dataSem; // semaphore for locking this
  97. // FIFO management data
  98. sem32_t messageSem; // semaphore for incoming messages
  99. volatile int32_t startPtr; // current start of FIFO in memory
  100. volatile int32_t endPtr; // current end of FIFO in memory
  101. char data[SHM_FIFO_SIZE]; // actual data
  102. } ;
  103. public:
  104. // constructor for master-side
  105. shmFifo() :
  106. m_invalid( false ),
  107. m_master( true ),
  108. m_shmKey( 0 ),
  109. #ifdef USE_QT_SHMEM
  110. m_shmObj(),
  111. #else
  112. m_shmID( -1 ),
  113. #endif
  114. m_data( NULL ),
  115. m_dataSem( QString::null ),
  116. m_messageSem( QString::null ),
  117. m_lockDepth( 0 )
  118. {
  119. #ifdef USE_QT_SHMEM
  120. do
  121. {
  122. m_shmObj.setKey( QString( "%1" ).arg( ++m_shmKey ) );
  123. m_shmObj.create( sizeof( shmData ) );
  124. } while( m_shmObj.error() != QSharedMemory::NoError );
  125. m_data = (shmData *) m_shmObj.data();
  126. #else
  127. while( ( m_shmID = shmget( ++m_shmKey, sizeof( shmData ),
  128. IPC_CREAT | IPC_EXCL | 0600 ) ) == -1 )
  129. {
  130. }
  131. m_data = (shmData *) shmat( m_shmID, 0, 0 );
  132. #endif
  133. assert( m_data != NULL );
  134. m_data->startPtr = m_data->endPtr = 0;
  135. static int k = 0;
  136. m_data->dataSem.semKey = ( getpid()<<10 ) + ++k;
  137. m_data->messageSem.semKey = ( getpid()<<10 ) + ++k;
  138. m_dataSem.setKey( QString::number( m_data->dataSem.semKey ),
  139. 1, QSystemSemaphore::Create );
  140. m_messageSem.setKey( QString::number(
  141. m_data->messageSem.semKey ),
  142. 0, QSystemSemaphore::Create );
  143. }
  144. // constructor for remote-/client-side - use _shm_key for making up
  145. // the connection to master
  146. shmFifo( key_t _shm_key ) :
  147. m_invalid( false ),
  148. m_master( false ),
  149. m_shmKey( 0 ),
  150. #ifdef USE_QT_SHMEM
  151. m_shmObj( QString::number( _shm_key ) ),
  152. #else
  153. m_shmID( shmget( _shm_key, 0, 0 ) ),
  154. #endif
  155. m_data( NULL ),
  156. m_dataSem( QString::null ),
  157. m_messageSem( QString::null ),
  158. m_lockDepth( 0 )
  159. {
  160. #ifdef USE_QT_SHMEM
  161. if( m_shmObj.attach() )
  162. {
  163. m_data = (shmData *) m_shmObj.data();
  164. }
  165. #else
  166. if( m_shmID != -1 )
  167. {
  168. m_data = (shmData *) shmat( m_shmID, 0, 0 );
  169. }
  170. #endif
  171. assert( m_data != NULL );
  172. m_dataSem.setKey( QString::number( m_data->dataSem.semKey ) );
  173. m_messageSem.setKey( QString::number(
  174. m_data->messageSem.semKey ) );
  175. }
  176. ~shmFifo()
  177. {
  178. // master?
  179. if( m_master )
  180. {
  181. #ifndef USE_QT_SHMEM
  182. shmctl( m_shmID, IPC_RMID, NULL );
  183. #endif
  184. }
  185. #ifndef USE_QT_SHMEM
  186. shmdt( m_data );
  187. #endif
  188. }
  189. inline bool isInvalid() const
  190. {
  191. return m_invalid;
  192. }
  193. void invalidate()
  194. {
  195. m_invalid = true;
  196. }
  197. // do we act as master (i.e. not as remote-process?)
  198. inline bool isMaster() const
  199. {
  200. return m_master;
  201. }
  202. // recursive lock
  203. inline void lock()
  204. {
  205. if( !isInvalid() && __sync_add_and_fetch( &m_lockDepth, 1 ) == 1 )
  206. {
  207. m_dataSem.acquire();
  208. }
  209. }
  210. // recursive unlock
  211. inline void unlock()
  212. {
  213. if( __sync_sub_and_fetch( &m_lockDepth, 1) <= 0 )
  214. {
  215. m_dataSem.release();
  216. }
  217. }
  218. // wait until message-semaphore is available
  219. inline void waitForMessage()
  220. {
  221. if( !isInvalid() )
  222. {
  223. m_messageSem.acquire();
  224. }
  225. }
  226. // increase message-semaphore
  227. inline void messageSent()
  228. {
  229. m_messageSem.release();
  230. }
  231. inline int32_t readInt()
  232. {
  233. int32_t i;
  234. read( &i, sizeof( i ) );
  235. return i;
  236. }
  237. inline void writeInt( const int32_t & _i )
  238. {
  239. write( &_i, sizeof( _i ) );
  240. }
  241. inline std::string readString()
  242. {
  243. const int len = readInt();
  244. if( len )
  245. {
  246. char * sc = new char[len + 1];
  247. read( sc, len );
  248. sc[len] = 0;
  249. std::string s( sc );
  250. delete[] sc;
  251. return s;
  252. }
  253. return std::string();
  254. }
  255. inline void writeString( const std::string & _s )
  256. {
  257. const int len = _s.size();
  258. writeInt( len );
  259. write( _s.c_str(), len );
  260. }
  261. inline bool messagesLeft()
  262. {
  263. if( isInvalid() )
  264. {
  265. return false;
  266. }
  267. lock();
  268. const bool empty = ( m_data->startPtr == m_data->endPtr );
  269. unlock();
  270. return !empty;
  271. }
  272. inline int shmKey() const
  273. {
  274. return m_shmKey;
  275. }
  276. private:
  277. static inline void fastMemCpy( void * _dest, const void * _src,
  278. const int _len )
  279. {
  280. // calling memcpy() for just an integer is obsolete overhead
  281. if( _len == 4 )
  282. {
  283. *( (int32_t *) _dest ) = *( (int32_t *) _src );
  284. }
  285. else
  286. {
  287. memcpy( _dest, _src, _len );
  288. }
  289. }
  290. void read( void * _buf, int _len )
  291. {
  292. if( isInvalid() )
  293. {
  294. memset( _buf, 0, _len );
  295. return;
  296. }
  297. lock();
  298. while( isInvalid() == false &&
  299. _len > m_data->endPtr - m_data->startPtr )
  300. {
  301. unlock();
  302. #ifndef LMMS_BUILD_WIN32
  303. usleep( 5 );
  304. #endif
  305. lock();
  306. }
  307. fastMemCpy( _buf, m_data->data + m_data->startPtr, _len );
  308. m_data->startPtr += _len;
  309. // nothing left?
  310. if( m_data->startPtr == m_data->endPtr )
  311. {
  312. // then reset to 0
  313. m_data->startPtr = m_data->endPtr = 0;
  314. }
  315. unlock();
  316. }
  317. void write( const void * _buf, int _len )
  318. {
  319. if( isInvalid() || _len > SHM_FIFO_SIZE )
  320. {
  321. return;
  322. }
  323. lock();
  324. while( _len > SHM_FIFO_SIZE - m_data->endPtr )
  325. {
  326. // if no space is left, try to move data to front
  327. if( m_data->startPtr > 0 )
  328. {
  329. memmove( m_data->data,
  330. m_data->data + m_data->startPtr,
  331. m_data->endPtr - m_data->startPtr );
  332. m_data->endPtr = m_data->endPtr -
  333. m_data->startPtr;
  334. m_data->startPtr = 0;
  335. }
  336. unlock();
  337. #ifndef LMMS_BUILD_WIN32
  338. usleep( 5 );
  339. #endif
  340. lock();
  341. }
  342. fastMemCpy( m_data->data + m_data->endPtr, _buf, _len );
  343. m_data->endPtr += _len;
  344. unlock();
  345. }
  346. volatile bool m_invalid;
  347. bool m_master;
  348. key_t m_shmKey;
  349. #ifdef USE_QT_SHMEM
  350. QSharedMemory m_shmObj;
  351. #else
  352. int m_shmID;
  353. #endif
  354. shmData * m_data;
  355. QSystemSemaphore m_dataSem;
  356. QSystemSemaphore m_messageSem;
  357. volatile int m_lockDepth;
  358. } ;
  359. #endif
  360. enum RemoteMessageIDs
  361. {
  362. IdUndefined,
  363. IdHostInfoGotten,
  364. IdInitDone,
  365. IdQuit,
  366. IdSampleRateInformation,
  367. IdBufferSizeInformation,
  368. IdInformationUpdated,
  369. IdMidiEvent,
  370. IdStartProcessing,
  371. IdProcessingDone,
  372. IdChangeSharedMemoryKey,
  373. IdChangeInputCount,
  374. IdChangeOutputCount,
  375. IdChangeInputOutputCount,
  376. IdShowUI,
  377. IdHideUI,
  378. IdToggleUI,
  379. IdIsUIVisible,
  380. IdSaveSettingsToString,
  381. IdSaveSettingsToFile,
  382. IdLoadSettingsFromString,
  383. IdLoadSettingsFromFile,
  384. IdSavePresetFile,
  385. IdLoadPresetFile,
  386. IdDebugMessage,
  387. IdUserBase = 64
  388. } ;
  389. class EXPORT RemotePluginBase
  390. {
  391. public:
  392. struct message
  393. {
  394. message() :
  395. id( IdUndefined ),
  396. data()
  397. {
  398. }
  399. message( const message & _m ) :
  400. id( _m.id ),
  401. data( _m.data )
  402. {
  403. }
  404. message( int _id ) :
  405. id( _id ),
  406. data()
  407. {
  408. }
  409. inline message & addString( const std::string & _s )
  410. {
  411. data.push_back( _s );
  412. return *this;
  413. }
  414. message & addInt( int _i )
  415. {
  416. char buf[32];
  417. sprintf( buf, "%d", _i );
  418. data.push_back( std::string( buf ) );
  419. return *this;
  420. }
  421. message & addFloat( float _f )
  422. {
  423. char buf[32];
  424. sprintf( buf, "%f", _f );
  425. data.push_back( std::string( buf ) );
  426. return *this;
  427. }
  428. inline std::string getString( int _p = 0 ) const
  429. {
  430. return data[_p];
  431. }
  432. #ifndef BUILD_REMOTE_PLUGIN_CLIENT
  433. inline QString getQString( int _p = 0 ) const
  434. {
  435. return QString::fromStdString( getString( _p ) );
  436. }
  437. #endif
  438. inline int getInt( int _p = 0 ) const
  439. {
  440. return atoi( data[_p].c_str() );
  441. }
  442. inline float getFloat( int _p ) const
  443. {
  444. return (float) atof( data[_p].c_str() );
  445. }
  446. inline bool operator==( const message & _m ) const
  447. {
  448. return( id == _m.id );
  449. }
  450. int id;
  451. private:
  452. std::vector<std::string> data;
  453. friend class RemotePluginBase;
  454. } ;
  455. #ifdef SYNC_WITH_SHM_FIFO
  456. RemotePluginBase( shmFifo * _in, shmFifo * _out );
  457. #else
  458. RemotePluginBase();
  459. #endif
  460. virtual ~RemotePluginBase();
  461. #ifdef SYNC_WITH_SHM_FIFO
  462. void reset( shmFifo *in, shmFifo *out )
  463. {
  464. delete m_in;
  465. delete m_out;
  466. m_in = in;
  467. m_out = out;
  468. }
  469. #endif
  470. int sendMessage( const message & _m );
  471. message receiveMessage();
  472. inline bool isInvalid() const
  473. {
  474. #ifdef SYNC_WITH_SHM_FIFO
  475. return m_in->isInvalid() || m_out->isInvalid();
  476. #else
  477. return m_invalid;
  478. #endif
  479. }
  480. message waitForMessage( const message & _m,
  481. bool _busy_waiting = false );
  482. inline message fetchAndProcessNextMessage()
  483. {
  484. message m = receiveMessage();
  485. processMessage( m );
  486. return m;
  487. }
  488. #ifndef SYNC_WITH_SHM_FIFO
  489. inline int32_t readInt()
  490. {
  491. int32_t i;
  492. read( &i, sizeof( i ) );
  493. return i;
  494. }
  495. inline void writeInt( const int32_t & _i )
  496. {
  497. write( &_i, sizeof( _i ) );
  498. }
  499. inline std::string readString()
  500. {
  501. const int len = readInt();
  502. if( len )
  503. {
  504. char * sc = new char[len + 1];
  505. read( sc, len );
  506. sc[len] = 0;
  507. std::string s( sc );
  508. delete[] sc;
  509. return s;
  510. }
  511. return std::string();
  512. }
  513. inline void writeString( const std::string & _s )
  514. {
  515. const int len = _s.size();
  516. writeInt( len );
  517. write( _s.c_str(), len );
  518. }
  519. #endif
  520. #ifndef BUILD_REMOTE_PLUGIN_CLIENT
  521. inline bool messagesLeft()
  522. {
  523. #ifdef SYNC_WITH_SHM_FIFO
  524. return m_in->messagesLeft();
  525. #else
  526. struct pollfd pollin;
  527. pollin.fd = m_socket;
  528. pollin.events = POLLIN;
  529. if ( poll( &pollin, 1, 0 ) == -1 )
  530. {
  531. qWarning( "Unexpected poll error." );
  532. }
  533. return pollin.revents & POLLIN;
  534. #endif
  535. }
  536. inline void fetchAndProcessAllMessages()
  537. {
  538. while( messagesLeft() )
  539. {
  540. fetchAndProcessNextMessage();
  541. }
  542. }
  543. static bool isMainThreadWaiting()
  544. {
  545. return waitDepthCounter() > 0;
  546. }
  547. #endif
  548. virtual bool processMessage( const message & _m ) = 0;
  549. protected:
  550. #ifdef SYNC_WITH_SHM_FIFO
  551. inline const shmFifo * in() const
  552. {
  553. return m_in;
  554. }
  555. inline const shmFifo * out() const
  556. {
  557. return m_out;
  558. }
  559. #endif
  560. inline void invalidate()
  561. {
  562. #ifdef SYNC_WITH_SHM_FIFO
  563. m_in->invalidate();
  564. m_out->invalidate();
  565. m_in->messageSent();
  566. #else
  567. m_invalid = true;
  568. #endif
  569. }
  570. #ifndef SYNC_WITH_SHM_FIFO
  571. int m_socket;
  572. #endif
  573. private:
  574. #ifndef BUILD_REMOTE_PLUGIN_CLIENT
  575. static int & waitDepthCounter()
  576. {
  577. static int waitDepth = 0;
  578. return waitDepth;
  579. }
  580. #endif
  581. #ifdef SYNC_WITH_SHM_FIFO
  582. shmFifo * m_in;
  583. shmFifo * m_out;
  584. #else
  585. void read( void * _buf, int _len )
  586. {
  587. if( isInvalid() )
  588. {
  589. memset( _buf, 0, _len );
  590. return;
  591. }
  592. char * buf = (char *) _buf;
  593. int remaining = _len;
  594. while ( remaining )
  595. {
  596. ssize_t nread = ::read( m_socket, buf, remaining );
  597. switch ( nread )
  598. {
  599. case -1:
  600. fprintf( stderr,
  601. "Error while reading.\n" );
  602. case 0:
  603. invalidate();
  604. memset( _buf, 0, _len );
  605. return;
  606. }
  607. buf += nread;
  608. remaining -= nread;
  609. }
  610. }
  611. void write( const void * _buf, int _len )
  612. {
  613. if( isInvalid() )
  614. {
  615. return;
  616. }
  617. const char * buf = (const char *) _buf;
  618. int remaining = _len;
  619. while ( remaining )
  620. {
  621. ssize_t nwritten = ::write( m_socket, buf, remaining );
  622. switch ( nwritten )
  623. {
  624. case -1:
  625. fprintf( stderr,
  626. "Error while writing.\n" );
  627. case 0:
  628. invalidate();
  629. return;
  630. }
  631. buf += nwritten;
  632. remaining -= nwritten;
  633. }
  634. }
  635. bool m_invalid;
  636. pthread_mutex_t m_receiveMutex;
  637. pthread_mutex_t m_sendMutex;
  638. #endif
  639. } ;
  640. #ifndef BUILD_REMOTE_PLUGIN_CLIENT
  641. class RemotePlugin;
  642. class ProcessWatcher : public QThread
  643. {
  644. public:
  645. ProcessWatcher( RemotePlugin * );
  646. virtual ~ProcessWatcher()
  647. {
  648. }
  649. void stop()
  650. {
  651. m_quit = true;
  652. quit();
  653. }
  654. void reset()
  655. {
  656. m_quit = false;
  657. }
  658. private:
  659. virtual void run();
  660. RemotePlugin * m_plugin;
  661. volatile bool m_quit;
  662. } ;
  663. class EXPORT RemotePlugin : public QObject, public RemotePluginBase
  664. {
  665. Q_OBJECT
  666. public:
  667. RemotePlugin();
  668. virtual ~RemotePlugin();
  669. inline bool isRunning()
  670. {
  671. #ifdef DEBUG_REMOTE_PLUGIN
  672. return true;
  673. #else
  674. return m_process.state() != QProcess::NotRunning;
  675. #endif
  676. }
  677. bool init( const QString &pluginExecutable, bool waitForInitDoneMsg, QStringList extraArgs = {} );
  678. inline void waitForHostInfoGotten()
  679. {
  680. m_failed = waitForMessage( IdHostInfoGotten ).id
  681. != IdHostInfoGotten;
  682. }
  683. inline void waitForInitDone( bool _busyWaiting = true )
  684. {
  685. m_failed = waitForMessage( IdInitDone, _busyWaiting ).id != IdInitDone;
  686. }
  687. virtual bool processMessage( const message & _m );
  688. bool process( const sampleFrame * _in_buf, sampleFrame * _out_buf );
  689. void processMidiEvent( const MidiEvent&, const f_cnt_t _offset );
  690. void updateSampleRate( sample_rate_t _sr )
  691. {
  692. lock();
  693. sendMessage( message( IdSampleRateInformation ).addInt( _sr ) );
  694. waitForMessage( IdInformationUpdated, true );
  695. unlock();
  696. }
  697. virtual void toggleUI()
  698. {
  699. lock();
  700. sendMessage( IdToggleUI );
  701. unlock();
  702. }
  703. int isUIVisible()
  704. {
  705. lock();
  706. sendMessage( IdIsUIVisible );
  707. unlock();
  708. message m = waitForMessage( IdIsUIVisible );
  709. return m.id != IdIsUIVisible ? -1 : m.getInt() ? 1 : 0;
  710. }
  711. inline bool failed() const
  712. {
  713. return m_failed;
  714. }
  715. inline void lock()
  716. {
  717. m_commMutex.lock();
  718. }
  719. inline void unlock()
  720. {
  721. m_commMutex.unlock();
  722. }
  723. public slots:
  724. virtual void showUI();
  725. virtual void hideUI();
  726. protected:
  727. inline void setSplittedChannels( bool _on )
  728. {
  729. m_splitChannels = _on;
  730. }
  731. private:
  732. void resizeSharedProcessingMemory();
  733. bool m_failed;
  734. QProcess m_process;
  735. ProcessWatcher m_watcher;
  736. QString m_exec;
  737. QStringList m_args;
  738. QMutex m_commMutex;
  739. bool m_splitChannels;
  740. #ifdef USE_QT_SHMEM
  741. QSharedMemory m_shmObj;
  742. #else
  743. int m_shmID;
  744. #endif
  745. size_t m_shmSize;
  746. float * m_shm;
  747. int m_inputCount;
  748. int m_outputCount;
  749. #ifndef SYNC_WITH_SHM_FIFO
  750. int m_server;
  751. QString m_socketFile;
  752. #endif
  753. friend class ProcessWatcher;
  754. private slots:
  755. void processFinished( int exitCode, QProcess::ExitStatus exitStatus );
  756. } ;
  757. #endif
  758. #ifdef BUILD_REMOTE_PLUGIN_CLIENT
  759. class RemotePluginClient : public RemotePluginBase
  760. {
  761. public:
  762. #ifdef SYNC_WITH_SHM_FIFO
  763. RemotePluginClient( key_t _shm_in, key_t _shm_out );
  764. #else
  765. RemotePluginClient( const char * socketPath );
  766. #endif
  767. virtual ~RemotePluginClient();
  768. #ifdef USE_QT_SHMEM
  769. VstSyncData * getQtVSTshm();
  770. #endif
  771. virtual bool processMessage( const message & _m );
  772. virtual void process( const sampleFrame * _in_buf,
  773. sampleFrame * _out_buf ) = 0;
  774. virtual void processMidiEvent( const MidiEvent&, const f_cnt_t /* _offset */ )
  775. {
  776. }
  777. inline float * sharedMemory()
  778. {
  779. return m_shm;
  780. }
  781. virtual void updateSampleRate()
  782. {
  783. }
  784. virtual void updateBufferSize()
  785. {
  786. }
  787. inline sample_rate_t sampleRate() const
  788. {
  789. return m_sampleRate;
  790. }
  791. inline fpp_t bufferSize() const
  792. {
  793. return m_bufferSize;
  794. }
  795. void setInputCount( int _i )
  796. {
  797. m_inputCount = _i;
  798. sendMessage( message( IdChangeInputCount ).addInt( _i ) );
  799. }
  800. void setOutputCount( int _i )
  801. {
  802. m_outputCount = _i;
  803. sendMessage( message( IdChangeOutputCount ).addInt( _i ) );
  804. }
  805. void setInputOutputCount( int i, int o )
  806. {
  807. m_inputCount = i;
  808. m_outputCount = o;
  809. sendMessage( message( IdChangeInputOutputCount )
  810. .addInt( i )
  811. .addInt( o ) );
  812. }
  813. virtual int inputCount() const
  814. {
  815. return m_inputCount;
  816. }
  817. virtual int outputCount() const
  818. {
  819. return m_outputCount;
  820. }
  821. void debugMessage( const std::string & _s )
  822. {
  823. sendMessage( message( IdDebugMessage ).addString( _s ) );
  824. }
  825. private:
  826. void setShmKey( key_t _key, int _size );
  827. void doProcessing();
  828. #ifdef USE_QT_SHMEM
  829. QSharedMemory m_shmObj;
  830. QSharedMemory m_shmQtID;
  831. #endif
  832. VstSyncData * m_vstSyncData;
  833. float * m_shm;
  834. int m_inputCount;
  835. int m_outputCount;
  836. sample_rate_t m_sampleRate;
  837. fpp_t m_bufferSize;
  838. } ;
  839. #endif
  840. #ifdef COMPILE_REMOTE_PLUGIN_BASE
  841. #ifndef BUILD_REMOTE_PLUGIN_CLIENT
  842. #include <QtCore/QCoreApplication>
  843. #endif
  844. #ifdef SYNC_WITH_SHM_FIFO
  845. RemotePluginBase::RemotePluginBase( shmFifo * _in, shmFifo * _out ) :
  846. m_in( _in ),
  847. m_out( _out )
  848. #else
  849. RemotePluginBase::RemotePluginBase() :
  850. m_socket( -1 ),
  851. m_invalid( false )
  852. #endif
  853. {
  854. #ifdef LMMS_HAVE_LOCALE_H
  855. // make sure, we're using common ways to print/scan
  856. // floats to/from strings (',' vs. '.' for decimal point etc.)
  857. setlocale( LC_NUMERIC, "C" );
  858. #endif
  859. #ifndef SYNC_WITH_SHM_FIFO
  860. pthread_mutex_init( &m_receiveMutex, NULL );
  861. pthread_mutex_init( &m_sendMutex, NULL );
  862. #endif
  863. }
  864. RemotePluginBase::~RemotePluginBase()
  865. {
  866. #ifdef SYNC_WITH_SHM_FIFO
  867. delete m_in;
  868. delete m_out;
  869. #else
  870. pthread_mutex_destroy( &m_receiveMutex );
  871. pthread_mutex_destroy( &m_sendMutex );
  872. #endif
  873. }
  874. int RemotePluginBase::sendMessage( const message & _m )
  875. {
  876. #ifdef SYNC_WITH_SHM_FIFO
  877. m_out->lock();
  878. m_out->writeInt( _m.id );
  879. m_out->writeInt( _m.data.size() );
  880. int j = 8;
  881. for( unsigned int i = 0; i < _m.data.size(); ++i )
  882. {
  883. m_out->writeString( _m.data[i] );
  884. j += 4 + _m.data[i].size();
  885. }
  886. m_out->unlock();
  887. m_out->messageSent();
  888. #else
  889. pthread_mutex_lock( &m_sendMutex );
  890. writeInt( _m.id );
  891. writeInt( _m.data.size() );
  892. int j = 8;
  893. for( unsigned int i = 0; i < _m.data.size(); ++i )
  894. {
  895. writeString( _m.data[i] );
  896. j += 4 + _m.data[i].size();
  897. }
  898. pthread_mutex_unlock( &m_sendMutex );
  899. #endif
  900. return j;
  901. }
  902. RemotePluginBase::message RemotePluginBase::receiveMessage()
  903. {
  904. #ifdef SYNC_WITH_SHM_FIFO
  905. m_in->waitForMessage();
  906. m_in->lock();
  907. message m;
  908. m.id = m_in->readInt();
  909. const int s = m_in->readInt();
  910. for( int i = 0; i < s; ++i )
  911. {
  912. m.data.push_back( m_in->readString() );
  913. }
  914. m_in->unlock();
  915. #else
  916. pthread_mutex_lock( &m_receiveMutex );
  917. message m;
  918. m.id = readInt();
  919. const int s = readInt();
  920. for( int i = 0; i < s; ++i )
  921. {
  922. m.data.push_back( readString() );
  923. }
  924. pthread_mutex_unlock( &m_receiveMutex );
  925. #endif
  926. return m;
  927. }
  928. RemotePluginBase::message RemotePluginBase::waitForMessage(
  929. const message & _wm,
  930. bool _busy_waiting )
  931. {
  932. #ifndef BUILD_REMOTE_PLUGIN_CLIENT
  933. if( _busy_waiting )
  934. {
  935. // No point processing events outside of the main thread
  936. _busy_waiting = QThread::currentThread() ==
  937. QCoreApplication::instance()->thread();
  938. }
  939. struct WaitDepthCounter
  940. {
  941. WaitDepthCounter( int & depth, bool busy ) :
  942. m_depth( depth ),
  943. m_busy( busy )
  944. {
  945. if( m_busy ) { ++m_depth; }
  946. }
  947. ~WaitDepthCounter()
  948. {
  949. if( m_busy ) { --m_depth; }
  950. }
  951. int & m_depth;
  952. bool m_busy;
  953. };
  954. WaitDepthCounter wdc( waitDepthCounter(), _busy_waiting );
  955. #endif
  956. while( !isInvalid() )
  957. {
  958. #ifndef BUILD_REMOTE_PLUGIN_CLIENT
  959. if( _busy_waiting && !messagesLeft() )
  960. {
  961. QCoreApplication::processEvents(
  962. QEventLoop::ExcludeUserInputEvents, 50 );
  963. continue;
  964. }
  965. #endif
  966. message m = receiveMessage();
  967. processMessage( m );
  968. if( m.id == _wm.id )
  969. {
  970. return m;
  971. }
  972. else if( m.id == IdUndefined )
  973. {
  974. return m;
  975. }
  976. }
  977. return message();
  978. }
  979. #endif
  980. #ifdef BUILD_REMOTE_PLUGIN_CLIENT
  981. #ifdef SYNC_WITH_SHM_FIFO
  982. RemotePluginClient::RemotePluginClient( key_t _shm_in, key_t _shm_out ) :
  983. RemotePluginBase( new shmFifo( _shm_in ), new shmFifo( _shm_out ) ),
  984. #else
  985. RemotePluginClient::RemotePluginClient( const char * socketPath ) :
  986. RemotePluginBase(),
  987. #endif
  988. #ifdef USE_QT_SHMEM
  989. m_shmObj(),
  990. m_shmQtID( "/usr/bin/lmms" ),
  991. #endif
  992. m_vstSyncData( NULL ),
  993. m_shm( NULL ),
  994. m_inputCount( 0 ),
  995. m_outputCount( 0 ),
  996. m_sampleRate( 44100 ),
  997. m_bufferSize( 0 )
  998. {
  999. #ifndef SYNC_WITH_SHM_FIFO
  1000. struct sockaddr_un sa;
  1001. sa.sun_family = AF_LOCAL;
  1002. size_t length = strlen( socketPath );
  1003. if ( length >= sizeof sa.sun_path )
  1004. {
  1005. length = sizeof sa.sun_path - 1;
  1006. fprintf( stderr, "Socket path too long.\n" );
  1007. }
  1008. memcpy( sa.sun_path, socketPath, length );
  1009. sa.sun_path[length] = '\0';
  1010. m_socket = socket( PF_LOCAL, SOCK_STREAM, 0 );
  1011. if ( m_socket == -1 )
  1012. {
  1013. fprintf( stderr, "Could not connect to local server.\n" );
  1014. }
  1015. if ( ::connect( m_socket, (struct sockaddr *) &sa, sizeof sa ) == -1 )
  1016. {
  1017. fprintf( stderr, "Could not connect to local server.\n" );
  1018. }
  1019. #endif
  1020. #ifdef USE_QT_SHMEM
  1021. if( m_shmQtID.attach( QSharedMemory::ReadOnly ) )
  1022. {
  1023. m_vstSyncData = (VstSyncData *) m_shmQtID.data();
  1024. m_bufferSize = m_vstSyncData->m_bufferSize;
  1025. m_sampleRate = m_vstSyncData->m_sampleRate;
  1026. sendMessage( IdHostInfoGotten );
  1027. return;
  1028. }
  1029. #else
  1030. key_t key;
  1031. int m_shmID;
  1032. if( ( key = ftok( VST_SNC_SHM_KEY_FILE, 'R' ) ) == -1 )
  1033. {
  1034. perror( "RemotePluginClient::ftok" );
  1035. }
  1036. else
  1037. { // connect to shared memory segment
  1038. if( ( m_shmID = shmget( key, 0, 0 ) ) == -1 )
  1039. {
  1040. perror( "RemotePluginClient::shmget" );
  1041. }
  1042. else
  1043. { // attach segment
  1044. m_vstSyncData = (VstSyncData *)shmat(m_shmID, 0, 0);
  1045. if( m_vstSyncData == (VstSyncData *)( -1 ) )
  1046. {
  1047. perror( "RemotePluginClient::shmat" );
  1048. }
  1049. else
  1050. {
  1051. m_bufferSize = m_vstSyncData->m_bufferSize;
  1052. m_sampleRate = m_vstSyncData->m_sampleRate;
  1053. sendMessage( IdHostInfoGotten );
  1054. // detach segment
  1055. if( shmdt(m_vstSyncData) == -1 )
  1056. {
  1057. perror("RemotePluginClient::shmdt");
  1058. }
  1059. return;
  1060. }
  1061. }
  1062. }
  1063. #endif
  1064. // if attaching shared memory fails
  1065. sendMessage( IdSampleRateInformation );
  1066. sendMessage( IdBufferSizeInformation );
  1067. if( waitForMessage( IdBufferSizeInformation ).id
  1068. != IdBufferSizeInformation )
  1069. {
  1070. fprintf( stderr, "Could not get buffer size information\n" );
  1071. }
  1072. sendMessage( IdHostInfoGotten );
  1073. }
  1074. RemotePluginClient::~RemotePluginClient()
  1075. {
  1076. #ifdef USE_QT_SHMEM
  1077. m_shmQtID.detach();
  1078. #endif
  1079. sendMessage( IdQuit );
  1080. #ifndef USE_QT_SHMEM
  1081. shmdt( m_shm );
  1082. #endif
  1083. #ifndef SYNC_WITH_SHM_FIFO
  1084. if ( close( m_socket ) == -1)
  1085. {
  1086. fprintf( stderr, "Error freeing resources.\n" );
  1087. }
  1088. #endif
  1089. }
  1090. #ifdef USE_QT_SHMEM
  1091. VstSyncData * RemotePluginClient::getQtVSTshm()
  1092. {
  1093. return m_vstSyncData;
  1094. }
  1095. #endif
  1096. bool RemotePluginClient::processMessage( const message & _m )
  1097. {
  1098. message reply_message( _m.id );
  1099. bool reply = false;
  1100. switch( _m.id )
  1101. {
  1102. case IdUndefined:
  1103. return false;
  1104. case IdSampleRateInformation:
  1105. m_sampleRate = _m.getInt();
  1106. updateSampleRate();
  1107. reply_message.id = IdInformationUpdated;
  1108. reply = true;
  1109. break;
  1110. case IdBufferSizeInformation:
  1111. // Should LMMS gain the ability to change buffer size
  1112. // without a restart, it must wait for this message to
  1113. // complete processing or else risk VST crashes
  1114. m_bufferSize = _m.getInt();
  1115. updateBufferSize();
  1116. break;
  1117. case IdQuit:
  1118. return false;
  1119. case IdMidiEvent:
  1120. processMidiEvent(
  1121. MidiEvent( static_cast<MidiEventTypes>(
  1122. _m.getInt( 0 ) ),
  1123. _m.getInt( 1 ),
  1124. _m.getInt( 2 ),
  1125. _m.getInt( 3 ) ),
  1126. _m.getInt( 4 ) );
  1127. break;
  1128. case IdStartProcessing:
  1129. doProcessing();
  1130. reply_message.id = IdProcessingDone;
  1131. reply = true;
  1132. break;
  1133. case IdChangeSharedMemoryKey:
  1134. setShmKey( _m.getInt( 0 ), _m.getInt( 1 ) );
  1135. break;
  1136. case IdInitDone:
  1137. break;
  1138. default:
  1139. {
  1140. char buf[64];
  1141. sprintf( buf, "undefined message: %d\n", (int) _m.id );
  1142. debugMessage( buf );
  1143. break;
  1144. }
  1145. }
  1146. if( reply )
  1147. {
  1148. sendMessage( reply_message );
  1149. }
  1150. return true;
  1151. }
  1152. void RemotePluginClient::setShmKey( key_t _key, int _size )
  1153. {
  1154. #ifdef USE_QT_SHMEM
  1155. m_shmObj.setKey( QString::number( _key ) );
  1156. if( m_shmObj.attach() || m_shmObj.error() == QSharedMemory::NoError )
  1157. {
  1158. m_shm = (float *) m_shmObj.data();
  1159. }
  1160. else
  1161. {
  1162. char buf[64];
  1163. sprintf( buf, "failed getting shared memory: %d\n", m_shmObj.error() );
  1164. debugMessage( buf );
  1165. }
  1166. #else
  1167. if( m_shm != NULL )
  1168. {
  1169. shmdt( m_shm );
  1170. m_shm = NULL;
  1171. }
  1172. // only called for detaching SHM?
  1173. if( _key == 0 )
  1174. {
  1175. return;
  1176. }
  1177. int shm_id = shmget( _key, _size, 0 );
  1178. if( shm_id == -1 )
  1179. {
  1180. debugMessage( "failed getting shared memory\n" );
  1181. }
  1182. else
  1183. {
  1184. m_shm = (float *) shmat( shm_id, 0, 0 );
  1185. }
  1186. #endif
  1187. }
  1188. void RemotePluginClient::doProcessing()
  1189. {
  1190. if( m_shm != NULL )
  1191. {
  1192. process( (sampleFrame *)( m_inputCount > 0 ? m_shm : NULL ),
  1193. (sampleFrame *)( m_shm +
  1194. ( m_inputCount*m_bufferSize ) ) );
  1195. }
  1196. else
  1197. {
  1198. debugMessage( "doProcessing(): have no shared memory!\n" );
  1199. }
  1200. }
  1201. #endif
  1202. #define QSTR_TO_STDSTR(s) std::string( s.toUtf8().constData() )
  1203. #endif