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.

1265 lines
37KB

  1. /*
  2. Copyright (C) 2001 Paul Davis
  3. Copyright (C) 2004-2008 Grame
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as published by
  6. the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  15. */
  16. #include "JackClient.h"
  17. #include "JackGraphManager.h"
  18. #include "JackClientControl.h"
  19. #include "JackEngineControl.h"
  20. #include "JackGlobals.h"
  21. #include "JackChannel.h"
  22. #include "JackTransportEngine.h"
  23. #include "driver_interface.h"
  24. #include "JackLibGlobals.h"
  25. #include <math.h>
  26. #include <string>
  27. #include <algorithm>
  28. using namespace std;
  29. namespace Jack
  30. {
  31. #define IsRealTime() ((fProcess != NULL) | (fThreadFun != NULL) | (fSync != NULL) | (fTimebase != NULL))
  32. JackClient::JackClient():fThread(this)
  33. {}
  34. JackClient::JackClient(JackSynchro* table):fThread(this)
  35. {
  36. fSynchroTable = table;
  37. fProcess = NULL;
  38. fGraphOrder = NULL;
  39. fXrun = NULL;
  40. fShutdown = NULL;
  41. fInfoShutdown = NULL;
  42. fInit = NULL;
  43. fBufferSize = NULL;
  44. fClientRegistration = NULL;
  45. fFreewheel = NULL;
  46. fPortRegistration = NULL;
  47. fPortConnect = NULL;
  48. fPortRename = NULL;
  49. fTimebase = NULL;
  50. fSync = NULL;
  51. fThreadFun = NULL;
  52. fSession = NULL;
  53. fLatency = NULL;
  54. fProcessArg = NULL;
  55. fGraphOrderArg = NULL;
  56. fXrunArg = NULL;
  57. fShutdownArg = NULL;
  58. fInfoShutdownArg = NULL;
  59. fInitArg = NULL;
  60. fBufferSizeArg = NULL;
  61. fFreewheelArg = NULL;
  62. fClientRegistrationArg = NULL;
  63. fPortRegistrationArg = NULL;
  64. fPortConnectArg = NULL;
  65. fPortRenameArg = NULL;
  66. fSyncArg = NULL;
  67. fTimebaseArg = NULL;
  68. fThreadFunArg = NULL;
  69. fSessionArg = NULL;
  70. fLatencyArg = NULL;
  71. }
  72. JackClient::~JackClient()
  73. {}
  74. int JackClient::Close()
  75. {
  76. jack_log("JackClient::Close ref = %ld", GetClientControl()->fRefNum);
  77. int result = 0;
  78. Deactivate();
  79. fChannel->Stop(); // Channels is stopped first to avoid receiving notifications while closing
  80. // Request close only if server is still running
  81. if (JackGlobals::fServerRunning) {
  82. fChannel->ClientClose(GetClientControl()->fRefNum, &result);
  83. } else {
  84. jack_log("JackClient::Close server is shutdown");
  85. }
  86. fChannel->Close();
  87. fSynchroTable[GetClientControl()->fRefNum].Disconnect();
  88. JackGlobals::fClientTable[GetClientControl()->fRefNum] = NULL;
  89. return result;
  90. }
  91. bool JackClient::IsActive()
  92. {
  93. return (GetClientControl()) ? GetClientControl()->fActive : false;
  94. }
  95. jack_native_thread_t JackClient::GetThreadID()
  96. {
  97. return fThread.GetThreadID();
  98. }
  99. /*!
  100. In "async" mode, the server does not synchronize itself on the output drivers, thus it would never "consume" the activations.
  101. The synchronization primitives for drivers are setup in "flush" mode that to not keep unneeded activations.
  102. Drivers synchro are setup in "flush" mode if server is "async" and NOT freewheel.
  103. */
  104. void JackClient::SetupDriverSync(bool freewheel)
  105. {
  106. if (!freewheel && !GetEngineControl()->fSyncMode) {
  107. jack_log("JackClient::SetupDriverSync driver sem in flush mode");
  108. for (int i = 0; i < GetEngineControl()->fDriverNum; i++) {
  109. fSynchroTable[i].SetFlush(true);
  110. }
  111. } else {
  112. jack_log("JackClient::SetupDriverSync driver sem in normal mode");
  113. for (int i = 0; i < GetEngineControl()->fDriverNum; i++)
  114. fSynchroTable[i].SetFlush(false);
  115. }
  116. }
  117. /*!
  118. \brief Notification received from the server.
  119. */
  120. int JackClient::ClientNotifyImp(int refnum, const char* name, int notify, int sync, const char* message, int value1, int value2)
  121. {
  122. return 0;
  123. }
  124. int JackClient::ClientNotify(int refnum, const char* name, int notify, int sync, const char* message, int value1, int value2)
  125. {
  126. int res = 0;
  127. // Done all time: redirected on subclass implementation JackLibClient and JackInternalClient
  128. switch (notify) {
  129. case kAddClient:
  130. res = ClientNotifyImp(refnum, name, notify, sync, message, value1, value2);
  131. break;
  132. case kRemoveClient:
  133. res = ClientNotifyImp(refnum, name, notify, sync, message, value1, value2);
  134. break;
  135. case kActivateClient:
  136. jack_log("JackClient::kActivateClient name = %s ref = %ld ", name, refnum);
  137. Init();
  138. break;
  139. }
  140. /*
  141. The current semantic is that notifications can only be received when the client has been activated,
  142. although is this implementation, one could imagine calling notifications as soon as the client has be opened.
  143. */
  144. if (IsActive()) {
  145. switch (notify) {
  146. case kAddClient:
  147. jack_log("JackClient::kAddClient fName = %s name = %s", GetClientControl()->fName, name);
  148. if (fClientRegistration && strcmp(GetClientControl()->fName, name) != 0) { // Don't call the callback for the registering client itself
  149. fClientRegistration(name, 1, fClientRegistrationArg);
  150. }
  151. break;
  152. case kRemoveClient:
  153. jack_log("JackClient::kRemoveClient fName = %s name = %s", GetClientControl()->fName, name);
  154. if (fClientRegistration && strcmp(GetClientControl()->fName, name) != 0) { // Don't call the callback for the registering client itself
  155. fClientRegistration(name, 0, fClientRegistrationArg);
  156. }
  157. break;
  158. case kBufferSizeCallback:
  159. jack_log("JackClient::kBufferSizeCallback buffer_size = %ld", value1);
  160. if (fBufferSize) {
  161. res = fBufferSize(value1, fBufferSizeArg);
  162. }
  163. break;
  164. case kSampleRateCallback:
  165. jack_log("JackClient::kSampleRateCallback sample_rate = %ld", value1);
  166. if (fSampleRate) {
  167. res = fSampleRate(value1, fSampleRateArg);
  168. }
  169. break;
  170. case kGraphOrderCallback:
  171. jack_log("JackClient::kGraphOrderCallback");
  172. if (fGraphOrder) {
  173. res = fGraphOrder(fGraphOrderArg);
  174. }
  175. break;
  176. case kStartFreewheelCallback:
  177. jack_log("JackClient::kStartFreewheel");
  178. SetupDriverSync(true);
  179. fThread.DropRealTime(); // Always done (JACK server in RT mode or not...)
  180. if (fFreewheel) {
  181. fFreewheel(1, fFreewheelArg);
  182. }
  183. break;
  184. case kStopFreewheelCallback:
  185. jack_log("JackClient::kStopFreewheel");
  186. SetupDriverSync(false);
  187. if (fFreewheel) {
  188. fFreewheel(0, fFreewheelArg);
  189. }
  190. if (GetEngineControl()->fRealTime) {
  191. fThread.AcquireRealTime();
  192. }
  193. break;
  194. case kPortRegistrationOnCallback:
  195. jack_log("JackClient::kPortRegistrationOn port_index = %ld", value1);
  196. if (fPortRegistration) {
  197. fPortRegistration(value1, 1, fPortRegistrationArg);
  198. }
  199. break;
  200. case kPortRegistrationOffCallback:
  201. jack_log("JackClient::kPortRegistrationOff port_index = %ld ", value1);
  202. if (fPortRegistration) {
  203. fPortRegistration(value1, 0, fPortRegistrationArg);
  204. }
  205. break;
  206. case kPortConnectCallback:
  207. jack_log("JackClient::kPortConnectCallback src = %ld dst = %ld", value1, value2);
  208. if (fPortConnect) {
  209. fPortConnect(value1, value2, 1, fPortConnectArg);
  210. }
  211. break;
  212. case kPortDisconnectCallback:
  213. jack_log("JackClient::kPortDisconnectCallback src = %ld dst = %ld", value1, value2);
  214. if (fPortConnect) {
  215. fPortConnect(value1, value2, 0, fPortConnectArg);
  216. }
  217. break;
  218. case kPortRenameCallback:
  219. jack_log("JackClient::kPortRenameCallback port = %ld", value1);
  220. if (fPortRename) {
  221. fPortRename(value1, message, GetGraphManager()->GetPort(value1)->GetName(), fPortRenameArg);
  222. }
  223. break;
  224. case kXRunCallback:
  225. jack_log("JackClient::kXRunCallback");
  226. if (fXrun) {
  227. res = fXrun(fXrunArg);
  228. }
  229. break;
  230. case kShutDownCallback:
  231. jack_log("JackClient::kShutDownCallback");
  232. if (fInfoShutdown) {
  233. fInfoShutdown((jack_status_t)value1, message, fInfoShutdownArg);
  234. fInfoShutdown = NULL;
  235. }
  236. break;
  237. case kSessionCallback:
  238. jack_log("JackClient::kSessionCallback");
  239. if (fSession) {
  240. jack_session_event_t *event = (jack_session_event_t *) malloc( sizeof(jack_session_event_t) );
  241. char uuid_buf[JACK_UUID_SIZE];
  242. event->type = (jack_session_event_type_t) value1;
  243. event->session_dir = strdup( message );
  244. event->command_line = NULL;
  245. event->flags = (jack_session_flags_t) 0;
  246. snprintf( uuid_buf, sizeof(uuid_buf), "%d", GetClientControl()->fSessionID );
  247. event->client_uuid = strdup( uuid_buf );
  248. fImmediateSessionReply = false;
  249. fSession(event, fSessionArg);
  250. res = (fImmediateSessionReply) ? 1 : 2;
  251. }
  252. break;
  253. case kLatencyCallback:
  254. res = HandleLatencyCallback(value1);
  255. break;
  256. }
  257. }
  258. return res;
  259. }
  260. int JackClient::HandleLatencyCallback(int status)
  261. {
  262. jack_latency_callback_mode_t mode = (status == 0) ? JackCaptureLatency : JackPlaybackLatency;
  263. jack_latency_range_t latency = { UINT32_MAX, 0 };
  264. /* first setup all latency values of the ports.
  265. * this is based on the connections of the ports.
  266. */
  267. list<jack_port_id_t>::iterator it;
  268. for (it = fPortList.begin(); it != fPortList.end(); it++) {
  269. JackPort* port = GetGraphManager()->GetPort(*it);
  270. if ((port->GetFlags() & JackPortIsOutput) && (mode == JackPlaybackLatency)) {
  271. GetGraphManager()->RecalculateLatency(*it, mode);
  272. }
  273. if ((port->GetFlags() & JackPortIsInput) && (mode == JackCaptureLatency)) {
  274. GetGraphManager()->RecalculateLatency(*it, mode);
  275. }
  276. }
  277. if (!fLatency) {
  278. /*
  279. * default action is to assume all ports depend on each other.
  280. * then always take the maximum latency.
  281. */
  282. if (mode == JackPlaybackLatency) {
  283. /* iterate over all OutputPorts, to find maximum playback latency
  284. */
  285. for (it = fPortList.begin(); it != fPortList.end(); it++) {
  286. JackPort* port = GetGraphManager()->GetPort(*it);
  287. if (port->GetFlags() & JackPortIsOutput) {
  288. jack_latency_range_t other_latency;
  289. port->GetLatencyRange(mode, &other_latency);
  290. if (other_latency.max > latency.max)
  291. latency.max = other_latency.max;
  292. if (other_latency.min < latency.min)
  293. latency.min = other_latency.min;
  294. }
  295. }
  296. if (latency.min == UINT32_MAX)
  297. latency.min = 0;
  298. /* now set the found latency on all input ports
  299. */
  300. for (it = fPortList.begin(); it != fPortList.end(); it++) {
  301. JackPort* port = GetGraphManager()->GetPort(*it);
  302. if (port->GetFlags() & JackPortIsInput) {
  303. port->SetLatencyRange(mode, &latency);
  304. }
  305. }
  306. }
  307. if (mode == JackCaptureLatency) {
  308. /* iterate over all InputPorts, to find maximum playback latency
  309. */
  310. for (it = fPortList.begin(); it != fPortList.end(); it++) {
  311. JackPort* port = GetGraphManager()->GetPort(*it);
  312. if (port->GetFlags() & JackPortIsInput) {
  313. jack_latency_range_t other_latency;
  314. port->GetLatencyRange(mode, &other_latency);
  315. if (other_latency.max > latency.max)
  316. latency.max = other_latency.max;
  317. if (other_latency.min < latency.min)
  318. latency.min = other_latency.min;
  319. }
  320. }
  321. if (latency.min == UINT32_MAX)
  322. latency.min = 0;
  323. /* now set the found latency on all output ports
  324. */
  325. for (it = fPortList.begin(); it != fPortList.end(); it++) {
  326. JackPort* port = GetGraphManager()->GetPort(*it);
  327. if (port->GetFlags() & JackPortIsOutput) {
  328. port->SetLatencyRange(mode, &latency);
  329. }
  330. }
  331. }
  332. return 0;
  333. }
  334. /* we have a latency callback setup by the client,
  335. * lets use it...
  336. */
  337. fLatency(mode, fLatencyArg);
  338. return 0;
  339. }
  340. /*!
  341. \brief We need to start thread before activating in the server, otherwise the FW driver
  342. connected to the client may not be activated.
  343. */
  344. int JackClient::Activate()
  345. {
  346. jack_log("JackClient::Activate");
  347. if (IsActive())
  348. return 0;
  349. // RT thread is started only when needed...
  350. if (IsRealTime()) {
  351. if (StartThread() < 0)
  352. return -1;
  353. }
  354. /*
  355. Insertion of client in the graph will cause a kGraphOrderCallback notification
  356. to be delivered by the server, the client wants to receive it.
  357. */
  358. GetClientControl()->fActive = true;
  359. // Transport related callback become "active"
  360. GetClientControl()->fTransportSync = true;
  361. GetClientControl()->fTransportTimebase = true;
  362. int result = -1;
  363. GetClientControl()->fCallback[kRealTimeCallback] = IsRealTime();
  364. fChannel->ClientActivate(GetClientControl()->fRefNum, IsRealTime(), &result);
  365. return result;
  366. }
  367. /*!
  368. \brief Need to stop thread after deactivating in the server.
  369. */
  370. int JackClient::Deactivate()
  371. {
  372. jack_log("JackClient::Deactivate");
  373. if (!IsActive())
  374. return 0;
  375. GetClientControl()->fActive = false;
  376. // Transport related callback become "unactive"
  377. GetClientControl()->fTransportSync = false;
  378. GetClientControl()->fTransportTimebase = false;
  379. // We need to wait for the new engine cycle before stopping the RT thread, but this is done by ClientDeactivate
  380. int result = -1;
  381. fChannel->ClientDeactivate(GetClientControl()->fRefNum, &result);
  382. jack_log("JackClient::Deactivate res = %ld", result);
  383. // RT thread is stopped only when needed...
  384. if (IsRealTime())
  385. fThread.Kill();
  386. return result;
  387. }
  388. //----------------------
  389. // RT thread management
  390. //----------------------
  391. /*!
  392. \brief Called once when the thread starts.
  393. */
  394. bool JackClient::Init()
  395. {
  396. if (fInit) {
  397. jack_log("JackClient::Init calling client thread init callback");
  398. fInit(fInitArg);
  399. }
  400. return true;
  401. }
  402. int JackClient::StartThread()
  403. {
  404. jack_log("JackClient::StartThread : period = %ld computation = %ld constraint = %ld",
  405. long(int64_t(GetEngineControl()->fPeriod) / 1000.0f),
  406. long(int64_t(GetEngineControl()->fComputation) / 1000.0f),
  407. long(int64_t(GetEngineControl()->fConstraint) / 1000.0f));
  408. // Will do "something" on OSX only...
  409. fThread.SetParams(GetEngineControl()->fPeriod, GetEngineControl()->fComputation, GetEngineControl()->fConstraint);
  410. if (fThread.StartSync() < 0) {
  411. jack_error("Start thread error");
  412. return -1;
  413. }
  414. if (GetEngineControl()->fRealTime) {
  415. if (fThread.AcquireRealTime(GetEngineControl()->fClientPriority) < 0) {
  416. jack_error("AcquireRealTime error");
  417. }
  418. }
  419. return 0;
  420. }
  421. /*!
  422. \brief RT thread.
  423. */
  424. bool JackClient::Execute()
  425. {
  426. if (!jack_tls_set(JackGlobals::fRealTime, this))
  427. jack_error("failed to set thread realtime key");
  428. if (GetEngineControl()->fRealTime)
  429. set_threaded_log_function();
  430. // Execute a dummy cycle to be sure thread has the correct properties
  431. DummyCycle();
  432. if (fThreadFun) {
  433. fThreadFun(fThreadFunArg);
  434. } else {
  435. ExecuteThread();
  436. }
  437. return false;
  438. }
  439. void JackClient::DummyCycle()
  440. {
  441. WaitSync();
  442. SignalSync();
  443. }
  444. inline void JackClient::ExecuteThread()
  445. {
  446. while (true) {
  447. CycleWaitAux();
  448. CycleSignalAux(CallProcessCallback());
  449. }
  450. }
  451. inline jack_nframes_t JackClient::CycleWaitAux()
  452. {
  453. if (!WaitSync())
  454. Error(); // Terminates the thread
  455. CallSyncCallbackAux();
  456. return GetEngineControl()->fBufferSize;
  457. }
  458. inline void JackClient::CycleSignalAux(int status)
  459. {
  460. if (status == 0)
  461. CallTimebaseCallbackAux();
  462. SignalSync();
  463. if (status != 0)
  464. End(); // Terminates the thread
  465. }
  466. jack_nframes_t JackClient::CycleWait()
  467. {
  468. return CycleWaitAux();
  469. }
  470. void JackClient::CycleSignal(int status)
  471. {
  472. CycleSignalAux(status);
  473. }
  474. inline int JackClient::CallProcessCallback()
  475. {
  476. return (fProcess != NULL) ? fProcess(GetEngineControl()->fBufferSize, fProcessArg) : 0;
  477. }
  478. inline bool JackClient::WaitSync()
  479. {
  480. // Suspend itself: wait on the input synchro
  481. if (GetGraphManager()->SuspendRefNum(GetClientControl(), fSynchroTable, 0x7FFFFFFF) < 0) {
  482. jack_error("SuspendRefNum error");
  483. return false;
  484. } else {
  485. return true;
  486. }
  487. }
  488. inline void JackClient::SignalSync()
  489. {
  490. // Resume: signal output clients connected to the running client
  491. if (GetGraphManager()->ResumeRefNum(GetClientControl(), fSynchroTable) < 0) {
  492. jack_error("ResumeRefNum error");
  493. }
  494. }
  495. inline void JackClient::End()
  496. {
  497. jack_log("JackClient::Execute end name = %s", GetClientControl()->fName);
  498. // Hum... not sure about this, the following "close" code is called in the RT thread...
  499. int result;
  500. fThread.DropSelfRealTime();
  501. GetClientControl()->fActive = false;
  502. fChannel->ClientDeactivate(GetClientControl()->fRefNum, &result);
  503. fThread.Terminate();
  504. }
  505. inline void JackClient::Error()
  506. {
  507. jack_error("JackClient::Execute error name = %s", GetClientControl()->fName);
  508. // Hum... not sure about this, the following "close" code is called in the RT thread...
  509. int result;
  510. fThread.DropSelfRealTime();
  511. GetClientControl()->fActive = false;
  512. fChannel->ClientDeactivate(GetClientControl()->fRefNum, &result);
  513. ShutDown();
  514. fThread.Terminate();
  515. }
  516. //-----------------
  517. // Port management
  518. //-----------------
  519. int JackClient::PortRegister(const char* port_name, const char* port_type, unsigned long flags, unsigned long buffer_size)
  520. {
  521. // Check if port name is empty
  522. string port_name_str = string(port_name);
  523. if (port_name_str.size() == 0) {
  524. jack_error("port_name is empty");
  525. return 0; // Means failure here...
  526. }
  527. // Check port name length
  528. string name = string(GetClientControl()->fName) + string(":") + port_name_str;
  529. if (name.size() >= JACK_PORT_NAME_SIZE) {
  530. jack_error("\"%s:%s\" is too long to be used as a JACK port name.\n"
  531. "Please use %lu characters or less",
  532. GetClientControl()->fName,
  533. port_name,
  534. JACK_PORT_NAME_SIZE - 1);
  535. return 0; // Means failure here...
  536. }
  537. int result = -1;
  538. jack_port_id_t port_index = NO_PORT;
  539. fChannel->PortRegister(GetClientControl()->fRefNum, name.c_str(), port_type, flags, buffer_size, &port_index, &result);
  540. if (result == 0) {
  541. jack_log("JackClient::PortRegister ref = %ld name = %s type = %s port_index = %ld", GetClientControl()->fRefNum, name.c_str(), port_type, port_index);
  542. fPortList.push_back(port_index);
  543. return port_index;
  544. } else {
  545. return 0;
  546. }
  547. }
  548. int JackClient::PortUnRegister(jack_port_id_t port_index)
  549. {
  550. jack_log("JackClient::PortUnRegister port_index = %ld", port_index);
  551. list<jack_port_id_t>::iterator it = find(fPortList.begin(), fPortList.end(), port_index);
  552. if (it != fPortList.end()) {
  553. fPortList.erase(it);
  554. int result = -1;
  555. fChannel->PortUnRegister(GetClientControl()->fRefNum, port_index, &result);
  556. return result;
  557. } else {
  558. jack_error("unregistering a port %ld that is not own by the client", port_index);
  559. return -1;
  560. }
  561. }
  562. int JackClient::PortConnect(const char* src, const char* dst)
  563. {
  564. jack_log("JackClient::Connect src = %s dst = %s", src, dst);
  565. int result = -1;
  566. fChannel->PortConnect(GetClientControl()->fRefNum, src, dst, &result);
  567. return result;
  568. }
  569. int JackClient::PortDisconnect(const char* src, const char* dst)
  570. {
  571. jack_log("JackClient::Disconnect src = %s dst = %s", src, dst);
  572. int result = -1;
  573. fChannel->PortDisconnect(GetClientControl()->fRefNum, src, dst, &result);
  574. return result;
  575. }
  576. int JackClient::PortDisconnect(jack_port_id_t src)
  577. {
  578. jack_log("JackClient::PortDisconnect src = %ld", src);
  579. int result = -1;
  580. fChannel->PortDisconnect(GetClientControl()->fRefNum, src, ALL_PORTS, &result);
  581. return result;
  582. }
  583. int JackClient::PortIsMine(jack_port_id_t port_index)
  584. {
  585. JackPort* port = GetGraphManager()->GetPort(port_index);
  586. return GetClientControl()->fRefNum == port->GetRefNum();
  587. }
  588. int JackClient::PortRename(jack_port_id_t port_index, const char* name)
  589. {
  590. int result = -1;
  591. fChannel->PortRename(GetClientControl()->fRefNum, port_index, name, &result);
  592. return result;
  593. }
  594. //--------------------
  595. // Context management
  596. //--------------------
  597. int JackClient::SetBufferSize(jack_nframes_t buffer_size)
  598. {
  599. int result = -1;
  600. fChannel->SetBufferSize(buffer_size, &result);
  601. return result;
  602. }
  603. int JackClient::SetFreeWheel(int onoff)
  604. {
  605. int result = -1;
  606. fChannel->SetFreewheel(onoff, &result);
  607. return result;
  608. }
  609. int JackClient::ComputeTotalLatencies()
  610. {
  611. int result = -1;
  612. fChannel->ComputeTotalLatencies(&result);
  613. return result;
  614. }
  615. /*
  616. ShutDown is called:
  617. - from the RT thread when Execute method fails
  618. - possibly from a "closed" notification channel
  619. (Not needed since the synch object used (Sema of Fifo will fails when server quits... see ShutDown))
  620. */
  621. void JackClient::ShutDown()
  622. {
  623. jack_log("ShutDown");
  624. JackGlobals::fServerRunning = false;
  625. if (fInfoShutdown) {
  626. fInfoShutdown(JackFailure, "JACK server has been closed", fInfoShutdownArg);
  627. fInfoShutdown = NULL;
  628. } else if (fShutdown) {
  629. fShutdown(fShutdownArg);
  630. fShutdown = NULL;
  631. }
  632. }
  633. //----------------------
  634. // Transport management
  635. //----------------------
  636. inline int JackClient::ActivateAux()
  637. {
  638. // If activated without RT thread...
  639. if (IsActive() && fThread.GetStatus() != JackThread::kRunning) {
  640. jack_log("ActivateAux");
  641. // RT thread is started
  642. if (StartThread() < 0)
  643. return -1;
  644. int result = -1;
  645. GetClientControl()->fCallback[kRealTimeCallback] = IsRealTime();
  646. fChannel->ClientActivate(GetClientControl()->fRefNum, IsRealTime(), &result);
  647. return result;
  648. } else {
  649. return 0;
  650. }
  651. }
  652. int JackClient::ReleaseTimebase()
  653. {
  654. int result = -1;
  655. fChannel->ReleaseTimebase(GetClientControl()->fRefNum, &result);
  656. if (result == 0) {
  657. GetClientControl()->fTransportTimebase = false;
  658. fTimebase = NULL;
  659. fTimebaseArg = NULL;
  660. }
  661. return result;
  662. }
  663. /* Call the server if the client is active, otherwise keeps the arguments */
  664. int JackClient::SetSyncCallback(JackSyncCallback sync_callback, void* arg)
  665. {
  666. GetClientControl()->fTransportSync = (fSync != NULL);
  667. fSyncArg = arg;
  668. fSync = sync_callback;
  669. return ActivateAux();
  670. }
  671. int JackClient::SetTimebaseCallback(int conditional, JackTimebaseCallback timebase_callback, void* arg)
  672. {
  673. int result = -1;
  674. fChannel->SetTimebaseCallback(GetClientControl()->fRefNum, conditional, &result);
  675. if (result == 0) {
  676. GetClientControl()->fTransportTimebase = true;
  677. fTimebase = timebase_callback;
  678. fTimebaseArg = arg;
  679. return ActivateAux();
  680. } else {
  681. fTimebase = NULL;
  682. fTimebaseArg = NULL;
  683. return -1;
  684. }
  685. }
  686. int JackClient::SetSyncTimeout(jack_time_t timeout)
  687. {
  688. GetEngineControl()->fTransport.SetSyncTimeout(timeout);
  689. return 0;
  690. }
  691. // Must be RT safe
  692. void JackClient::TransportLocate(jack_nframes_t frame)
  693. {
  694. jack_position_t pos;
  695. pos.frame = frame;
  696. pos.valid = (jack_position_bits_t)0;
  697. jack_log("TransportLocate pos = %ld", pos.frame);
  698. GetEngineControl()->fTransport.RequestNewPos(&pos);
  699. }
  700. int JackClient::TransportReposition(jack_position_t* pos)
  701. {
  702. jack_position_t tmp = *pos;
  703. jack_log("TransportReposition pos = %ld", pos->frame);
  704. if (tmp.valid & ~JACK_POSITION_MASK) {
  705. return EINVAL;
  706. } else {
  707. GetEngineControl()->fTransport.RequestNewPos(pos);
  708. return 0;
  709. }
  710. }
  711. jack_transport_state_t JackClient::TransportQuery(jack_position_t* pos)
  712. {
  713. return GetEngineControl()->fTransport.Query(pos);
  714. }
  715. jack_nframes_t JackClient::GetCurrentTransportFrame()
  716. {
  717. return GetEngineControl()->fTransport.GetCurrentFrame();
  718. }
  719. // Must be RT safe: directly write in the transport shared mem
  720. void JackClient::TransportStart()
  721. {
  722. GetEngineControl()->fTransport.SetCommand(TransportCommandStart);
  723. }
  724. // Must be RT safe: directly write in the transport shared mem
  725. void JackClient::TransportStop()
  726. {
  727. GetEngineControl()->fTransport.SetCommand(TransportCommandStop);
  728. }
  729. // Never called concurently with the server
  730. // TODO check concurrency with SetSyncCallback
  731. void JackClient::CallSyncCallback()
  732. {
  733. CallSyncCallbackAux();
  734. }
  735. inline void JackClient::CallSyncCallbackAux()
  736. {
  737. if (GetClientControl()->fTransportSync) {
  738. JackTransportEngine& transport = GetEngineControl()->fTransport;
  739. jack_position_t* cur_pos = transport.ReadCurrentState();
  740. jack_transport_state_t transport_state = transport.GetState();
  741. if (fSync != NULL) {
  742. if (fSync(transport_state, cur_pos, fSyncArg)) {
  743. GetClientControl()->fTransportState = JackTransportRolling;
  744. GetClientControl()->fTransportSync = false;
  745. }
  746. } else {
  747. GetClientControl()->fTransportState = JackTransportRolling;
  748. GetClientControl()->fTransportSync = false;
  749. }
  750. }
  751. }
  752. void JackClient::CallTimebaseCallback()
  753. {
  754. CallTimebaseCallbackAux();
  755. }
  756. inline void JackClient::CallTimebaseCallbackAux()
  757. {
  758. JackTransportEngine& transport = GetEngineControl()->fTransport;
  759. int master;
  760. bool unused;
  761. transport.GetTimebaseMaster(master, unused);
  762. if (GetClientControl()->fRefNum == master && fTimebase) { // Client *is* timebase...
  763. jack_transport_state_t transport_state = transport.GetState();
  764. jack_position_t* cur_pos = transport.WriteNextStateStart(1);
  765. if (GetClientControl()->fTransportTimebase) {
  766. fTimebase(transport_state, GetEngineControl()->fBufferSize, cur_pos, true, fTimebaseArg);
  767. GetClientControl()->fTransportTimebase = false; // Callback is called only once with "new_pos" = true
  768. } else if (transport_state == JackTransportRolling) {
  769. fTimebase(transport_state, GetEngineControl()->fBufferSize, cur_pos, false, fTimebaseArg);
  770. }
  771. transport.WriteNextStateStop(1);
  772. }
  773. }
  774. //---------------------
  775. // Callback management
  776. //---------------------
  777. void JackClient::OnShutdown(JackShutdownCallback callback, void *arg)
  778. {
  779. if (IsActive()) {
  780. jack_error("You cannot set callbacks on an active client");
  781. } else {
  782. fShutdownArg = arg;
  783. fShutdown = callback;
  784. }
  785. }
  786. void JackClient::OnInfoShutdown(JackInfoShutdownCallback callback, void *arg)
  787. {
  788. if (IsActive()) {
  789. jack_error("You cannot set callbacks on an active client");
  790. } else {
  791. GetClientControl()->fCallback[kShutDownCallback] = (callback != NULL);
  792. fInfoShutdownArg = arg;
  793. fInfoShutdown = callback;
  794. }
  795. }
  796. int JackClient::SetProcessCallback(JackProcessCallback callback, void *arg)
  797. {
  798. if (IsActive()) {
  799. jack_error("You cannot set callbacks on an active client");
  800. return -1;
  801. } else if (fThreadFun) {
  802. jack_error ("A thread callback has already been setup, both models cannot be used at the same time!");
  803. return -1;
  804. } else {
  805. fProcessArg = arg;
  806. fProcess = callback;
  807. return 0;
  808. }
  809. }
  810. int JackClient::SetXRunCallback(JackXRunCallback callback, void *arg)
  811. {
  812. if (IsActive()) {
  813. jack_error("You cannot set callbacks on an active client");
  814. return -1;
  815. } else {
  816. GetClientControl()->fCallback[kXRunCallback] = (callback != NULL);
  817. fXrunArg = arg;
  818. fXrun = callback;
  819. return 0;
  820. }
  821. }
  822. int JackClient::SetInitCallback(JackThreadInitCallback callback, void *arg)
  823. {
  824. if (IsActive()) {
  825. jack_error("You cannot set callbacks on an active client");
  826. return -1;
  827. } else {
  828. fInitArg = arg;
  829. fInit = callback;
  830. /* make sure that the message buffer thread is initialized too */
  831. JackMessageBuffer::fInstance->SetInitCallback(callback, arg);
  832. return 0;
  833. }
  834. }
  835. int JackClient::SetGraphOrderCallback(JackGraphOrderCallback callback, void *arg)
  836. {
  837. jack_log("SetGraphOrderCallback ");
  838. if (IsActive()) {
  839. jack_error("You cannot set callbacks on an active client");
  840. return -1;
  841. } else {
  842. GetClientControl()->fCallback[kGraphOrderCallback] = (callback != NULL);
  843. fGraphOrder = callback;
  844. fGraphOrderArg = arg;
  845. return 0;
  846. }
  847. }
  848. int JackClient::SetBufferSizeCallback(JackBufferSizeCallback callback, void *arg)
  849. {
  850. if (IsActive()) {
  851. jack_error("You cannot set callbacks on an active client");
  852. return -1;
  853. } else {
  854. GetClientControl()->fCallback[kBufferSizeCallback] = (callback != NULL);
  855. fBufferSizeArg = arg;
  856. fBufferSize = callback;
  857. return 0;
  858. }
  859. }
  860. int JackClient::SetSampleRateCallback(JackSampleRateCallback callback, void *arg)
  861. {
  862. if (IsActive()) {
  863. jack_error("You cannot set callbacks on an active client");
  864. return -1;
  865. } else {
  866. GetClientControl()->fCallback[kSampleRateCallback] = (callback != NULL);
  867. fSampleRateArg = arg;
  868. fSampleRate = callback;
  869. // Now invoke it
  870. if (callback)
  871. callback(GetEngineControl()->fSampleRate, arg);
  872. return 0;
  873. }
  874. }
  875. int JackClient::SetClientRegistrationCallback(JackClientRegistrationCallback callback, void* arg)
  876. {
  877. if (IsActive()) {
  878. jack_error("You cannot set callbacks on an active client");
  879. return -1;
  880. } else {
  881. // kAddClient and kRemoveClient notifications must be delivered by the server in any case
  882. fClientRegistrationArg = arg;
  883. fClientRegistration = callback;
  884. return 0;
  885. }
  886. }
  887. int JackClient::SetFreewheelCallback(JackFreewheelCallback callback, void *arg)
  888. {
  889. if (IsActive()) {
  890. jack_error("You cannot set callbacks on an active client");
  891. return -1;
  892. } else {
  893. GetClientControl()->fCallback[kStartFreewheelCallback] = (callback != NULL);
  894. GetClientControl()->fCallback[kStopFreewheelCallback] = (callback != NULL);
  895. fFreewheelArg = arg;
  896. fFreewheel = callback;
  897. return 0;
  898. }
  899. }
  900. int JackClient::SetPortRegistrationCallback(JackPortRegistrationCallback callback, void *arg)
  901. {
  902. if (IsActive()) {
  903. jack_error("You cannot set callbacks on an active client");
  904. return -1;
  905. } else {
  906. GetClientControl()->fCallback[kPortRegistrationOnCallback] = (callback != NULL);
  907. GetClientControl()->fCallback[kPortRegistrationOffCallback] = (callback != NULL);
  908. fPortRegistrationArg = arg;
  909. fPortRegistration = callback;
  910. return 0;
  911. }
  912. }
  913. int JackClient::SetPortConnectCallback(JackPortConnectCallback callback, void *arg)
  914. {
  915. if (IsActive()) {
  916. jack_error("You cannot set callbacks on an active client");
  917. return -1;
  918. } else {
  919. GetClientControl()->fCallback[kPortConnectCallback] = (callback != NULL);
  920. GetClientControl()->fCallback[kPortDisconnectCallback] = (callback != NULL);
  921. fPortConnectArg = arg;
  922. fPortConnect = callback;
  923. return 0;
  924. }
  925. }
  926. int JackClient::SetPortRenameCallback(JackPortRenameCallback callback, void *arg)
  927. {
  928. if (IsActive()) {
  929. jack_error("You cannot set callbacks on an active client");
  930. return -1;
  931. } else {
  932. GetClientControl()->fCallback[kPortRenameCallback] = (callback != NULL);
  933. fPortRenameArg = arg;
  934. fPortRename = callback;
  935. return 0;
  936. }
  937. }
  938. int JackClient::SetProcessThread(JackThreadCallback fun, void *arg)
  939. {
  940. if (IsActive()) {
  941. jack_error("You cannot set callbacks on an active client");
  942. return -1;
  943. } else if (fProcess) {
  944. jack_error ("A process callback has already been setup, both models cannot be used at the same time!");
  945. return -1;
  946. } else {
  947. fThreadFun = fun;
  948. fThreadFunArg = arg;
  949. return 0;
  950. }
  951. }
  952. int JackClient::SetSessionCallback(JackSessionCallback callback, void *arg)
  953. {
  954. if (IsActive()) {
  955. jack_error("You cannot set callbacks on an active client");
  956. return -1;
  957. } else {
  958. GetClientControl()->fCallback[kSessionCallback] = (callback != NULL);
  959. fSessionArg = arg;
  960. fSession = callback;
  961. return 0;
  962. }
  963. }
  964. int JackClient::SetLatencyCallback(JackLatencyCallback callback, void *arg)
  965. {
  966. if (IsActive()) {
  967. jack_error("You cannot set callbacks on an active client");
  968. return -1;
  969. } else {
  970. GetClientControl()->fCallback[kLatencyCallback] = (callback != NULL);
  971. fLatencyArg = arg;
  972. fLatency = callback;
  973. return 0;
  974. }
  975. }
  976. //------------------
  977. // Internal clients
  978. //------------------
  979. char* JackClient::GetInternalClientName(int ref)
  980. {
  981. char name_res[JACK_CLIENT_NAME_SIZE + 1];
  982. int result = -1;
  983. fChannel->GetInternalClientName(GetClientControl()->fRefNum, ref, name_res, &result);
  984. return (result < 0) ? NULL : strdup(name_res);
  985. }
  986. int JackClient::InternalClientHandle(const char* client_name, jack_status_t* status)
  987. {
  988. int int_ref, result = -1;
  989. fChannel->InternalClientHandle(GetClientControl()->fRefNum, client_name, (int*)status, &int_ref, &result);
  990. return int_ref;
  991. }
  992. int JackClient::InternalClientLoad(const char* client_name, jack_options_t options, jack_status_t* status, jack_varargs_t* va)
  993. {
  994. if (strlen(client_name) >= JACK_CLIENT_NAME_SIZE) {
  995. jack_error ("\"%s\" is too long for a JACK client name.\n"
  996. "Please use %lu characters or less.",
  997. client_name, JACK_CLIENT_NAME_SIZE);
  998. return 0;
  999. }
  1000. if (va->load_name && (strlen(va->load_name) >= JACK_PATH_MAX)) {
  1001. jack_error("\"%s\" is too long for a shared object name.\n"
  1002. "Please use %lu characters or less.",
  1003. va->load_name, JACK_PATH_MAX);
  1004. int my_status1 = *status | (JackFailure | JackInvalidOption);
  1005. *status = (jack_status_t)my_status1;
  1006. return 0;
  1007. }
  1008. if (va->load_init && (strlen(va->load_init) >= JACK_LOAD_INIT_LIMIT)) {
  1009. jack_error ("\"%s\" is too long for internal client init "
  1010. "string.\nPlease use %lu characters or less.",
  1011. va->load_init, JACK_LOAD_INIT_LIMIT);
  1012. int my_status1 = *status | (JackFailure | JackInvalidOption);
  1013. *status = (jack_status_t)my_status1;
  1014. return 0;
  1015. }
  1016. int int_ref, result = -1;
  1017. fChannel->InternalClientLoad(GetClientControl()->fRefNum, client_name, va->load_name, va->load_init, options, (int*)status, &int_ref, -1, &result);
  1018. return int_ref;
  1019. }
  1020. void JackClient::InternalClientUnload(int ref, jack_status_t* status)
  1021. {
  1022. int result = -1;
  1023. fChannel->InternalClientUnload(GetClientControl()->fRefNum, ref, (int*)status, &result);
  1024. }
  1025. //------------------
  1026. // Session API
  1027. //------------------
  1028. jack_session_command_t *JackClient::SessionNotify( const char* target, jack_session_event_type_t type, const char* path )
  1029. {
  1030. jack_session_command_t *res;
  1031. fChannel->SessionNotify( GetClientControl()->fRefNum, target, type, path, &res );
  1032. return res;
  1033. }
  1034. int JackClient::SessionReply( jack_session_event_t *ev )
  1035. {
  1036. if (ev->command_line) {
  1037. strncpy( GetClientControl()->fSessionCommand, ev->command_line, sizeof(GetClientControl()->fSessionCommand) );
  1038. } else {
  1039. GetClientControl()->fSessionCommand[0] = '\0';
  1040. }
  1041. GetClientControl()->fSessionFlags = ev->flags;
  1042. jack_log( "JackClient::SessionReply... we are here" );
  1043. if (fChannel->IsChannelThread()) {
  1044. jack_log( "JackClient::SessionReply... in callback reply" );
  1045. fImmediateSessionReply = true;
  1046. return 0;
  1047. }
  1048. jack_log( "JackClient::SessionReply... out of cb" );
  1049. int res;
  1050. fChannel->SessionReply( GetClientControl()->fRefNum, &res);
  1051. return res;
  1052. }
  1053. char* JackClient::GetUUIDForClientName(const char* client_name)
  1054. {
  1055. char uuid_res[JACK_UUID_SIZE];
  1056. int result = -1;
  1057. fChannel->GetUUIDForClientName( GetClientControl()->fRefNum, client_name, uuid_res, &result);
  1058. if (result)
  1059. return NULL;
  1060. return strdup(uuid_res);
  1061. }
  1062. char* JackClient::GetClientNameForUUID(const char* uuid)
  1063. {
  1064. char name_res[JACK_CLIENT_NAME_SIZE + 1];
  1065. int result = -1;
  1066. fChannel->GetClientNameForUUID(GetClientControl()->fRefNum, uuid, name_res, &result);
  1067. if (result)
  1068. return NULL;
  1069. return strdup(name_res);
  1070. }
  1071. int JackClient::ReserveClientName(const char *name, const char* uuid)
  1072. {
  1073. int result = -1;
  1074. fChannel->ReserveClientName( GetClientControl()->fRefNum, name, uuid, &result);
  1075. return result;
  1076. }
  1077. } // end of namespace