jack2 codebase
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

884 lines
36KB

  1. /*
  2. Copyright (C) 2001 Paul Davis
  3. Copyright (C) 2008 Romain Moret at Grame
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. */
  16. #include "JackNetDriver.h"
  17. #include "JackEngineControl.h"
  18. #include "JackClientControl.h"
  19. #include "JackGraphManager.h"
  20. #include "JackDriverLoader.h"
  21. #include "JackThreadedDriver.h"
  22. #include "JackWaitThreadedDriver.h"
  23. #include "JackException.h"
  24. #define DEFAULT_MULTICAST_IP "225.3.19.154"
  25. #define DEFAULT_PORT 19000
  26. using namespace std;
  27. namespace Jack
  28. {
  29. JackNetDriver::JackNetDriver ( const char* name, const char* alias, JackLockedEngine* engine, JackSynchro* table,
  30. const char* ip, int port, int mtu, int midi_input_ports, int midi_output_ports,
  31. const char* net_name, uint transport_sync, char network_mode )
  32. : JackAudioDriver ( name, alias, engine, table ), fSocket ( ip, port )
  33. {
  34. jack_log ( "JackNetDriver::JackNetDriver ip %s, port %d", ip, port );
  35. fMulticastIP = new char[strlen ( ip ) + 1];
  36. strcpy ( fMulticastIP, ip );
  37. fParams.fMtu = mtu;
  38. fParams.fSendMidiChannels = midi_input_ports;
  39. fParams.fReturnMidiChannels = midi_output_ports;
  40. strcpy ( fParams.fName, net_name );
  41. fSocket.GetName ( fParams.fSlaveNetName );
  42. fParams.fTransportSync = transport_sync;
  43. fParams.fNetworkMode = network_mode;
  44. #ifdef JACK_MONITOR
  45. fNetTimeMon = NULL;
  46. fNetTimeMeasure = NULL;
  47. #endif
  48. }
  49. JackNetDriver::~JackNetDriver()
  50. {
  51. fSocket.Close();
  52. SocketAPIEnd();
  53. delete fNetAudioCaptureBuffer;
  54. delete fNetAudioPlaybackBuffer;
  55. delete fNetMidiCaptureBuffer;
  56. delete fNetMidiPlaybackBuffer;
  57. delete[] fTxBuffer;
  58. delete[] fRxBuffer;
  59. delete[] fMulticastIP;
  60. delete[] fMidiCapturePortList;
  61. delete[] fMidiPlaybackPortList;
  62. #ifdef JACK_MONITOR
  63. delete[] fNetTimeMeasure;
  64. delete fNetTimeMon;
  65. #endif
  66. }
  67. //*************************************initialization***********************************************************************
  68. int JackNetDriver::Open ( jack_nframes_t buffer_size, jack_nframes_t samplerate, bool capturing, bool playing,
  69. int inchannels, int outchannels, bool monitor,
  70. const char* capture_driver_name, const char* playback_driver_name,
  71. jack_nframes_t capture_latency, jack_nframes_t playback_latency )
  72. {
  73. int res = JackAudioDriver::Open ( buffer_size, samplerate, capturing, playing, inchannels, outchannels, monitor,
  74. capture_driver_name, playback_driver_name, capture_latency, playback_latency );
  75. fEngineControl->fPeriod = 0;
  76. fEngineControl->fComputation = 500 * 1000;
  77. fEngineControl->fConstraint = 500 * 1000;
  78. return res;
  79. }
  80. #ifdef JACK_MONITOR
  81. int JackNetDriver::Close()
  82. {
  83. if ( fNetTimeMon )
  84. fNetTimeMon->Save();
  85. if ( fCycleTimeMon )
  86. fCycleTimeMon->Save();
  87. return JackDriver::Close();
  88. }
  89. #endif
  90. int JackNetDriver::Attach()
  91. {
  92. return 0;
  93. }
  94. int JackNetDriver::Detach()
  95. {
  96. return 0;
  97. }
  98. bool JackNetDriver::Init()
  99. {
  100. jack_log ( "JackNetDriver::Init()" );
  101. //new loading, but existing socket, restart the driver
  102. if ( fSocket.IsSocket() )
  103. Restart();
  104. //set the parameters to send
  105. strcpy ( fParams.fPacketType, "params" );
  106. fParams.fProtocolVersion = 'a';
  107. SetPacketType ( &fParams, SLAVE_AVAILABLE );
  108. fParams.fSendAudioChannels = fCaptureChannels;
  109. fParams.fReturnAudioChannels = fPlaybackChannels;
  110. fParams.fSlaveSyncMode = fEngineControl->fSyncMode;
  111. //is transport sync ?
  112. if ( fParams.fTransportSync )
  113. jack_info ( "NetDriver started with Master's Transport Sync." );
  114. //init loop : get a master and start, do it until connection is ok
  115. net_status_t status;
  116. do
  117. {
  118. //first, get a master, do it until a valid connection is running
  119. jack_info ( "Initializing Net Driver..." );
  120. do
  121. {
  122. status = GetNetMaster();
  123. if ( status == NET_SOCKET_ERROR )
  124. return false;
  125. }
  126. while ( status != NET_CONNECTED );
  127. //then tell the master we are ready
  128. jack_info ( "Initializing connection with %s...", fParams.fMasterNetName );
  129. status = SendMasterStartSync();
  130. if ( status == NET_ERROR )
  131. return false;
  132. }
  133. while ( status != NET_ROLLING );
  134. //driver parametering
  135. if ( SetParams() )
  136. {
  137. jack_error ( "Fatal error : can't alloc net driver ports." );
  138. return false;
  139. }
  140. //init done, display parameters
  141. SessionParamsDisplay ( &fParams );
  142. return true;
  143. }
  144. net_status_t JackNetDriver::GetNetMaster()
  145. {
  146. jack_log ( "JackNetDriver::GetNetMaster()" );
  147. //utility
  148. session_params_t params;
  149. int us_timeout = 2000000;
  150. int rx_bytes = 0;
  151. unsigned char loop = 0;
  152. //socket
  153. if ( fSocket.NewSocket() == SOCKET_ERROR )
  154. {
  155. jack_error ( "Fatal error : network unreachable - %s", StrError ( NET_ERROR_CODE ) );
  156. return NET_SOCKET_ERROR;
  157. }
  158. //bind the socket
  159. if ( fSocket.Bind() == SOCKET_ERROR )
  160. jack_error ( "Can't bind the socket : %s", StrError ( NET_ERROR_CODE ) );
  161. //timeout on receive
  162. if ( fSocket.SetTimeOut ( us_timeout ) == SOCKET_ERROR )
  163. jack_error ( "Can't set timeout : %s", StrError ( NET_ERROR_CODE ) );
  164. //disable local loop
  165. if ( fSocket.SetOption ( IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof ( loop ) ) == SOCKET_ERROR )
  166. jack_error ( "Can't disable multicast loop : %s", StrError ( NET_ERROR_CODE ) );
  167. //send 'AVAILABLE' until 'SLAVE_SETUP' received
  168. jack_info ( "Waiting for a master..." );
  169. do
  170. {
  171. //send 'available'
  172. if ( fSocket.SendTo ( &fParams, sizeof ( session_params_t ), 0, fMulticastIP ) == SOCKET_ERROR )
  173. jack_error ( "Error in data send : %s", StrError ( NET_ERROR_CODE ) );
  174. //filter incoming packets : don't exit while no error is detected
  175. rx_bytes = fSocket.CatchHost ( &params, sizeof ( session_params_t ), 0 );
  176. if ( ( rx_bytes == SOCKET_ERROR ) && ( fSocket.GetError() != NET_NO_DATA ) )
  177. {
  178. jack_error ( "Can't receive : %s", StrError ( NET_ERROR_CODE ) );
  179. return NET_RECV_ERROR;
  180. }
  181. }
  182. while ( strcmp ( params.fPacketType, fParams.fPacketType ) && ( GetPacketType ( &params ) != SLAVE_SETUP ) );
  183. //connect the socket
  184. if ( fSocket.Connect() == SOCKET_ERROR )
  185. {
  186. jack_error ( "Error in connect : %s", StrError ( NET_ERROR_CODE ) );
  187. return NET_CONNECT_ERROR;
  188. }
  189. //everything is OK, copy parameters and return
  190. fParams = params;
  191. return NET_CONNECTED;
  192. }
  193. net_status_t JackNetDriver::SendMasterStartSync()
  194. {
  195. jack_log ( "JackNetDriver::GetNetMasterStartSync()" );
  196. //tell the master to start
  197. SetPacketType ( &fParams, START_MASTER );
  198. if ( fSocket.Send ( &fParams, sizeof ( session_params_t ), 0 ) == SOCKET_ERROR )
  199. {
  200. jack_error ( "Error in send : %s", StrError ( NET_ERROR_CODE ) );
  201. return ( fSocket.GetError() == NET_CONN_ERROR ) ? NET_ERROR : NET_SEND_ERROR;
  202. }
  203. return NET_ROLLING;
  204. }
  205. void JackNetDriver::Restart()
  206. {
  207. jack_log ( "JackNetDriver::Restart" );
  208. jack_info ( "Restarting driver..." );
  209. delete[] fTxBuffer;
  210. fTxBuffer = NULL;
  211. delete[] fRxBuffer;
  212. fRxBuffer = NULL;
  213. delete fNetAudioCaptureBuffer;
  214. fNetAudioCaptureBuffer = NULL;
  215. delete fNetAudioPlaybackBuffer;
  216. fNetAudioPlaybackBuffer = NULL;
  217. delete fNetMidiCaptureBuffer;
  218. fNetMidiCaptureBuffer = NULL;
  219. delete fNetMidiPlaybackBuffer;
  220. fNetMidiPlaybackBuffer = NULL;
  221. FreePorts();
  222. delete[] fMidiCapturePortList;
  223. fMidiCapturePortList = NULL;
  224. delete[] fMidiPlaybackPortList;
  225. fMidiPlaybackPortList = NULL;
  226. #ifdef JACK_MONITOR
  227. delete[] fNetTimeMeasure;
  228. fNetTimeMeasure = NULL;
  229. delete fNetTimeMon;
  230. fNetTimeMon = NULL;
  231. delete fCycleTimeMon;
  232. fCycleTimeMon = NULL;
  233. #endif
  234. }
  235. int JackNetDriver::SetParams()
  236. {
  237. fNSubProcess = fParams.fPeriodSize / fParams.fFramesPerPacket;
  238. JackAudioDriver::SetBufferSize ( fParams.fPeriodSize );
  239. JackAudioDriver::SetSampleRate ( fParams.fSampleRate );
  240. JackDriver::NotifyBufferSize ( fParams.fPeriodSize );
  241. JackDriver::NotifySampleRate ( fParams.fSampleRate );
  242. //allocate midi ports lists
  243. fMidiCapturePortList = new jack_port_id_t [fParams.fSendMidiChannels];
  244. fMidiPlaybackPortList = new jack_port_id_t [fParams.fReturnMidiChannels];
  245. //register jack ports
  246. if ( AllocPorts() != 0 )
  247. {
  248. jack_error ( "Can't allocate ports." );
  249. return -1;
  250. }
  251. //TX header init
  252. strcpy ( fTxHeader.fPacketType, "header" );
  253. fTxHeader.fDataStream = 'r';
  254. fTxHeader.fID = fParams.fID;
  255. fTxHeader.fCycle = 0;
  256. fTxHeader.fSubCycle = 0;
  257. fTxHeader.fMidiDataSize = 0;
  258. fTxHeader.fBitdepth = fParams.fBitdepth;
  259. //RX header init
  260. strcpy ( fRxHeader.fPacketType, "header" );
  261. fRxHeader.fDataStream = 's';
  262. fRxHeader.fID = fParams.fID;
  263. fRxHeader.fCycle = 0;
  264. fRxHeader.fSubCycle = 0;
  265. fRxHeader.fMidiDataSize = 0;
  266. fRxHeader.fBitdepth = fParams.fBitdepth;
  267. //network buffers
  268. fTxBuffer = new char[fParams.fMtu];
  269. fRxBuffer = new char[fParams.fMtu];
  270. //net audio/midi buffers
  271. fTxData = fTxBuffer + sizeof ( packet_header_t );
  272. fRxData = fRxBuffer + sizeof ( packet_header_t );
  273. //midi net buffers
  274. fNetMidiCaptureBuffer = new NetMidiBuffer ( &fParams, fParams.fSendMidiChannels, fRxData );
  275. fNetMidiPlaybackBuffer = new NetMidiBuffer ( &fParams, fParams.fReturnMidiChannels, fTxData );
  276. //audio net buffers
  277. fNetAudioCaptureBuffer = new NetAudioBuffer ( &fParams, fParams.fSendAudioChannels, fRxData );
  278. fNetAudioPlaybackBuffer = new NetAudioBuffer ( &fParams, fParams.fReturnAudioChannels, fTxData );
  279. //audio netbuffer length
  280. fAudioTxLen = sizeof ( packet_header_t ) + fNetAudioPlaybackBuffer->GetSize();
  281. fAudioRxLen = sizeof ( packet_header_t ) + fNetAudioCaptureBuffer->GetSize();
  282. //payload size
  283. fPayloadSize = fParams.fMtu - sizeof ( packet_header_t );
  284. //monitor
  285. #ifdef JACK_MONITOR
  286. string plot_name;
  287. //NetTimeMon
  288. plot_name = string ( fParams.fName );
  289. plot_name += string ( "_slave" );
  290. plot_name += ( fEngineControl->fSyncMode ) ? string ( "_sync" ) : string ( "_async" );
  291. plot_name += ( fParams.fNetworkMode == 'f' ) ? string ( "_fast-network" ) : string ( "" );
  292. fNetTimeMon = new JackGnuPlotMonitor<float> ( 128, 4, plot_name );
  293. fNetTimeMeasure = new float[4];
  294. string net_time_mon_fields[] =
  295. {
  296. string ( "end of read" ),
  297. string ( "start of write" ),
  298. string ( "sync send" ),
  299. string ( "end of write" )
  300. };
  301. string net_time_mon_options[] =
  302. {
  303. string ( "set xlabel \"audio cycles\"" ),
  304. string ( "set ylabel \"% of audio cycle\"" )
  305. };
  306. fNetTimeMon->SetPlotFile ( net_time_mon_options, 2, net_time_mon_fields, 4 );
  307. //CycleTimeMon
  308. plot_name.clear();
  309. plot_name = string ( fParams.fName );
  310. plot_name += string ( "_slave_cycle_time" );
  311. fCycleTimeMon = new JackGnuPlotMonitor<jack_time_t> ( 2048, 1, plot_name );
  312. string cycle_time_mon_field = string ( "time since last cycle" );
  313. string cycle_time_mon_options[] =
  314. {
  315. string ( "set xlabel \"audio cycles\"" ),
  316. string ( "set ylabel \"usecs\"" )
  317. };
  318. fCycleTimeMon->SetPlotFile ( cycle_time_mon_options, 2, &cycle_time_mon_field, 1 );
  319. fCycleTime = GetMicroSeconds();
  320. #endif
  321. return 0;
  322. }
  323. int JackNetDriver::AllocPorts()
  324. {
  325. jack_log ( "JackNetDriver::AllocPorts fBufferSize = %ld fSampleRate = %ld", fEngineControl->fBufferSize, fEngineControl->fSampleRate );
  326. JackPort* port;
  327. jack_port_id_t port_id;
  328. char name[JACK_CLIENT_NAME_SIZE + JACK_PORT_NAME_SIZE];
  329. char alias[JACK_CLIENT_NAME_SIZE + JACK_PORT_NAME_SIZE];
  330. unsigned long port_flags;
  331. int audio_port_index;
  332. uint midi_port_index;
  333. //audio
  334. port_flags = JackPortIsOutput | JackPortIsPhysical | JackPortIsTerminal;
  335. for ( audio_port_index = 0; audio_port_index < fCaptureChannels; audio_port_index++ )
  336. {
  337. snprintf ( alias, sizeof ( alias ) - 1, "%s:%s:out%d", fAliasName, fCaptureDriverName, audio_port_index + 1 );
  338. snprintf ( name, sizeof ( name ) - 1, "%s:capture_%d", fClientControl.fName, audio_port_index + 1 );
  339. if ( ( port_id = fGraphManager->AllocatePort ( fClientControl.fRefNum, name, JACK_DEFAULT_AUDIO_TYPE,
  340. static_cast<JackPortFlags> ( port_flags ), fEngineControl->fBufferSize ) ) == NO_PORT )
  341. {
  342. jack_error ( "driver: cannot register port for %s", name );
  343. return -1;
  344. }
  345. port = fGraphManager->GetPort ( port_id );
  346. port->SetAlias ( alias );
  347. port->SetLatency ( fEngineControl->fBufferSize );
  348. fCapturePortList[audio_port_index] = port_id;
  349. jack_log ( "JackNetDriver::AllocPorts() fCapturePortList[%d] audio_port_index = %ld fPortLatency = %ld", audio_port_index, port_id, port->GetLatency() );
  350. }
  351. port_flags = JackPortIsInput | JackPortIsPhysical | JackPortIsTerminal;
  352. for ( audio_port_index = 0; audio_port_index < fPlaybackChannels; audio_port_index++ )
  353. {
  354. snprintf ( alias, sizeof ( alias ) - 1, "%s:%s:in%d", fAliasName, fPlaybackDriverName, audio_port_index + 1 );
  355. snprintf ( name, sizeof ( name ) - 1, "%s:playback_%d",fClientControl.fName, audio_port_index + 1 );
  356. if ( ( port_id = fGraphManager->AllocatePort ( fClientControl.fRefNum, name, JACK_DEFAULT_AUDIO_TYPE,
  357. static_cast<JackPortFlags> ( port_flags ), fEngineControl->fBufferSize ) ) == NO_PORT )
  358. {
  359. jack_error ( "driver: cannot register port for %s", name );
  360. return -1;
  361. }
  362. port = fGraphManager->GetPort ( port_id );
  363. port->SetAlias ( alias );
  364. port->SetLatency ( ( fParams.fNetworkMode == 'f' ) ? 0 : fEngineControl->fBufferSize + ( ( fEngineControl->fSyncMode ) ? 0 : fEngineControl->fBufferSize ) );
  365. fPlaybackPortList[audio_port_index] = port_id;
  366. jack_log ( "JackNetDriver::AllocPorts() fPlaybackPortList[%d] audio_port_index = %ld fPortLatency = %ld", audio_port_index, port_id, port->GetLatency() );
  367. }
  368. //midi
  369. port_flags = JackPortIsOutput | JackPortIsPhysical | JackPortIsTerminal;
  370. for ( midi_port_index = 0; midi_port_index < fParams.fSendMidiChannels; midi_port_index++ )
  371. {
  372. snprintf ( alias, sizeof ( alias ) - 1, "%s:%s:out%d", fAliasName, fCaptureDriverName, midi_port_index + 1 );
  373. snprintf ( name, sizeof ( name ) - 1, "%s:midi_capture_%d", fClientControl.fName, midi_port_index + 1 );
  374. if ( ( port_id = fGraphManager->AllocatePort ( fClientControl.fRefNum, name, JACK_DEFAULT_MIDI_TYPE,
  375. static_cast<JackPortFlags> ( port_flags ), fEngineControl->fBufferSize ) ) == NO_PORT )
  376. {
  377. jack_error ( "driver: cannot register port for %s", name );
  378. return -1;
  379. }
  380. port = fGraphManager->GetPort ( port_id );
  381. port->SetLatency ( fEngineControl->fBufferSize );
  382. fMidiCapturePortList[midi_port_index] = port_id;
  383. jack_log ( "JackNetDriver::AllocPorts() fMidiCapturePortList[%d] midi_port_index = %ld fPortLatency = %ld", midi_port_index, port_id, port->GetLatency() );
  384. }
  385. port_flags = JackPortIsInput | JackPortIsPhysical | JackPortIsTerminal;
  386. for ( midi_port_index = 0; midi_port_index < fParams.fReturnMidiChannels; midi_port_index++ )
  387. {
  388. snprintf ( alias, sizeof ( alias ) - 1, "%s:%s:in%d", fAliasName, fPlaybackDriverName, midi_port_index + 1 );
  389. snprintf ( name, sizeof ( name ) - 1, "%s:midi_playback_%d", fClientControl.fName, midi_port_index + 1 );
  390. if ( ( port_id = fGraphManager->AllocatePort ( fClientControl.fRefNum, name, JACK_DEFAULT_MIDI_TYPE,
  391. static_cast<JackPortFlags> ( port_flags ), fEngineControl->fBufferSize ) ) == NO_PORT )
  392. {
  393. jack_error ( "driver: cannot register port for %s", name );
  394. return -1;
  395. }
  396. port = fGraphManager->GetPort ( port_id );
  397. port->SetLatency ( ( fParams.fNetworkMode == 'f' ) ? 0 : fEngineControl->fBufferSize + ( ( fEngineControl->fSyncMode ) ? 0 : fEngineControl->fBufferSize ) );
  398. fMidiPlaybackPortList[midi_port_index] = port_id;
  399. jack_log ( "JackNetDriver::AllocPorts() fMidiPlaybackPortList[%d] midi_port_index = %ld fPortLatency = %ld", midi_port_index, port_id, port->GetLatency() );
  400. }
  401. return 0;
  402. }
  403. int JackNetDriver::FreePorts()
  404. {
  405. jack_log ( "JackNetDriver::FreePorts" );
  406. int audio_port_index;
  407. uint midi_port_index;
  408. for ( audio_port_index = 0; audio_port_index < fCaptureChannels; audio_port_index++ )
  409. fGraphManager->ReleasePort ( fClientControl.fRefNum, fCapturePortList[audio_port_index] );
  410. for ( audio_port_index = 0; audio_port_index < fPlaybackChannels; audio_port_index++ )
  411. fGraphManager->ReleasePort ( fClientControl.fRefNum, fPlaybackPortList[audio_port_index] );
  412. for ( midi_port_index = 0; midi_port_index < fParams.fSendMidiChannels; midi_port_index++ )
  413. fGraphManager->ReleasePort ( fClientControl.fRefNum, fMidiCapturePortList[midi_port_index] );
  414. for ( midi_port_index = 0; midi_port_index < fParams.fReturnMidiChannels; midi_port_index++ )
  415. fGraphManager->ReleasePort ( fClientControl.fRefNum, fMidiPlaybackPortList[midi_port_index] );
  416. return 0;
  417. }
  418. JackMidiBuffer* JackNetDriver::GetMidiInputBuffer ( int port_index )
  419. {
  420. return static_cast<JackMidiBuffer*> ( fGraphManager->GetBuffer ( fMidiCapturePortList[port_index], fEngineControl->fBufferSize ) );
  421. }
  422. JackMidiBuffer* JackNetDriver::GetMidiOutputBuffer ( int port_index )
  423. {
  424. return static_cast<JackMidiBuffer*> ( fGraphManager->GetBuffer ( fMidiPlaybackPortList[port_index], fEngineControl->fBufferSize ) );
  425. }
  426. int JackNetDriver::SetSyncPacket()
  427. {
  428. if ( fParams.fTransportSync )
  429. {
  430. //set the TransportData
  431. //copy to TxBuffer
  432. memcpy ( fTxData, &fTransportData, sizeof ( net_transport_data_t ) );
  433. }
  434. return 0;
  435. }
  436. //***********************************network operations*************************************************************
  437. int JackNetDriver::Recv ( size_t size, int flags )
  438. {
  439. int rx_bytes = fSocket.Recv ( fRxBuffer, size, flags );
  440. //handle errors
  441. if ( rx_bytes == SOCKET_ERROR )
  442. {
  443. net_error_t error = fSocket.GetError();
  444. //no data isn't really an error in realtime processing, so just return 0
  445. if ( error == NET_NO_DATA )
  446. jack_error ( "No data, is the master still running ?" );
  447. //if a network error occurs, this exception will restart the driver
  448. else if ( error == NET_CONN_ERROR )
  449. {
  450. jack_error ( "Connection lost." );
  451. throw JackDriverException();
  452. }
  453. else
  454. jack_error ( "Fatal error in receive : %s", StrError ( NET_ERROR_CODE ) );
  455. }
  456. return rx_bytes;
  457. }
  458. int JackNetDriver::Send ( size_t size, int flags )
  459. {
  460. int tx_bytes = fSocket.Send ( fTxBuffer, size, flags );
  461. //handle errors
  462. if ( tx_bytes == SOCKET_ERROR )
  463. {
  464. net_error_t error = fSocket.GetError();
  465. //if a network error occurs, this exception will restart the driver
  466. if ( error == NET_CONN_ERROR )
  467. {
  468. jack_error ( "Connection lost." );
  469. throw JackDriverException();
  470. }
  471. else
  472. jack_error ( "Fatal error in send : %s", StrError ( NET_ERROR_CODE ) );
  473. }
  474. return tx_bytes;
  475. }
  476. //*************************************process************************************************************************
  477. int JackNetDriver::Read()
  478. {
  479. int rx_bytes;
  480. uint recvd_midi_pckt = 0;
  481. packet_header_t* rx_head = reinterpret_cast<packet_header_t*> ( fRxBuffer );
  482. fRxHeader.fIsLastPckt = 'n';
  483. uint midi_port_index;
  484. int audio_port_index;
  485. //buffers
  486. for ( midi_port_index = 0; midi_port_index < fParams.fSendMidiChannels; midi_port_index++ )
  487. fNetMidiCaptureBuffer->SetBuffer ( midi_port_index, GetMidiInputBuffer ( midi_port_index ) );
  488. for ( audio_port_index = 0; audio_port_index < fCaptureChannels; audio_port_index++ )
  489. fNetAudioCaptureBuffer->SetBuffer ( audio_port_index, GetInputBuffer ( audio_port_index ) );
  490. #ifdef JACK_MONITOR
  491. fNetTimeMeasureId = 0;
  492. #endif
  493. //receive sync (launch the cycle)
  494. do
  495. {
  496. rx_bytes = Recv ( fParams.fMtu, 0 );
  497. //connection issue, send will detect it, so don't skip the cycle (return 0)
  498. if ( rx_bytes == SOCKET_ERROR )
  499. return 0;
  500. }
  501. while ( !rx_bytes && ( rx_head->fDataType != 's' ) );
  502. //take the time at the beginning of the cycle
  503. JackDriver::CycleTakeBeginTime();
  504. #ifdef JACK_MONITOR
  505. jack_time_t cycle_time = GetMicroSeconds() - fCycleTime;
  506. fCycleTimeMon->Write ( &cycle_time );
  507. fCycleTime = GetMicroSeconds();
  508. #endif
  509. //audio, midi or sync if driver is late
  510. if ( fParams.fSendMidiChannels || fParams.fSendAudioChannels )
  511. {
  512. do
  513. {
  514. rx_bytes = Recv ( fParams.fMtu, MSG_PEEK );
  515. //error here, problem with recv, just skip the cycle (return -1)
  516. if ( rx_bytes == SOCKET_ERROR )
  517. return rx_bytes;
  518. if ( rx_bytes && ( rx_head->fDataStream == 's' ) && ( rx_head->fID == fParams.fID ) )
  519. {
  520. switch ( rx_head->fDataType )
  521. {
  522. case 'm': //midi
  523. rx_bytes = Recv ( rx_head->fPacketSize, 0 );
  524. fRxHeader.fCycle = rx_head->fCycle;
  525. fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
  526. fNetMidiCaptureBuffer->RenderFromNetwork ( rx_head->fSubCycle, rx_bytes - sizeof ( packet_header_t ) );
  527. if ( ++recvd_midi_pckt == rx_head->fNMidiPckt )
  528. fNetMidiCaptureBuffer->RenderToJackPorts();
  529. break;
  530. case 'a': //audio
  531. rx_bytes = Recv ( rx_head->fPacketSize, 0 );
  532. if ( !IsNextPacket ( &fRxHeader, rx_head, fNSubProcess ) )
  533. jack_error ( "Packet(s) missing..." );
  534. fRxHeader.fCycle = rx_head->fCycle;
  535. fRxHeader.fSubCycle = rx_head->fSubCycle;
  536. fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
  537. fNetAudioCaptureBuffer->RenderToJackPorts ( rx_head->fSubCycle );
  538. break;
  539. case 's': //sync
  540. jack_info ( "NetDriver : driver overloaded, skipping receive." );
  541. fRxHeader.fCycle = rx_head->fCycle;
  542. return 0;
  543. }
  544. }
  545. }
  546. while ( fRxHeader.fIsLastPckt != 'y' );
  547. }
  548. fRxHeader.fCycle = rx_head->fCycle;
  549. #ifdef JACK_MONITOR
  550. fNetTimeMeasure[fNetTimeMeasureId++] = ( ( float ) ( GetMicroSeconds() - JackDriver::fBeginDateUst ) / ( float ) fEngineControl->fPeriodUsecs ) * 100.f;
  551. #endif
  552. return 0;
  553. }
  554. int JackNetDriver::Write()
  555. {
  556. uint midi_port_index;
  557. int tx_bytes, audio_port_index;
  558. //tx header
  559. if ( fEngineControl->fSyncMode )
  560. fTxHeader.fCycle = fRxHeader.fCycle;
  561. else
  562. fTxHeader.fCycle++;
  563. fTxHeader.fSubCycle = 0;
  564. fTxHeader.fIsLastPckt = 'n';
  565. //buffers
  566. for ( midi_port_index = 0; midi_port_index < fParams.fReturnMidiChannels; midi_port_index++ )
  567. fNetMidiPlaybackBuffer->SetBuffer ( midi_port_index, GetMidiOutputBuffer ( midi_port_index ) );
  568. for ( audio_port_index = 0; audio_port_index < fPlaybackChannels; audio_port_index++ )
  569. fNetAudioPlaybackBuffer->SetBuffer ( audio_port_index, GetOutputBuffer ( audio_port_index ) );
  570. #ifdef JACK_MONITOR
  571. fNetTimeMeasure[fNetTimeMeasureId++] = ( ( float ) ( GetMicroSeconds() - JackDriver::fBeginDateUst ) / ( float ) fEngineControl->fPeriodUsecs ) * 100.f;
  572. #endif
  573. //sync
  574. fTxHeader.fDataType = 's';
  575. if ( !fParams.fSendMidiChannels && !fParams.fSendAudioChannels )
  576. fTxHeader.fIsLastPckt = 'y';
  577. fTxHeader.fPacketSize = fParams.fMtu;
  578. memcpy ( fTxBuffer, &fTxHeader, sizeof ( packet_header_t ) );
  579. memset ( fTxData, 0, fPayloadSize );
  580. SetSyncPacket();
  581. tx_bytes = Send ( fTxHeader.fPacketSize, 0 );
  582. if ( tx_bytes == SOCKET_ERROR )
  583. return tx_bytes;
  584. #ifdef JACK_MONITOR
  585. fNetTimeMeasure[fNetTimeMeasureId++] = ( ( float ) ( GetMicroSeconds() - JackDriver::fBeginDateUst ) / ( float ) fEngineControl->fPeriodUsecs ) * 100.f;
  586. #endif
  587. //midi
  588. if ( fParams.fReturnMidiChannels )
  589. {
  590. fTxHeader.fDataType = 'm';
  591. fTxHeader.fMidiDataSize = fNetMidiPlaybackBuffer->RenderFromJackPorts();
  592. fTxHeader.fNMidiPckt = GetNMidiPckt ( &fParams, fTxHeader.fMidiDataSize );
  593. for ( uint subproc = 0; subproc < fTxHeader.fNMidiPckt; subproc++ )
  594. {
  595. fTxHeader.fSubCycle = subproc;
  596. if ( ( subproc == ( fTxHeader.fNMidiPckt - 1 ) ) && !fParams.fReturnAudioChannels )
  597. fTxHeader.fIsLastPckt = 'y';
  598. fTxHeader.fPacketSize = fNetMidiPlaybackBuffer->RenderToNetwork ( subproc, fTxHeader.fMidiDataSize );
  599. fTxHeader.fPacketSize += sizeof ( packet_header_t );
  600. memcpy ( fTxBuffer, &fTxHeader, sizeof ( packet_header_t ) );
  601. tx_bytes = Send ( fTxHeader.fPacketSize, 0 );
  602. if ( tx_bytes == SOCKET_ERROR )
  603. return tx_bytes;
  604. }
  605. }
  606. //audio
  607. if ( fParams.fReturnAudioChannels )
  608. {
  609. fTxHeader.fDataType = 'a';
  610. for ( uint subproc = 0; subproc < fNSubProcess; subproc++ )
  611. {
  612. fTxHeader.fSubCycle = subproc;
  613. if ( subproc == ( fNSubProcess - 1 ) )
  614. fTxHeader.fIsLastPckt = 'y';
  615. fTxHeader.fPacketSize = fAudioTxLen;
  616. memcpy ( fTxBuffer, &fTxHeader, sizeof ( packet_header_t ) );
  617. fNetAudioPlaybackBuffer->RenderFromJackPorts ( subproc );
  618. tx_bytes = Send ( fTxHeader.fPacketSize, 0 );
  619. if ( tx_bytes == SOCKET_ERROR )
  620. return tx_bytes;
  621. }
  622. }
  623. #ifdef JACK_MONITOR
  624. fNetTimeMeasure[fNetTimeMeasureId++] = ( ( float ) ( GetMicroSeconds() - JackDriver::fBeginDateUst ) / ( float ) fEngineControl->fPeriodUsecs ) * 100.f;
  625. fNetTimeMon->Write ( fNetTimeMeasure );
  626. #endif
  627. return 0;
  628. }
  629. //*************************************loader*******************************************************
  630. #ifdef __cplusplus
  631. extern "C"
  632. {
  633. #endif
  634. EXPORT jack_driver_desc_t* driver_get_descriptor ()
  635. {
  636. jack_driver_desc_t* desc = ( jack_driver_desc_t* ) calloc ( 1, sizeof ( jack_driver_desc_t ) );
  637. strcpy ( desc->name, "net" );
  638. desc->nparams = 10;
  639. desc->params = ( jack_driver_param_desc_t* ) calloc ( desc->nparams, sizeof ( jack_driver_param_desc_t ) );
  640. int i = 0;
  641. strcpy ( desc->params[i].name, "multicast_ip" );
  642. desc->params[i].character = 'a';
  643. desc->params[i].type = JackDriverParamString;
  644. strcpy ( desc->params[i].value.str, DEFAULT_MULTICAST_IP );
  645. strcpy ( desc->params[i].short_desc, "Multicast Address" );
  646. strcpy ( desc->params[i].long_desc, desc->params[i].short_desc );
  647. i++;
  648. strcpy ( desc->params[i].name, "udp_net_port" );
  649. desc->params[i].character = 'p';
  650. desc->params[i].type = JackDriverParamInt;
  651. desc->params[i].value.i = 19000;
  652. strcpy ( desc->params[i].short_desc, "UDP port" );
  653. strcpy ( desc->params[i].long_desc, desc->params[i].short_desc );
  654. i++;
  655. strcpy ( desc->params[i].name, "mtu" );
  656. desc->params[i].character = 'M';
  657. desc->params[i].type = JackDriverParamInt;
  658. desc->params[i].value.i = 1500;
  659. strcpy ( desc->params[i].short_desc, "MTU to the master" );
  660. strcpy ( desc->params[i].long_desc, desc->params[i].short_desc );
  661. i++;
  662. strcpy ( desc->params[i].name, "input_ports" );
  663. desc->params[i].character = 'C';
  664. desc->params[i].type = JackDriverParamInt;
  665. desc->params[i].value.i = 2;
  666. strcpy ( desc->params[i].short_desc, "Number of audio input ports" );
  667. strcpy ( desc->params[i].long_desc, desc->params[i].short_desc );
  668. i++;
  669. strcpy ( desc->params[i].name, "output_ports" );
  670. desc->params[i].character = 'P';
  671. desc->params[i].type = JackDriverParamInt;
  672. desc->params[i].value.i = 2;
  673. strcpy ( desc->params[i].short_desc, "Number of audio output ports" );
  674. strcpy ( desc->params[i].long_desc, desc->params[i].short_desc );
  675. i++;
  676. strcpy ( desc->params[i].name, "midi_in_ports" );
  677. desc->params[i].character = 'i';
  678. desc->params[i].type = JackDriverParamInt;
  679. desc->params[i].value.i = 0;
  680. strcpy ( desc->params[i].short_desc, "Number of midi input ports" );
  681. strcpy ( desc->params[i].long_desc, desc->params[i].short_desc );
  682. i++;
  683. strcpy ( desc->params[i].name, "midi_out_ports" );
  684. desc->params[i].character = 'o';
  685. desc->params[i].type = JackDriverParamUInt;
  686. desc->params[i].value.i = 0;
  687. strcpy ( desc->params[i].short_desc, "Number of midi output ports" );
  688. strcpy ( desc->params[i].long_desc, desc->params[i].short_desc );
  689. i++;
  690. strcpy ( desc->params[i].name, "client_name" );
  691. desc->params[i].character = 'n';
  692. desc->params[i].type = JackDriverParamString;
  693. strcpy ( desc->params[i].value.str, "'hostname'" );
  694. strcpy ( desc->params[i].short_desc, "Name of the jack client" );
  695. strcpy ( desc->params[i].long_desc, desc->params[i].short_desc );
  696. i++;
  697. strcpy ( desc->params[i].name, "transport_sync" );
  698. desc->params[i].character = 't';
  699. desc->params[i].type = JackDriverParamUInt;
  700. desc->params[i].value.ui = 1U;
  701. strcpy ( desc->params[i].short_desc, "Sync transport with master's" );
  702. strcpy ( desc->params[i].long_desc, desc->params[i].short_desc );
  703. i++;
  704. strcpy ( desc->params[i].name, "network_mode" );
  705. desc->params[i].character = 'f';
  706. desc->params[i].type = JackDriverParamString;
  707. strcpy ( desc->params[i].value.str, "" );
  708. strcpy ( desc->params[i].short_desc, "Fast mode allows a zero latency transmission." );
  709. strcpy ( desc->params[i].long_desc, desc->params[i].short_desc );
  710. return desc;
  711. }
  712. EXPORT Jack::JackDriverClientInterface* driver_initialize ( Jack::JackLockedEngine* engine, Jack::JackSynchro* table, const JSList* params )
  713. {
  714. if ( SocketAPIInit() < 0 )
  715. {
  716. jack_error ( "Can't init Socket API, exiting..." );
  717. return NULL;
  718. }
  719. const char* multicast_ip = DEFAULT_MULTICAST_IP;
  720. char name[JACK_CLIENT_NAME_SIZE];
  721. GetHostName ( name, JACK_CLIENT_NAME_SIZE );
  722. int udp_port = DEFAULT_PORT;
  723. int mtu = 1500;
  724. uint transport_sync = 1;
  725. jack_nframes_t period_size = 128;
  726. jack_nframes_t sample_rate = 48000;
  727. int audio_capture_ports = 2;
  728. int audio_playback_ports = 2;
  729. int midi_input_ports = 0;
  730. int midi_output_ports = 0;
  731. bool monitor = false;
  732. char network_mode = 'n';
  733. const JSList* node;
  734. const jack_driver_param_t* param;
  735. for ( node = params; node; node = jack_slist_next ( node ) )
  736. {
  737. param = ( const jack_driver_param_t* ) node->data;
  738. switch ( param->character )
  739. {
  740. case 'a' :
  741. multicast_ip = strdup ( param->value.str );
  742. break;
  743. case 'p':
  744. udp_port = param->value.ui;
  745. break;
  746. case 'M':
  747. mtu = param->value.i;
  748. break;
  749. case 'C':
  750. audio_capture_ports = param->value.i;
  751. break;
  752. case 'P':
  753. audio_playback_ports = param->value.i;
  754. break;
  755. case 'i':
  756. midi_input_ports = param->value.i;
  757. break;
  758. case 'o':
  759. midi_output_ports = param->value.i;
  760. break;
  761. case 'n' :
  762. strncpy ( name, param->value.str, JACK_CLIENT_NAME_SIZE );
  763. break;
  764. case 't' :
  765. transport_sync = param->value.ui;
  766. break;
  767. case 'f' :
  768. network_mode = 'f';
  769. break;
  770. }
  771. }
  772. Jack::JackDriverClientInterface* driver = new Jack::JackWaitThreadedDriver (
  773. new Jack::JackNetDriver ( "system", "net_pcm", engine, table, multicast_ip, udp_port, mtu,
  774. midi_input_ports, midi_output_ports, name, transport_sync, network_mode ) );
  775. if ( driver->Open ( period_size, sample_rate, 1, 1, audio_capture_ports, audio_playback_ports,
  776. monitor, "from_master_", "to_master_", 0, 0 ) == 0 )
  777. return driver;
  778. delete driver;
  779. return NULL;
  780. }
  781. #ifdef __cplusplus
  782. }
  783. #endif
  784. }