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.

1509 lines
36KB

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