RemotePlugin.h 25 KB

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