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.

1352 lines
41KB

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