jack1 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.

1565 lines
39KB

  1. /*
  2. Copyright (C) 2001-2003 Paul Davis
  3. This program is free software; you can redistribute it and/or modify
  4. it under the terms of the GNU Lesser General Public License as published by
  5. the Free Software Foundation; either version 2.1 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Lesser General Public License for more details.
  11. You should have received a copy of the GNU Lesser General Public License
  12. along with this program; if not, write to the Free Software
  13. Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  14. $Id$
  15. */
  16. #if defined(__APPLE__) && defined(__POWERPC__)
  17. #include "pThreadUtilities.h"
  18. #include "ipc.h"
  19. #include "fakepoll.h"
  20. #else
  21. #include <sys/poll.h>
  22. #endif
  23. #include <sys/socket.h>
  24. #include <sys/un.h>
  25. #include <pthread.h>
  26. #include <errno.h>
  27. #include <fcntl.h>
  28. #include <sys/types.h>
  29. #include <sys/ipc.h>
  30. #include <sys/mman.h>
  31. #include <stdarg.h>
  32. #include <stdio.h>
  33. #include <stdint.h>
  34. #include <regex.h>
  35. #include <config.h>
  36. #include <jack/jack.h>
  37. #include <jack/internal.h>
  38. #include <jack/engine.h>
  39. #include <jack/pool.h>
  40. #include <jack/time.h>
  41. #include <jack/jslist.h>
  42. #include <jack/version.h>
  43. #include <jack/shm.h>
  44. #include "local.h"
  45. #ifdef WITH_TIMESTAMPS
  46. #include <jack/timestamps.h>
  47. #endif /* WITH_TIMESTAMPS */
  48. #ifdef DEFAULT_TMP_DIR
  49. char *jack_server_dir = DEFAULT_TMP_DIR;
  50. #else
  51. char *jack_server_dir = "/tmp";
  52. #endif
  53. void
  54. jack_set_server_dir (const char *path)
  55. {
  56. jack_server_dir = strdup (path);
  57. }
  58. static pthread_mutex_t client_lock;
  59. static pthread_cond_t client_ready;
  60. void *jack_zero_filled_buffer = 0;
  61. #define event_fd pollfd[0].fd
  62. #define graph_wait_fd pollfd[1].fd
  63. typedef struct {
  64. int status;
  65. struct _jack_client *client;
  66. const char *client_name;
  67. } client_info;
  68. void
  69. jack_error (const char *fmt, ...)
  70. {
  71. va_list ap;
  72. char buffer[300];
  73. va_start (ap, fmt);
  74. vsnprintf (buffer, sizeof(buffer), fmt, ap);
  75. jack_error_callback (buffer);
  76. va_end (ap);
  77. }
  78. void default_jack_error_callback (const char *desc)
  79. {
  80. fprintf(stderr, "%s\n", desc);
  81. }
  82. void (*jack_error_callback)(const char *desc) = &default_jack_error_callback;
  83. static int
  84. oop_client_deliver_request (void *ptr, jack_request_t *req)
  85. {
  86. jack_client_t *client = (jack_client_t*) ptr;
  87. if (write (client->request_fd, req, sizeof (*req)) != sizeof (*req)) {
  88. jack_error ("cannot send request type %d to server", req->type);
  89. req->status = -1;
  90. }
  91. if (read (client->request_fd, req, sizeof (*req)) != sizeof (*req)) {
  92. jack_error ("cannot read result for request type %d from server (%s)", req->type, strerror (errno));
  93. req->status = -1;
  94. }
  95. return req->status;
  96. }
  97. int
  98. jack_client_deliver_request (const jack_client_t *client, jack_request_t *req)
  99. {
  100. /* indirect through the function pointer that was set
  101. either by jack_client_new() (external) or handle_new_client()
  102. in the server.
  103. */
  104. return client->control->deliver_request (client->control->deliver_arg, req);
  105. }
  106. jack_client_t *
  107. jack_client_alloc ()
  108. {
  109. jack_client_t *client;
  110. client = (jack_client_t *) malloc (sizeof (jack_client_t));
  111. client->pollfd = (struct pollfd *) malloc (sizeof (struct pollfd) * 2);
  112. client->pollmax = 2;
  113. client->request_fd = -1;
  114. client->event_fd = -1;
  115. client->graph_wait_fd = -1;
  116. client->graph_next_fd = -1;
  117. client->port_segments = NULL;
  118. client->ports = NULL;
  119. client->engine = NULL;
  120. client->control = 0;
  121. client->thread_ok = FALSE;
  122. client->first_active = TRUE;
  123. client->on_shutdown = NULL;
  124. return client;
  125. }
  126. jack_client_t *
  127. jack_client_alloc_internal (jack_client_control_t *cc, jack_control_t *ec)
  128. {
  129. jack_client_t* client;
  130. client = jack_client_alloc ();
  131. client->control = cc;
  132. client->engine = ec;
  133. return client;
  134. }
  135. static void
  136. jack_client_free (jack_client_t *client)
  137. {
  138. if (client->pollfd) {
  139. free (client->pollfd);
  140. }
  141. free (client);
  142. }
  143. void
  144. jack_client_invalidate_port_buffers (jack_client_t *client)
  145. {
  146. JSList *node;
  147. jack_port_t *port;
  148. /* This releases all local memory owned by input ports
  149. and sets the buffer pointer to NULL. This will cause
  150. jack_port_get_buffer() to reallocate space for the
  151. buffer on the next call (if there is one).
  152. */
  153. for (node = client->ports; node; node = jack_slist_next (node)) {
  154. port = (jack_port_t *) node->data;
  155. if (port->shared->flags & JackPortIsInput) {
  156. if (port->client_segment_base == 0) {
  157. jack_pool_release ((void *) port->shared->offset);
  158. port->client_segment_base = 0;
  159. port->shared->offset = 0;
  160. }
  161. }
  162. }
  163. }
  164. int
  165. jack_client_handle_port_connection (jack_client_t *client, jack_event_t *event)
  166. {
  167. jack_port_t *control_port;
  168. jack_port_t *other;
  169. JSList *node;
  170. switch (event->type) {
  171. case PortConnected:
  172. other = jack_port_new (client, event->y.other_id, client->engine);
  173. control_port = jack_port_by_id (client, event->x.self_id);
  174. pthread_mutex_lock (&control_port->connection_lock);
  175. control_port->connections = jack_slist_prepend (control_port->connections, (void*)other);
  176. pthread_mutex_unlock (&control_port->connection_lock);
  177. break;
  178. case PortDisconnected:
  179. control_port = jack_port_by_id (client, event->x.self_id);
  180. pthread_mutex_lock (&control_port->connection_lock);
  181. for (node = control_port->connections; node; node = jack_slist_next (node)) {
  182. other = (jack_port_t *) node->data;
  183. if (other->shared->id == event->y.other_id) {
  184. control_port->connections = jack_slist_remove_link (control_port->connections, node);
  185. jack_slist_free_1 (node);
  186. free (other);
  187. break;
  188. }
  189. }
  190. pthread_mutex_unlock (&control_port->connection_lock);
  191. break;
  192. default:
  193. /* impossible */
  194. break;
  195. }
  196. return 0;
  197. }
  198. static int
  199. jack_handle_reorder (jack_client_t *client, jack_event_t *event)
  200. {
  201. char path[PATH_MAX+1];
  202. if (client->graph_wait_fd >= 0) {
  203. DEBUG ("closing graph_wait_fd==%d", client->graph_wait_fd);
  204. close (client->graph_wait_fd);
  205. client->graph_wait_fd = -1;
  206. }
  207. if (client->graph_next_fd >= 0) {
  208. DEBUG ("closing graph_next_fd==%d", client->graph_next_fd);
  209. close (client->graph_next_fd);
  210. client->graph_next_fd = -1;
  211. }
  212. sprintf (path, "%s-%" PRIu32, client->fifo_prefix, event->x.n);
  213. if ((client->graph_wait_fd = open (path, O_RDONLY|O_NONBLOCK)) < 0) {
  214. jack_error ("cannot open specified fifo [%s] for reading (%s)", path, strerror (errno));
  215. return -1;
  216. }
  217. DEBUG ("opened new graph_wait_fd %d (%s)", client->graph_wait_fd, path);
  218. sprintf (path, "%s-%" PRIu32, client->fifo_prefix, event->x.n+1);
  219. if ((client->graph_next_fd = open (path, O_WRONLY|O_NONBLOCK)) < 0) {
  220. jack_error ("cannot open specified fifo [%s] for writing (%s)", path, strerror (errno));
  221. return -1;
  222. }
  223. DEBUG ("opened new graph_next_fd %d (%s)", client->graph_next_fd, path);
  224. /* If the client registered its own callback for graph order events,
  225. execute it now.
  226. */
  227. if (client->control->graph_order) {
  228. client->control->graph_order (client->control->graph_order_arg);
  229. }
  230. return 0;
  231. }
  232. static int
  233. server_connect (int which)
  234. {
  235. int fd;
  236. struct sockaddr_un addr;
  237. if ((fd = socket (AF_UNIX, SOCK_STREAM, 0)) < 0) {
  238. jack_error ("cannot create client socket (%s)", strerror (errno));
  239. return -1;
  240. }
  241. addr.sun_family = AF_UNIX;
  242. snprintf (addr.sun_path, sizeof (addr.sun_path) - 1, "%s/jack_%d", jack_server_dir, which);
  243. if (connect (fd, (struct sockaddr *) &addr, sizeof (addr)) < 0) {
  244. jack_error ("cannot connect to jack server", strerror (errno));
  245. close (fd);
  246. return -1;
  247. }
  248. return fd;
  249. }
  250. static int
  251. server_event_connect (jack_client_t *client)
  252. {
  253. int fd;
  254. struct sockaddr_un addr;
  255. jack_client_connect_ack_request_t req;
  256. jack_client_connect_ack_result_t res;
  257. if ((fd = socket (AF_UNIX, SOCK_STREAM, 0)) < 0) {
  258. jack_error ("cannot create client event socket (%s)", strerror (errno));
  259. return -1;
  260. }
  261. addr.sun_family = AF_UNIX;
  262. snprintf (addr.sun_path, sizeof (addr.sun_path) - 1, "%s/jack_ack_0", jack_server_dir);
  263. if (connect (fd, (struct sockaddr *) &addr, sizeof (addr)) < 0) {
  264. jack_error ("cannot connect to jack server for events", strerror (errno));
  265. close (fd);
  266. return -1;
  267. }
  268. req.client_id = client->control->id;
  269. if (write (fd, &req, sizeof (req)) != sizeof (req)) {
  270. jack_error ("cannot write event connect request to server (%s)", strerror (errno));
  271. close (fd);
  272. return -1;
  273. }
  274. if (read (fd, &res, sizeof (res)) != sizeof (res)) {
  275. jack_error ("cannot read event connect result from server (%s)", strerror (errno));
  276. close (fd);
  277. return -1;
  278. }
  279. if (res.status != 0) {
  280. close (fd);
  281. return -1;
  282. }
  283. return fd;
  284. }
  285. static int
  286. jack_request_client (ClientType type, const char* client_name, const char* so_name,
  287. const char* so_data, jack_client_connect_result_t *res, int *req_fd)
  288. {
  289. jack_client_connect_request_t req;
  290. *req_fd = -1;
  291. memset (&req, 0, sizeof (req));
  292. if (strlen (client_name) > sizeof (req.name) - 1) {
  293. jack_error ("\"%s\" is too long to be used as a JACK client name.\n"
  294. "Please use %lu characters or less.",
  295. client_name, sizeof (req.name) - 1);
  296. return -1;
  297. }
  298. if (strlen (so_name) > sizeof (req.object_path) - 1) {
  299. jack_error ("\"%s\" is too long to be used as a JACK shared object name.\n"
  300. "Please use %lu characters or less.",
  301. so_name, sizeof (req.object_path) - 1);
  302. return -1;
  303. }
  304. if (strlen (so_data) > sizeof (req.object_data) - 1) {
  305. jack_error ("\"%s\" is too long to be used as a JACK shared object data string.\n"
  306. "Please use %lu characters or less.",
  307. so_data, sizeof (req.object_data) - 1);
  308. return -1;
  309. }
  310. if ((*req_fd = server_connect (0)) < 0) {
  311. jack_error ("cannot connect to default JACK server");
  312. goto fail;
  313. }
  314. req.load = TRUE;
  315. req.type = type;
  316. snprintf (req.name, sizeof (req.name), "%s", client_name);
  317. snprintf (req.object_path, sizeof (req.object_path), "%s", so_name);
  318. snprintf (req.object_data, sizeof (req.object_data), "%s", so_data);
  319. if (write (*req_fd, &req, sizeof (req)) != sizeof (req)) {
  320. jack_error ("cannot send request to jack server (%s)", strerror (errno));
  321. goto fail;
  322. }
  323. if (read (*req_fd, res, sizeof (*res)) != sizeof (*res)) {
  324. if (errno == 0) {
  325. /* server shut the socket */
  326. jack_error ("could not attach as client (duplicate client name?)");
  327. goto fail;
  328. }
  329. jack_error ("cannot read response from jack server (%s)", strerror (errno));
  330. goto fail;
  331. }
  332. if (res->status) {
  333. jack_error ("could not attach as client (duplicate client name?)");
  334. goto fail;
  335. }
  336. if (res->protocol_v != jack_protocol_version){
  337. jack_error ("application linked against too wrong of a version of libjack.");
  338. goto fail;
  339. }
  340. switch (type) {
  341. case ClientDriver:
  342. case ClientInternal:
  343. close (*req_fd);
  344. *req_fd = -1;
  345. break;
  346. default:
  347. break;
  348. }
  349. return 0;
  350. fail:
  351. if (*req_fd >= 0) {
  352. close (*req_fd);
  353. *req_fd = -1;
  354. }
  355. return -1;
  356. }
  357. jack_client_t *
  358. jack_client_new (const char *client_name)
  359. {
  360. int req_fd = -1;
  361. int ev_fd = -1;
  362. jack_client_connect_result_t res;
  363. jack_client_t *client;
  364. void *addr;
  365. int i;
  366. int shmid;
  367. jack_port_type_info_t* type_info;
  368. /* external clients need this initialized; internal clients
  369. will use the setup in the server's address space.
  370. */
  371. jack_init_time ();
  372. if (jack_request_client (ClientExternal, client_name, "", "", &res, &req_fd)) {
  373. return NULL;
  374. }
  375. client = jack_client_alloc ();
  376. strcpy (client->fifo_prefix, res.fifo_prefix);
  377. client->request_fd = req_fd;
  378. client->pollfd[0].events = POLLIN|POLLERR|POLLHUP|POLLNVAL;
  379. client->pollfd[1].events = POLLIN|POLLERR|POLLHUP|POLLNVAL;
  380. /* attach the engine control/info block */
  381. if ((addr = jack_get_shm (res.control_shm_name, res.control_size, O_RDWR,
  382. 0, (PROT_READ|PROT_WRITE), &shmid)) == MAP_FAILED) {
  383. jack_error ("cannot attached engine control shared memory segment");
  384. goto fail;
  385. }
  386. client->engine = (jack_control_t *) addr;
  387. /* now attach the client control block */
  388. if ((addr = jack_get_shm (res.client_shm_name, sizeof (jack_client_control_t), O_RDWR,
  389. 0, (PROT_READ|PROT_WRITE), &shmid)) == MAP_FAILED) {
  390. jack_error ("cannot attached client control shared memory segment");
  391. goto fail;
  392. }
  393. client->control = (jack_client_control_t *) addr;
  394. /* nobody else needs to access this shared memory any more, so
  395. destroy it. because we have our own link to it, it won't vanish
  396. till we exit.
  397. */
  398. jack_destroy_shm (res.client_shm_name);
  399. /* read incoming port type information so that we can get shared memory
  400. information for each one.
  401. */
  402. type_info = (jack_port_type_info_t *) malloc (sizeof (jack_port_type_info_t) * res.n_port_types);
  403. if (read (req_fd, type_info, sizeof (jack_port_type_info_t) * res.n_port_types) !=
  404. sizeof (jack_port_type_info_t) * res.n_port_types) {
  405. jack_error ("cannot read port type information during client connection");
  406. free (type_info);
  407. goto fail;
  408. }
  409. for (i = 0; i < res.n_port_types; ++i) {
  410. jack_client_handle_new_port_type (client, type_info[i].shm_info.shm_name, type_info[i].shm_info.size, 0);
  411. }
  412. free (type_info);
  413. /* set up the client so that it does the right thing for an external client */
  414. client->control->deliver_request = oop_client_deliver_request;
  415. client->control->deliver_arg = client;
  416. if ((ev_fd = server_event_connect (client)) < 0) {
  417. jack_error ("cannot connect to server for event stream (%s)", strerror (errno));
  418. goto fail;
  419. }
  420. client->event_fd = ev_fd;
  421. #if defined(__APPLE__) && defined(__POWERPC__)
  422. /* specific ressources for server/client real-time thread communication */
  423. client->clienttask = mach_task_self();
  424. if (task_get_bootstrap_port(client->clienttask, &client->bp)){
  425. jack_error ("Can't find bootstrap port");
  426. goto fail;
  427. }
  428. if (allocate_mach_clientport(client, res.portnum) < 0) {
  429. jack_error("Can't allocate mach port");
  430. goto fail;
  431. };
  432. #endif
  433. return client;
  434. fail:
  435. if (client->engine) {
  436. munmap ((char *) client->engine, res.control_size);
  437. }
  438. if (client->control) {
  439. munmap ((char *) client->control, sizeof (jack_client_control_t));
  440. }
  441. if (req_fd >= 0) {
  442. close (req_fd);
  443. }
  444. if (ev_fd >= 0) {
  445. close (ev_fd);
  446. }
  447. return 0;
  448. }
  449. int
  450. jack_internal_client_new (const char *client_name, const char *so_name, const char *so_data)
  451. {
  452. jack_client_connect_result_t res;
  453. int req_fd;
  454. return jack_request_client (ClientInternal, client_name, so_name, so_data, &res, &req_fd);
  455. }
  456. void
  457. jack_internal_client_close (const char *client_name)
  458. {
  459. jack_client_connect_request_t req;
  460. int fd;
  461. req.load = FALSE;
  462. snprintf (req.name, sizeof (req.name), "%s", client_name);
  463. if ((fd = server_connect (0)) < 0) {
  464. jack_error ("cannot connect to default JACK server.");
  465. return;
  466. }
  467. if (write (fd, &req, sizeof (req)) != sizeof(req)) {
  468. jack_error ("cannot deliver ClientUnload request to JACK server.");
  469. }
  470. /* no response to this request */
  471. close (fd);
  472. return;
  473. }
  474. void
  475. jack_client_handle_new_port_type (jack_client_t *client, shm_name_t shm_name, size_t size, void* addr)
  476. {
  477. jack_port_segment_info_t *si;
  478. int shmid;
  479. /* Lookup, attach and register the port/buffer segments in use
  480. right now.
  481. */
  482. if (client->control->type == ClientExternal) {
  483. if ((addr = jack_get_shm(shm_name, size, O_RDWR, 0, (PROT_READ|PROT_WRITE), &shmid)) == MAP_FAILED) {
  484. jack_error ("cannot attached port segment shared memory (%s)", strerror (errno));
  485. return;
  486. }
  487. } else {
  488. /* client is in same address space as server, so just use `addr' directly */
  489. }
  490. si = (jack_port_segment_info_t *) malloc (sizeof (jack_port_segment_info_t));
  491. strcpy (si->shm_name, shm_name);
  492. si->address = addr;
  493. si->size = size;
  494. /* the first chunk of the first port segment is always set by the engine
  495. to be a conveniently-sized, zero-filled lump of memory.
  496. */
  497. if (client->port_segments == NULL) {
  498. jack_zero_filled_buffer = si->address;
  499. }
  500. client->port_segments = jack_slist_prepend (client->port_segments, si);
  501. }
  502. static void *
  503. jack_client_thread (void *arg)
  504. {
  505. jack_client_t *client = (jack_client_t *) arg;
  506. jack_client_control_t *control = client->control;
  507. jack_event_t event;
  508. char status = 0;
  509. char c;
  510. int err = 0;
  511. pthread_setcanceltype (PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  512. pthread_mutex_lock (&client_lock);
  513. client->thread_ok = TRUE;
  514. client->thread_id = pthread_self();
  515. pthread_cond_signal (&client_ready);
  516. pthread_mutex_unlock (&client_lock);
  517. client->control->pid = getpid();
  518. DEBUG ("client thread is now running");
  519. while (err == 0) {
  520. if (client->engine->engine_ok == 0) {
  521. jack_error ("engine unexpectedly shutdown; thread exiting\n");
  522. if (client->on_shutdown) {
  523. client->on_shutdown (client->on_shutdown_arg);
  524. }
  525. pthread_exit (0);
  526. }
  527. DEBUG ("client polling on event_fd and graph_wait_fd...");
  528. if (poll (client->pollfd, client->pollmax, 1000) < 0) {
  529. if (errno == EINTR) {
  530. printf ("poll interrupted\n");
  531. continue;
  532. }
  533. jack_error ("poll failed in client (%s)", strerror (errno));
  534. status = -1;
  535. break;
  536. }
  537. pthread_testcancel();
  538. /* get an accurate timestamp on waking from poll for a process()
  539. cycle.
  540. */
  541. if (client->pollfd[1].revents & POLLIN) {
  542. control->awake_at = jack_get_microseconds();
  543. }
  544. if (client->pollfd[0].revents & ~POLLIN || client->control->dead) {
  545. goto zombie;
  546. }
  547. if (client->pollfd[0].revents & POLLIN) {
  548. DEBUG ("client receives an event, now reading on event fd");
  549. /* server has sent us an event. process the event and reply */
  550. if (read (client->event_fd, &event, sizeof (event)) != sizeof (event)) {
  551. jack_error ("cannot read server event (%s)", strerror (errno));
  552. err++;
  553. break;
  554. }
  555. status = 0;
  556. switch (event.type) {
  557. case PortRegistered:
  558. if (control->port_register) {
  559. control->port_register (event.x.port_id, TRUE, control->port_register_arg);
  560. }
  561. break;
  562. case PortUnregistered:
  563. if (control->port_register) {
  564. control->port_register (event.x.port_id, FALSE, control->port_register_arg);
  565. }
  566. break;
  567. case GraphReordered:
  568. status = jack_handle_reorder (client, &event);
  569. break;
  570. case PortConnected:
  571. case PortDisconnected:
  572. status = jack_client_handle_port_connection (client, &event);
  573. break;
  574. case BufferSizeChange:
  575. jack_client_invalidate_port_buffers (client);
  576. if (control->bufsize) {
  577. status = control->bufsize (control->nframes, control->bufsize_arg);
  578. }
  579. break;
  580. case SampleRateChange:
  581. if (control->srate) {
  582. status = control->srate (control->nframes, control->srate_arg);
  583. }
  584. break;
  585. case XRun:
  586. if (control->xrun) {
  587. status = control->xrun (control->xrun_arg);
  588. }
  589. break;
  590. case NewPortType:
  591. jack_client_handle_new_port_type (client, event.x.shm_name, event.z.size, event.y.addr);
  592. break;
  593. }
  594. DEBUG ("client has dealt with the event, writing response on event fd");
  595. if (write (client->event_fd, &status, sizeof (status)) != sizeof (status)) {
  596. jack_error ("cannot send event response to engine (%s)", strerror (errno));
  597. err++;
  598. break;
  599. }
  600. }
  601. if (client->pollfd[1].revents & POLLIN) {
  602. #ifdef WITH_TIMESTAMPS
  603. jack_reset_timestamps ();
  604. #endif
  605. DEBUG ("client %d signalled at %" PRIu64
  606. ", awake for process at %" PRIu64
  607. " (delay = %" PRIu64
  608. " usecs) (wakeup on graph_wait_fd==%d)",
  609. getpid(),
  610. control->signalled_at,
  611. control->awake_at,
  612. control->awake_at - control->signalled_at,
  613. client->pollfd[1].fd);
  614. control->state = Running;
  615. if (control->sync_cb)
  616. jack_call_sync_client (client);
  617. if (control->process) {
  618. if (control->process (control->nframes, control->process_arg) == 0) {
  619. control->state = Finished;
  620. }
  621. } else {
  622. control->state = Finished;
  623. }
  624. if (control->timebase_cb)
  625. jack_call_timebase_master (client);
  626. control->finished_at = jack_get_microseconds();
  627. #ifdef WITH_TIMESTAMPS
  628. jack_timestamp ("finished");
  629. #endif
  630. /* pass the execution token along */
  631. DEBUG ("client finished processing at %Lu (elapsed = %Lu usecs), writing on graph_next_fd==%d",
  632. control->finished_at,
  633. control->finished_at - control->awake_at,
  634. client->graph_next_fd);
  635. if (write (client->graph_next_fd, &c, sizeof (c)) != sizeof (c)) {
  636. jack_error ("cannot continue execution of the processing graph (%s)", strerror(errno));
  637. err++;
  638. break;
  639. }
  640. DEBUG ("client sent message to next stage by %Lu, client reading on graph_wait_fd==%d",
  641. jack_get_microseconds(), client->graph_wait_fd);
  642. #ifdef WITH_TIMESTAMPS
  643. jack_timestamp ("read pending byte from wait");
  644. #endif
  645. DEBUG("reading cleanup byte from pipe\n");
  646. if ((read (client->graph_wait_fd, &c, sizeof (c)) != sizeof (c))) {
  647. DEBUG ("WARNING: READ FAILED!");
  648. /*
  649. jack_error ("cannot complete execution of the processing graph (%s)", strerror(errno));
  650. err++;
  651. break;
  652. */
  653. }
  654. /* check if we were killed during the process cycle (or whatever) */
  655. if (client->control->dead) {
  656. goto zombie;
  657. }
  658. DEBUG("process cycle fully complete\n");
  659. #ifdef WITH_TIMESTAMPS
  660. jack_timestamp ("read done");
  661. jack_dump_timestamps (stdout);
  662. #endif
  663. }
  664. }
  665. return (void *) ((intptr_t)err);
  666. zombie:
  667. if (client->on_shutdown) {
  668. jack_error ("zombified - calling shutdown handler");
  669. client->on_shutdown (client->on_shutdown_arg);
  670. } else {
  671. jack_error ("zombified - exiting from JACK");
  672. jack_client_close (client); /* Need a fix : possibly make client crash if zombified without shutdown handler */
  673. }
  674. pthread_exit (0);
  675. /*NOTREACHED*/
  676. return 0;
  677. }
  678. #if defined(__APPLE__) && defined(__POWERPC__)
  679. /* real-time thread : separated from the normal client thread, it will communicate with the server using fast mach RPC mechanism */
  680. static void *
  681. jack_client_process_thread (void *arg)
  682. {
  683. jack_client_t *client = (jack_client_t *) arg;
  684. jack_client_control_t *control = client->control;
  685. int err = 0;
  686. client->control->pid = getpid();
  687. DEBUG ("client process thread is now running");
  688. pthread_setcanceltype (PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  689. while (err == 0) {
  690. if (jack_client_suspend(client) < 0) {
  691. pthread_exit (0);
  692. }
  693. control->awake_at = jack_get_microseconds();
  694. DEBUG ("client resumed");
  695. control->state = Running;
  696. if (control->process) {
  697. if (control->process (control->nframes, control->process_arg) == 0) {
  698. control->state = Finished;
  699. }
  700. } else {
  701. control->state = Finished;
  702. }
  703. control->finished_at = jack_get_microseconds();
  704. #ifdef WITH_TIMESTAMPS
  705. jack_timestamp ("finished");
  706. #endif
  707. DEBUG ("client finished processing at %Lu (elapsed = %f usecs)",
  708. control->finished_at, ((float)(control->finished_at - control->awake_at)));
  709. /* check if we were killed during the process cycle (or whatever) */
  710. if (client->control->dead) {
  711. jack_error ("jack_client_process_thread : client->control->dead");
  712. goto zombie;
  713. }
  714. DEBUG("process cycle fully complete\n");
  715. }
  716. return (void *) ((intptr_t)err);
  717. zombie:
  718. jack_error ("jack_client_process_thread : zombified");
  719. if (client->on_shutdown) {
  720. jack_error ("zombified - calling shutdown handler");
  721. client->on_shutdown (client->on_shutdown_arg);
  722. } else {
  723. jack_error ("zombified - exiting from JACK");
  724. jack_client_close (client); /* Need a fix : possibly make client crash if zombified without shutdown handler */
  725. }
  726. pthread_exit (0);
  727. /*NOTREACHED*/
  728. return 0;
  729. }
  730. #endif
  731. static int
  732. jack_start_thread (jack_client_t *client)
  733. {
  734. pthread_attr_t *attributes = 0;
  735. #ifdef USE_CAPABILITIES
  736. int policy = SCHED_OTHER;
  737. struct sched_param client_param, temp_param;
  738. #endif
  739. if (client->engine->real_time) {
  740. /* Get the client thread to run as an RT-FIFO
  741. scheduled thread of appropriate priority.
  742. */
  743. struct sched_param rt_param;
  744. attributes = (pthread_attr_t *) malloc (sizeof (pthread_attr_t));
  745. pthread_attr_init (attributes);
  746. if (pthread_attr_setschedpolicy (attributes, SCHED_FIFO)) {
  747. jack_error ("cannot set FIFO scheduling class for RT thread");
  748. return -1;
  749. }
  750. if (pthread_attr_setscope (attributes, PTHREAD_SCOPE_SYSTEM)) {
  751. jack_error ("Cannot set scheduling scope for RT thread");
  752. return -1;
  753. }
  754. memset (&rt_param, 0, sizeof (rt_param));
  755. rt_param.sched_priority = client->engine->client_priority;
  756. if (pthread_attr_setschedparam (attributes, &rt_param)) {
  757. jack_error ("Cannot set scheduling priority for RT thread (%s)", strerror (errno));
  758. return -1;
  759. }
  760. #if defined(__APPLE__) && defined(__POWERPC__)
  761. // To be implemented
  762. #else
  763. if (mlockall (MCL_CURRENT | MCL_FUTURE) != 0) {
  764. jack_error ("cannot lock down memory for RT thread (%s)", strerror (errno));
  765. return -1;
  766. }
  767. #endif
  768. }
  769. if (pthread_create (&client->thread, attributes, jack_client_thread, client)) {
  770. #ifdef USE_CAPABILITIES
  771. if (client->engine->real_time && client->engine->has_capabilities) {
  772. /* we are probably dealing with a broken glibc so try
  773. to work around the bug, see below for more details
  774. */
  775. goto capabilities_workaround;
  776. }
  777. #endif
  778. return -1;
  779. }
  780. #if defined(__APPLE__) && defined(__POWERPC__)
  781. /* a spcial real-time thread to call the "process" callback. It will communicate with the server using fast mach RPC mechanism */
  782. if (pthread_create (&client->process_thread, attributes, jack_client_process_thread, client)) {
  783. jack_error("pthread_create failed for process_thread \n");
  784. return -1;
  785. }
  786. if (client->engine->real_time){
  787. /* time constraint thread */
  788. setThreadToPriority(client->process_thread, 96, true, 10000000);
  789. }else{
  790. /* fixed priority thread */
  791. setThreadToPriority(client->process_thread, 63, true, 10000000);
  792. }
  793. #endif
  794. return 0;
  795. #ifdef USE_CAPABILITIES
  796. /* we get here only with engine running realtime and capabilities */
  797. capabilities_workaround:
  798. /* the version of glibc I've played with has a bug that makes
  799. that code fail when running under a non-root user but with the
  800. proper realtime capabilities (in short, pthread_attr_setschedpolicy
  801. does not check for capabilities, only for the uid being
  802. zero). Newer versions apparently have this fixed. This
  803. workaround temporarily switches the client thread to the
  804. proper scheduler and priority, then starts the realtime
  805. thread so that it can inherit them and finally switches the
  806. client thread back to what it was before. Sigh. For ardour
  807. I have to check again and switch the thread explicitly to
  808. realtime, don't know why or how to debug - nando
  809. */
  810. /* get current scheduler and parameters of the client process */
  811. if ((policy = sched_getscheduler (0)) < 0) {
  812. jack_error ("Cannot get current client scheduler: %s", strerror(errno));
  813. return -1;
  814. }
  815. memset (&client_param, 0, sizeof (client_param));
  816. if (sched_getparam (0, &client_param)) {
  817. jack_error ("Cannot get current client scheduler parameters: %s", strerror(errno));
  818. return -1;
  819. }
  820. /* temporarily change the client process to SCHED_FIFO so that
  821. the realtime thread can inherit the scheduler and priority
  822. */
  823. memset (&temp_param, 0, sizeof (temp_param));
  824. temp_param.sched_priority = client->engine->client_priority;
  825. if (sched_setscheduler(0, SCHED_FIFO, &temp_param)) {
  826. jack_error ("Cannot temporarily set client to RT scheduler: %s", strerror(errno));
  827. return -1;
  828. }
  829. /* prepare the attributes for the realtime thread */
  830. attributes = (pthread_attr_t *) malloc (sizeof (pthread_attr_t));
  831. pthread_attr_init (attributes);
  832. if (pthread_attr_setscope (attributes, PTHREAD_SCOPE_SYSTEM)) {
  833. sched_setscheduler (0, policy, &client_param);
  834. jack_error ("Cannot set scheduling scope for RT thread");
  835. return -1;
  836. }
  837. if (pthread_attr_setinheritsched (attributes, PTHREAD_INHERIT_SCHED)) {
  838. sched_setscheduler (0, policy, &client_param);
  839. jack_error ("Cannot set scheduler inherit policy for RT thread");
  840. return -1;
  841. }
  842. /* create the RT thread */
  843. if (pthread_create (&client->thread, attributes, jack_client_thread, client)) {
  844. sched_setscheduler (0, policy, &client_param);
  845. return -1;
  846. }
  847. /* return the client process to the scheduler it was in before */
  848. if (sched_setscheduler (0, policy, &client_param)) {
  849. jack_error ("Cannot reset original client scheduler: %s", strerror(errno));
  850. return -1;
  851. }
  852. /* check again... inheritance of policy and priority works in jack_simple_client
  853. but not in ardour! So I check again and force the policy if it is not set
  854. correctly. This does not really really work either, the manager thread
  855. of the linuxthreads implementation is left running with SCHED_OTHER,
  856. that is presumably very bad.
  857. */
  858. memset (&client_param, 0, sizeof (client_param));
  859. if (pthread_getschedparam(client->thread, &policy, &client_param) == 0) {
  860. if (policy != SCHED_FIFO) {
  861. /* jack_error ("RT thread did not go SCHED_FIFO, trying again"); */
  862. memset (&client_param, 0, sizeof (client_param));
  863. client_param.sched_priority = client->engine->client_priority;
  864. if (pthread_setschedparam (client->thread, SCHED_FIFO, &client_param)) {
  865. jack_error ("Cannot set (again) FIFO scheduling class for RT thread\n");
  866. return -1;
  867. }
  868. }
  869. }
  870. return 0;
  871. #endif
  872. }
  873. int
  874. jack_activate (jack_client_t *client)
  875. {
  876. jack_request_t req;
  877. /* we need to scribble on our stack to ensure that its memory pages are
  878. * actually mapped (more important for mlockall(2) usage in
  879. * jack_start_thread())
  880. */
  881. #if defined(__APPLE__) && defined(__POWERPC__)
  882. #define BIG_ENOUGH_STACK 10000 // a bigger stack make the application crash...
  883. #else
  884. #define BIG_ENOUGH_STACK 1048576
  885. #endif
  886. char buf[BIG_ENOUGH_STACK];
  887. int i;
  888. for (i = 0; i < BIG_ENOUGH_STACK; i++) {
  889. buf[i] = (char) (i & 0xff);
  890. }
  891. #undef BIG_ENOUGH_STACK
  892. if (client->control->type == ClientInternal || client->control->type == ClientDriver) {
  893. goto startit;
  894. }
  895. /* get the pid of the client process to pass it to engine */
  896. client->control->pid = getpid ();
  897. #ifdef USE_CAPABILITIES
  898. if (client->engine->has_capabilities != 0 &&
  899. client->control->pid != 0 && client->engine->real_time != 0) {
  900. /* we need to ask the engine for realtime capabilities
  901. before trying to start the realtime thread
  902. */
  903. req.type = SetClientCapabilities;
  904. req.x.client_id = client->control->id;
  905. jack_client_deliver_request (client, &req);
  906. if (req.status) {
  907. /* what to do? engine is running realtime, it is using capabilities and has
  908. them (otherwise we would not get an error return) but for some reason it
  909. could not give the client the required capabilities, so for now downgrade
  910. the client so that it still runs, albeit non-realtime - nando
  911. */
  912. jack_error ("could not receive realtime capabilities, client will run non-realtime");
  913. /* XXX wrong, this is a property of the engine
  914. client->engine->real_time = 0;
  915. */
  916. }
  917. }
  918. #endif
  919. if (client->first_active) {
  920. pthread_mutex_init (&client_lock, NULL);
  921. pthread_cond_init (&client_ready, NULL);
  922. pthread_mutex_lock (&client_lock);
  923. if (jack_start_thread (client)) {
  924. pthread_mutex_unlock (&client_lock);
  925. return -1;
  926. }
  927. pthread_cond_wait (&client_ready, &client_lock);
  928. pthread_mutex_unlock (&client_lock);
  929. if (!client->thread_ok) {
  930. jack_error ("could not start client thread");
  931. return -1;
  932. }
  933. client->first_active = FALSE;
  934. }
  935. startit:
  936. req.type = ActivateClient;
  937. req.x.client_id = client->control->id;
  938. return jack_client_deliver_request (client, &req);
  939. }
  940. int
  941. jack_deactivate (jack_client_t *client)
  942. {
  943. jack_request_t req;
  944. req.type = DeactivateClient;
  945. req.x.client_id = client->control->id;
  946. return jack_client_deliver_request (client, &req);
  947. }
  948. int
  949. jack_client_close (jack_client_t *client)
  950. {
  951. JSList *node;
  952. void *status;
  953. if (client->control->active) {
  954. jack_deactivate (client);
  955. }
  956. if (client->control->type == ClientExternal) {
  957. /* stop the thread that communicates with the jack server, only if it was actually running */
  958. if (client->thread_ok){
  959. pthread_cancel (client->thread);
  960. pthread_join (client->thread, &status);
  961. }
  962. munmap ((char *) client->control, sizeof (jack_client_control_t));
  963. munmap ((char *) client->engine, sizeof (jack_control_t));
  964. for (node = client->port_segments; node; node = jack_slist_next (node)) {
  965. jack_port_segment_info_t *si = (jack_port_segment_info_t *) node->data;
  966. munmap ((char *) si->address, si->size);
  967. free (node->data);
  968. }
  969. jack_slist_free (client->port_segments);
  970. if (client->graph_wait_fd) {
  971. close (client->graph_wait_fd);
  972. }
  973. if (client->graph_next_fd) {
  974. close (client->graph_next_fd);
  975. }
  976. close (client->event_fd);
  977. close (client->request_fd);
  978. }
  979. for (node = client->ports; node; node = jack_slist_next (node)) {
  980. free (node->data);
  981. }
  982. jack_slist_free (client->ports);
  983. jack_client_free (client);
  984. return 0;
  985. }
  986. int jack_is_realtime (jack_client_t *client)
  987. {
  988. return client->engine->real_time;
  989. }
  990. jack_nframes_t jack_get_buffer_size (jack_client_t *client)
  991. {
  992. return client->engine->buffer_size;
  993. }
  994. int
  995. jack_connect (jack_client_t *client, const char *source_port, const char *destination_port)
  996. {
  997. jack_request_t req;
  998. req.type = ConnectPorts;
  999. snprintf (req.x.connect.source_port, sizeof (req.x.connect.source_port), "%s", source_port);
  1000. snprintf (req.x.connect.destination_port, sizeof (req.x.connect.destination_port), "%s", destination_port);
  1001. return jack_client_deliver_request (client, &req);
  1002. }
  1003. int
  1004. jack_port_disconnect (jack_client_t *client, jack_port_t *port)
  1005. {
  1006. jack_request_t req;
  1007. pthread_mutex_lock (&port->connection_lock);
  1008. if (port->connections == NULL) {
  1009. pthread_mutex_unlock (&port->connection_lock);
  1010. return 0;
  1011. }
  1012. pthread_mutex_unlock (&port->connection_lock);
  1013. req.type = DisconnectPort;
  1014. req.x.port_info.port_id = port->shared->id;
  1015. return jack_client_deliver_request (client, &req);
  1016. }
  1017. int
  1018. jack_disconnect (jack_client_t *client, const char *source_port, const char *destination_port)
  1019. {
  1020. jack_request_t req;
  1021. req.type = DisconnectPorts;
  1022. snprintf (req.x.connect.source_port, sizeof (req.x.connect.source_port), "%s", source_port);
  1023. snprintf (req.x.connect.destination_port, sizeof (req.x.connect.destination_port), "%s", destination_port);
  1024. return jack_client_deliver_request (client, &req);
  1025. }
  1026. void
  1027. jack_set_error_function (void (*func) (const char *))
  1028. {
  1029. jack_error_callback = func;
  1030. }
  1031. int
  1032. jack_set_graph_order_callback (jack_client_t *client, JackGraphOrderCallback callback, void *arg)
  1033. {
  1034. if (client->control->active) {
  1035. jack_error ("You cannot set callbacks on an active client.");
  1036. return -1;
  1037. }
  1038. client->control->graph_order = callback;
  1039. client->control->graph_order_arg = arg;
  1040. return 0;
  1041. }
  1042. int jack_set_xrun_callback (jack_client_t *client, JackXRunCallback callback, void *arg)
  1043. {
  1044. if (client->control->active) {
  1045. jack_error ("You cannot set callbacks on an active client.");
  1046. return -1;
  1047. }
  1048. client->control->xrun = callback;
  1049. client->control->xrun_arg = arg;
  1050. return 0;
  1051. }
  1052. int
  1053. jack_set_process_callback (jack_client_t *client, JackProcessCallback callback, void *arg)
  1054. {
  1055. if (client->control->active) {
  1056. jack_error ("You cannot set callbacks on an active client.");
  1057. return -1;
  1058. }
  1059. client->control->process_arg = arg;
  1060. client->control->process = callback;
  1061. return 0;
  1062. }
  1063. int
  1064. jack_set_buffer_size_callback (jack_client_t *client, JackBufferSizeCallback callback, void *arg)
  1065. {
  1066. client->control->bufsize_arg = arg;
  1067. client->control->bufsize = callback;
  1068. return 0;
  1069. }
  1070. int
  1071. jack_set_port_registration_callback(jack_client_t *client, JackPortRegistrationCallback callback, void *arg)
  1072. {
  1073. if (client->control->active) {
  1074. jack_error ("You cannot set callbacks on an active client.");
  1075. return -1;
  1076. }
  1077. client->control->port_register_arg = arg;
  1078. client->control->port_register = callback;
  1079. return 0;
  1080. }
  1081. int
  1082. jack_get_process_start_fd (jack_client_t *client)
  1083. {
  1084. /* once this has been called, the client thread
  1085. does not sleep on the graph wait fd.
  1086. */
  1087. client->pollmax = 1;
  1088. return client->graph_wait_fd;
  1089. }
  1090. int
  1091. jack_get_process_done_fd (jack_client_t *client)
  1092. {
  1093. return client->graph_next_fd;
  1094. }
  1095. void
  1096. jack_on_shutdown (jack_client_t *client, void (*function)(void *arg), void *arg)
  1097. {
  1098. client->on_shutdown = function;
  1099. client->on_shutdown_arg = arg;
  1100. }
  1101. const char **
  1102. jack_get_ports (jack_client_t *client,
  1103. const char *port_name_pattern,
  1104. const char *type_name_pattern,
  1105. unsigned long flags)
  1106. {
  1107. jack_control_t *engine;
  1108. const char **matching_ports;
  1109. unsigned long match_cnt;
  1110. jack_port_shared_t *psp;
  1111. unsigned long i;
  1112. regex_t port_regex;
  1113. regex_t type_regex;
  1114. int matching;
  1115. engine = client->engine;
  1116. if (port_name_pattern && port_name_pattern[0]) {
  1117. regcomp (&port_regex, port_name_pattern, REG_EXTENDED|REG_NOSUB);
  1118. }
  1119. if (type_name_pattern && type_name_pattern[0]) {
  1120. regcomp (&type_regex, type_name_pattern, REG_EXTENDED|REG_NOSUB);
  1121. }
  1122. psp = engine->ports;
  1123. match_cnt = 0;
  1124. matching_ports = (const char **) malloc (sizeof (char *) * engine->port_max);
  1125. for (i = 0; i < engine->port_max; i++) {
  1126. matching = 1;
  1127. if (!psp[i].in_use) {
  1128. continue;
  1129. }
  1130. if (flags) {
  1131. if ((psp[i].flags & flags) != flags) {
  1132. matching = 0;
  1133. }
  1134. }
  1135. if (matching && port_name_pattern && port_name_pattern[0]) {
  1136. if (regexec (&port_regex, psp[i].name, 0, NULL, 0)) {
  1137. matching = 0;
  1138. }
  1139. }
  1140. if (matching && type_name_pattern && type_name_pattern[0]) {
  1141. if (regexec (&type_regex, psp[i].type_info.type_name, 0, NULL, 0)) {
  1142. matching = 0;
  1143. }
  1144. }
  1145. if (matching) {
  1146. matching_ports[match_cnt++] = psp[i].name;
  1147. }
  1148. }
  1149. matching_ports[match_cnt] = 0;
  1150. if (match_cnt == 0) {
  1151. free (matching_ports);
  1152. matching_ports = 0;
  1153. }
  1154. return matching_ports;
  1155. }
  1156. float
  1157. jack_cpu_load (jack_client_t *client)
  1158. {
  1159. return client->engine->cpu_load;
  1160. }
  1161. pthread_t
  1162. jack_client_thread_id (jack_client_t *client)
  1163. {
  1164. return client->thread_id;
  1165. }
  1166. #if defined(__APPLE__) && defined(__POWERPC__)
  1167. double __jack_time_ratio;
  1168. void jack_init_time ()
  1169. {
  1170. mach_timebase_info_data_t info;
  1171. mach_timebase_info(&info);
  1172. __jack_time_ratio = ((float)info.numer/info.denom) / 1000;
  1173. }
  1174. #else
  1175. jack_time_t
  1176. jack_get_mhz (void)
  1177. {
  1178. FILE *f = fopen("/proc/cpuinfo", "r");
  1179. if (f == 0)
  1180. {
  1181. perror("can't open /proc/cpuinfo\n");
  1182. exit(1);
  1183. }
  1184. for ( ; ; )
  1185. {
  1186. jack_time_t mhz;
  1187. int ret;
  1188. char buf[1000];
  1189. if (fgets(buf, sizeof(buf), f) == NULL)
  1190. {
  1191. fprintf(stderr, "cannot locate cpu MHz in /proc/cpuinfo\n");
  1192. exit(1);
  1193. }
  1194. #ifdef __powerpc__
  1195. ret = sscanf(buf, "clock\t: %" SCNu64 "MHz", &mhz);
  1196. #else
  1197. ret = sscanf(buf, "cpu MHz : %" SCNu64, &mhz);
  1198. #endif /* __powerpc__ */
  1199. if (ret == 1)
  1200. {
  1201. fclose(f);
  1202. return (jack_time_t)mhz;
  1203. }
  1204. }
  1205. }
  1206. jack_time_t __jack_cpu_mhz;
  1207. void jack_init_time ()
  1208. {
  1209. __jack_cpu_mhz = jack_get_mhz ();
  1210. }
  1211. #endif