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.

3809 lines
93KB

  1. /* -*- mode: c; c-file-style: "bsd"; -*- */
  2. /*
  3. Copyright (C) 2001-2003 Paul Davis
  4. Copyright (C) 2004 Jack O'Quin
  5. This program is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 2 of the License, or
  8. (at your option) any later version.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with this program; if not, write to the Free Software
  15. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  16. */
  17. #include <config.h>
  18. #include <math.h>
  19. #include <unistd.h>
  20. #include <sys/socket.h>
  21. #include <sys/un.h>
  22. #include <sys/stat.h>
  23. #include <errno.h>
  24. #include <fcntl.h>
  25. #include <stdio.h>
  26. #include <stdarg.h>
  27. #ifdef HAVE_STDINT_H
  28. #include <stdint.h>
  29. #endif
  30. #include <dirent.h>
  31. #include <signal.h>
  32. #include <sys/types.h>
  33. #include <string.h>
  34. #include <limits.h>
  35. #include <jack/internal.h>
  36. #include <jack/engine.h>
  37. #include <jack/messagebuffer.h>
  38. #include <jack/driver.h>
  39. #include <jack/shm.h>
  40. #include <jack/thread.h>
  41. #include <sysdeps/poll.h>
  42. #include <sysdeps/ipc.h>
  43. #ifdef USE_MLOCK
  44. #include <sys/mman.h>
  45. #endif /* USE_MLOCK */
  46. #ifdef USE_CAPABILITIES
  47. /* capgetp and capsetp are linux only extensions, not posix */
  48. #undef _POSIX_SOURCE
  49. #include <sys/capability.h>
  50. #endif
  51. #include "clientengine.h"
  52. #include "transengine.h"
  53. typedef struct {
  54. jack_port_internal_t *source;
  55. jack_port_internal_t *destination;
  56. signed int dir; /* -1 = feedback, 0 = self, 1 = forward */
  57. jack_client_internal_t *srcclient;
  58. jack_client_internal_t *dstclient;
  59. } jack_connection_internal_t;
  60. typedef struct _jack_driver_info {
  61. jack_driver_t *(*initialize)(jack_client_t*, const JSList *);
  62. void (*finish);
  63. char (*client_name);
  64. dlhandle handle;
  65. } jack_driver_info_t;
  66. jack_timer_type_t clock_source = JACK_TIMER_SYSTEM_CLOCK;
  67. static int jack_port_assign_buffer (jack_engine_t *,
  68. jack_port_internal_t *);
  69. static jack_port_internal_t *jack_get_port_by_name (jack_engine_t *,
  70. const char *name);
  71. static int jack_rechain_graph (jack_engine_t *engine);
  72. static void jack_clear_fifos (jack_engine_t *engine);
  73. static int jack_port_do_connect (jack_engine_t *engine,
  74. const char *source_port,
  75. const char *destination_port);
  76. static int jack_port_do_disconnect (jack_engine_t *engine,
  77. const char *source_port,
  78. const char *destination_port);
  79. static int jack_port_do_disconnect_all (jack_engine_t *engine,
  80. jack_port_id_t);
  81. static int jack_port_do_unregister (jack_engine_t *engine, jack_request_t *);
  82. static int jack_port_do_register (jack_engine_t *engine, jack_request_t *);
  83. static int jack_do_get_port_connections (jack_engine_t *engine,
  84. jack_request_t *req, int reply_fd);
  85. static int jack_port_disconnect_internal (jack_engine_t *engine,
  86. jack_port_internal_t *src,
  87. jack_port_internal_t *dst);
  88. static int jack_send_connection_notification (jack_engine_t *,
  89. jack_client_id_t,
  90. jack_port_id_t,
  91. jack_port_id_t, int);
  92. static int jack_deliver_event (jack_engine_t *, jack_client_internal_t *,
  93. jack_event_t *);
  94. static void jack_deliver_event_to_all (jack_engine_t *engine,
  95. jack_event_t *event);
  96. static void jack_engine_post_process (jack_engine_t *);
  97. static int jack_use_driver (jack_engine_t *engine, jack_driver_t *driver);
  98. static int jack_run_cycle (jack_engine_t *engine, jack_nframes_t nframes,
  99. float delayed_usecs);
  100. static void jack_engine_delay (jack_engine_t *engine,
  101. float delayed_usecs);
  102. static void jack_engine_driver_exit (jack_engine_t* engine);
  103. static int jack_start_freewheeling (jack_engine_t* engine);
  104. static int jack_stop_freewheeling (jack_engine_t* engine);
  105. static int jack_client_feeds_transitive (jack_client_internal_t *source,
  106. jack_client_internal_t *dest);
  107. static int jack_client_sort (jack_client_internal_t *a,
  108. jack_client_internal_t *b);
  109. static void jack_check_acyclic (jack_engine_t* engine);
  110. static void jack_compute_all_port_total_latencies (jack_engine_t *engine);
  111. static inline int
  112. jack_rolling_interval (jack_time_t period_usecs)
  113. {
  114. return floor ((JACK_ENGINE_ROLLING_INTERVAL * 1000.0f) / period_usecs);
  115. }
  116. void
  117. jack_engine_reset_rolling_usecs (jack_engine_t *engine)
  118. {
  119. memset (engine->rolling_client_usecs, 0,
  120. sizeof (engine->rolling_client_usecs));
  121. engine->rolling_client_usecs_index = 0;
  122. engine->rolling_client_usecs_cnt = 0;
  123. if (engine->driver) {
  124. engine->rolling_interval =
  125. jack_rolling_interval (engine->driver->period_usecs);
  126. } else {
  127. engine->rolling_interval = JACK_ENGINE_ROLLING_INTERVAL;
  128. }
  129. engine->spare_usecs = 0;
  130. }
  131. static inline jack_port_type_info_t *
  132. jack_port_type_info (jack_engine_t *engine, jack_port_internal_t *port)
  133. {
  134. /* Returns a pointer to the port type information in the
  135. engine's shared control structure.
  136. */
  137. return &engine->control->port_types[port->shared->ptype_id];
  138. }
  139. static inline jack_port_buffer_list_t *
  140. jack_port_buffer_list (jack_engine_t *engine, jack_port_internal_t *port)
  141. {
  142. /* Points to the engine's private port buffer list struct. */
  143. return &engine->port_buffers[port->shared->ptype_id];
  144. }
  145. static int
  146. make_directory (const char *path)
  147. {
  148. struct stat statbuf;
  149. if (stat (path, &statbuf)) {
  150. if (errno == ENOENT) {
  151. int mode;
  152. if (getenv ("JACK_PROMISCUOUS_SERVER")) {
  153. mode = 0777;
  154. } else {
  155. mode = 0700;
  156. }
  157. if (mkdir (path, mode) < 0){
  158. jack_error ("cannot create %s directory (%s)\n",
  159. path, strerror (errno));
  160. return -1;
  161. }
  162. } else {
  163. jack_error ("cannot stat() %s\n", path);
  164. return -1;
  165. }
  166. } else {
  167. if (!S_ISDIR (statbuf.st_mode)) {
  168. jack_error ("%s already exists, but is not"
  169. " a directory!\n", path);
  170. return -1;
  171. }
  172. }
  173. return 0;
  174. }
  175. static int
  176. make_socket_subdirectories (const char *server_name)
  177. {
  178. struct stat statbuf;
  179. char server_dir[PATH_MAX+1] = "";
  180. /* check tmpdir directory */
  181. if (stat (jack_tmpdir, &statbuf)) {
  182. jack_error ("cannot stat() %s (%s)\n",
  183. jack_tmpdir, strerror (errno));
  184. return -1;
  185. } else {
  186. if (!S_ISDIR(statbuf.st_mode)) {
  187. jack_error ("%s exists, but is not a directory!\n",
  188. jack_tmpdir);
  189. return -1;
  190. }
  191. }
  192. /* create user subdirectory */
  193. if (make_directory (jack_user_dir ()) < 0) {
  194. return -1;
  195. }
  196. /* create server_name subdirectory */
  197. if (make_directory (jack_server_dir (server_name, server_dir)) < 0) {
  198. return -1;
  199. }
  200. return 0;
  201. }
  202. static int
  203. make_sockets (const char *server_name, int fd[2])
  204. {
  205. struct sockaddr_un addr;
  206. int i;
  207. char server_dir[PATH_MAX+1] = "";
  208. if (make_socket_subdirectories (server_name) < 0) {
  209. return -1;
  210. }
  211. /* First, the master server socket */
  212. if ((fd[0] = socket (AF_UNIX, SOCK_STREAM, 0)) < 0) {
  213. jack_error ("cannot create server socket (%s)",
  214. strerror (errno));
  215. return -1;
  216. }
  217. addr.sun_family = AF_UNIX;
  218. for (i = 0; i < 999; i++) {
  219. snprintf (addr.sun_path, sizeof (addr.sun_path) - 1,
  220. "%s/jack_%d", jack_server_dir (server_name, server_dir), i);
  221. if (access (addr.sun_path, F_OK) != 0) {
  222. break;
  223. }
  224. }
  225. if (i == 999) {
  226. jack_error ("all possible server socket names in use!!!");
  227. close (fd[0]);
  228. return -1;
  229. }
  230. if (bind (fd[0], (struct sockaddr *) &addr, sizeof (addr)) < 0) {
  231. jack_error ("cannot bind server to socket (%s)",
  232. strerror (errno));
  233. close (fd[0]);
  234. return -1;
  235. }
  236. if (listen (fd[0], 1) < 0) {
  237. jack_error ("cannot enable listen on server socket (%s)",
  238. strerror (errno));
  239. close (fd[0]);
  240. return -1;
  241. }
  242. /* Now the client/server event ack server socket */
  243. if ((fd[1] = socket (AF_UNIX, SOCK_STREAM, 0)) < 0) {
  244. jack_error ("cannot create event ACK socket (%s)",
  245. strerror (errno));
  246. close (fd[0]);
  247. return -1;
  248. }
  249. addr.sun_family = AF_UNIX;
  250. for (i = 0; i < 999; i++) {
  251. snprintf (addr.sun_path, sizeof (addr.sun_path) - 1,
  252. "%s/jack_ack_%d", jack_server_dir (server_name, server_dir), i);
  253. if (access (addr.sun_path, F_OK) != 0) {
  254. break;
  255. }
  256. }
  257. if (i == 999) {
  258. jack_error ("all possible server ACK socket names in use!!!");
  259. close (fd[0]);
  260. close (fd[1]);
  261. return -1;
  262. }
  263. if (bind (fd[1], (struct sockaddr *) &addr, sizeof (addr)) < 0) {
  264. jack_error ("cannot bind server to socket (%s)",
  265. strerror (errno));
  266. close (fd[0]);
  267. close (fd[1]);
  268. return -1;
  269. }
  270. if (listen (fd[1], 1) < 0) {
  271. jack_error ("cannot enable listen on server socket (%s)",
  272. strerror (errno));
  273. close (fd[0]);
  274. close (fd[1]);
  275. return -1;
  276. }
  277. return 0;
  278. }
  279. void
  280. jack_engine_place_port_buffers (jack_engine_t* engine,
  281. jack_port_type_id_t ptid,
  282. jack_shmsize_t one_buffer,
  283. jack_shmsize_t size,
  284. unsigned long nports)
  285. {
  286. jack_shmsize_t offset; /* shared memory offset */
  287. jack_port_buffer_info_t *bi;
  288. jack_port_buffer_list_t* pti = &engine->port_buffers[ptid];
  289. jack_port_functions_t *pfuncs = jack_get_port_functions(ptid);
  290. pthread_mutex_lock (&pti->lock);
  291. offset = 0;
  292. if (pti->info) {
  293. /* Buffer info array already allocated for this port
  294. * type. This must be a resize operation, so
  295. * recompute the buffer offsets, but leave the free
  296. * list alone.
  297. */
  298. int i;
  299. bi = pti->info;
  300. while (offset < size) {
  301. bi->offset = offset;
  302. offset += one_buffer;
  303. ++bi;
  304. }
  305. /* update any existing output port offsets */
  306. for (i = 0; i < engine->port_max; i++) {
  307. jack_port_shared_t *port = &engine->control->ports[i];
  308. if (port->in_use &&
  309. (port->flags & JackPortIsOutput) &&
  310. port->ptype_id == ptid) {
  311. bi = engine->internal_ports[i].buffer_info;
  312. if (bi) {
  313. port->offset = bi->offset;
  314. }
  315. }
  316. }
  317. } else {
  318. jack_port_type_info_t* port_type = &engine->control->port_types[ptid];
  319. /* Allocate an array of buffer info structures for all
  320. * the buffers in the segment. Chain them to the free
  321. * list in memory address order, offset zero must come
  322. * first.
  323. */
  324. bi = pti->info = (jack_port_buffer_info_t *)
  325. malloc (nports * sizeof (jack_port_buffer_info_t));
  326. while (offset < size) {
  327. bi->offset = offset;
  328. pti->freelist = jack_slist_append (pti->freelist, bi);
  329. offset += one_buffer;
  330. ++bi;
  331. }
  332. /* Allocate the first buffer of the port segment
  333. * for an empy buffer area.
  334. * NOTE: audio buffer is zeroed in its buffer_init function.
  335. */
  336. bi = (jack_port_buffer_info_t *) pti->freelist->data;
  337. pti->freelist = jack_slist_remove_link (pti->freelist,
  338. pti->freelist);
  339. port_type->zero_buffer_offset = bi->offset;
  340. if (ptid == JACK_AUDIO_PORT_TYPE)
  341. engine->silent_buffer = bi;
  342. }
  343. /* initialize buffers */
  344. {
  345. int i;
  346. jack_shm_info_t *shm_info = &engine->port_segment[ptid];
  347. char* shm_segment = (char *) jack_shm_addr(shm_info);
  348. bi = pti->info;
  349. for (i=0; i<nports; ++i, ++bi)
  350. pfuncs->buffer_init(shm_segment + bi->offset, one_buffer);
  351. }
  352. pthread_mutex_unlock (&pti->lock);
  353. }
  354. // JOQ: this should have a return code...
  355. static void
  356. jack_resize_port_segment (jack_engine_t *engine,
  357. jack_port_type_id_t ptid,
  358. unsigned long nports)
  359. {
  360. jack_event_t event;
  361. jack_shmsize_t one_buffer; /* size of one buffer */
  362. jack_shmsize_t size; /* segment size */
  363. jack_port_type_info_t* port_type = &engine->control->port_types[ptid];
  364. jack_shm_info_t* shm_info = &engine->port_segment[ptid];
  365. if (port_type->buffer_scale_factor < 0) {
  366. one_buffer = port_type->buffer_size;
  367. } else {
  368. one_buffer = sizeof (jack_default_audio_sample_t)
  369. * port_type->buffer_scale_factor
  370. * engine->control->buffer_size;
  371. }
  372. size = nports * one_buffer;
  373. if (shm_info->attached_at == 0) {
  374. if (jack_shmalloc (size, shm_info)) {
  375. jack_error ("cannot create new port segment of %d"
  376. " bytes (%s)",
  377. size,
  378. strerror (errno));
  379. return;
  380. }
  381. if (jack_attach_shm (shm_info)) {
  382. jack_error ("cannot attach to new port segment "
  383. "(%s)", strerror (errno));
  384. return;
  385. }
  386. engine->control->port_types[ptid].shm_registry_index =
  387. shm_info->index;
  388. } else {
  389. /* resize existing buffer segment */
  390. if (jack_resize_shm (shm_info, size)) {
  391. jack_error ("cannot resize port segment to %d bytes,"
  392. " (%s)", size,
  393. strerror (errno));
  394. return;
  395. }
  396. }
  397. jack_engine_place_port_buffers (engine, ptid, one_buffer, size, nports);
  398. #ifdef USE_MLOCK
  399. if (engine->control->real_time) {
  400. /* Although we've called mlockall(CURRENT|FUTURE), the
  401. * Linux VM manager still allows newly allocated pages
  402. * to fault on first reference. This mlock() ensures
  403. * that any new pages are present before restarting
  404. * the process cycle. Since memory locks do not
  405. * stack, they can still be unlocked with a single
  406. * munlockall().
  407. */
  408. int rc = mlock (jack_shm_addr (shm_info), size);
  409. if (rc < 0) {
  410. jack_error("JACK: unable to mlock() port buffers: "
  411. "%s", strerror(errno));
  412. }
  413. }
  414. #endif /* USE_MLOCK */
  415. /* Tell everybody about this segment. */
  416. event.type = AttachPortSegment;
  417. event.y.ptid = ptid;
  418. jack_deliver_event_to_all (engine, &event);
  419. }
  420. /* The driver invokes this callback both initially and whenever its
  421. * buffer size changes.
  422. */
  423. static int
  424. jack_driver_buffer_size (jack_engine_t *engine, jack_nframes_t nframes)
  425. {
  426. int i;
  427. jack_event_t event;
  428. JSList *node;
  429. VERBOSE (engine, "new buffer size %" PRIu32 "\n", nframes);
  430. engine->control->buffer_size = nframes;
  431. if (engine->driver)
  432. engine->rolling_interval =
  433. jack_rolling_interval (engine->driver->period_usecs);
  434. for (i = 0; i < engine->control->n_port_types; ++i) {
  435. jack_resize_port_segment (engine, i, engine->control->port_max);
  436. }
  437. /* update shared client copy of nframes */
  438. jack_lock_graph (engine);
  439. for (node = engine->clients; node; node = jack_slist_next (node)) {
  440. jack_client_internal_t *client = node->data;
  441. client->control->nframes = nframes;
  442. }
  443. jack_unlock_graph (engine);
  444. event.type = BufferSizeChange;
  445. jack_deliver_event_to_all (engine, &event);
  446. return 0;
  447. }
  448. /* handle client SetBufferSize request */
  449. int
  450. jack_set_buffer_size_request (jack_engine_t *engine, jack_nframes_t nframes)
  451. {
  452. /* precondition: caller holds the request_lock */
  453. int rc;
  454. jack_driver_t* driver = engine->driver;
  455. if (driver == NULL)
  456. return ENXIO; /* no such device */
  457. if (!jack_power_of_two(nframes)) {
  458. jack_error("buffer size %" PRIu32 " not a power of 2",
  459. nframes);
  460. return EINVAL;
  461. }
  462. rc = driver->bufsize(driver, nframes);
  463. if (rc != 0)
  464. jack_error("driver does not support %" PRIu32
  465. "-frame buffers", nframes);
  466. return rc;
  467. }
  468. static JSList *
  469. jack_process_internal(jack_engine_t *engine, JSList *node,
  470. jack_nframes_t nframes)
  471. {
  472. jack_client_internal_t *client;
  473. jack_client_control_t *ctl;
  474. client = (jack_client_internal_t *) node->data;
  475. ctl = client->control;
  476. /* internal client */
  477. DEBUG ("invoking an internal client's callbacks");
  478. ctl->state = Running;
  479. engine->current_client = client;
  480. /* XXX how to time out an internal client? */
  481. if (ctl->sync_cb)
  482. jack_call_sync_client (ctl->private_client);
  483. if (ctl->process)
  484. if (ctl->process (nframes, ctl->process_arg)) {
  485. jack_error ("internal client %s failed", ctl->name);
  486. engine->process_errors++;
  487. }
  488. if (ctl->timebase_cb)
  489. jack_call_timebase_master (ctl->private_client);
  490. ctl->state = Finished;
  491. if (engine->process_errors)
  492. return NULL; /* will stop the loop */
  493. else
  494. return jack_slist_next (node);
  495. }
  496. #ifdef JACK_USE_MACH_THREADS
  497. static JSList *
  498. jack_process_external(jack_engine_t *engine, JSList *node)
  499. {
  500. jack_client_internal_t * client = (jack_client_internal_t *) node->data;
  501. jack_client_control_t *ctl;
  502. client = (jack_client_internal_t *) node->data;
  503. ctl = client->control;
  504. engine->current_client = client;
  505. // a race exists if we do this after the write(2)
  506. ctl->state = Triggered;
  507. ctl->signalled_at = jack_get_microseconds();
  508. ctl->awake_at = 0;
  509. ctl->finished_at = 0;
  510. if (jack_client_resume(client) < 0) {
  511. jack_error("Client will be removed\n");
  512. ctl->state = Finished;
  513. }
  514. return jack_slist_next (node);
  515. }
  516. #else /* !JACK_USE_MACH_THREADS */
  517. static JSList *
  518. jack_process_external(jack_engine_t *engine, JSList *node)
  519. {
  520. int status = 0;
  521. char c = 0;
  522. struct pollfd pfd[1];
  523. int poll_timeout;
  524. jack_client_internal_t *client;
  525. jack_client_control_t *ctl;
  526. jack_time_t now, then;
  527. client = (jack_client_internal_t *) node->data;
  528. ctl = client->control;
  529. /* external subgraph */
  530. /* a race exists if we do this after the write(2) */
  531. ctl->state = Triggered;
  532. ctl->signalled_at = jack_get_microseconds();
  533. ctl->awake_at = 0;
  534. ctl->finished_at = 0;
  535. engine->current_client = client;
  536. DEBUG ("calling process() on an external subgraph, fd==%d",
  537. client->subgraph_start_fd);
  538. if (write (client->subgraph_start_fd, &c, sizeof (c)) != sizeof (c)) {
  539. jack_error ("cannot initiate graph processing (%s)",
  540. strerror (errno));
  541. engine->process_errors++;
  542. return NULL; /* will stop the loop */
  543. }
  544. then = jack_get_microseconds ();
  545. if (engine->freewheeling) {
  546. poll_timeout = 10000; /* 10 seconds */
  547. } else {
  548. poll_timeout = (engine->client_timeout_msecs > 0 ?
  549. engine->client_timeout_msecs :
  550. 1 + engine->driver->period_usecs/1000);
  551. }
  552. pfd[0].fd = client->subgraph_wait_fd;
  553. pfd[0].events = POLLERR|POLLIN|POLLHUP|POLLNVAL;
  554. DEBUG ("waiting on fd==%d for process() subgraph to finish",
  555. client->subgraph_wait_fd);
  556. if (poll (pfd, 1, poll_timeout) < 0) {
  557. jack_error ("poll on subgraph processing failed (%s)",
  558. strerror (errno));
  559. status = -1;
  560. }
  561. DEBUG ("\n\n\n\n\n back from subgraph poll, revents = 0x%x\n\n\n", pfd[0].revents);
  562. if (pfd[0].revents & ~POLLIN) {
  563. jack_error ("subgraph starting at %s lost client",
  564. client->control->name);
  565. status = -2;
  566. }
  567. if (pfd[0].revents & POLLIN) {
  568. status = 0;
  569. } else {
  570. jack_error ("subgraph starting at %s timed out "
  571. "(subgraph_wait_fd=%d, status = %d, state = %s)",
  572. client->control->name,
  573. client->subgraph_wait_fd, status,
  574. jack_client_state_name (client));
  575. status = 1;
  576. }
  577. now = jack_get_microseconds ();
  578. if (status != 0) {
  579. VERBOSE (engine, "at %" PRIu64
  580. " waiting on %d for %" PRIu64
  581. " usecs, status = %d sig = %" PRIu64
  582. " awa = %" PRIu64 " fin = %" PRIu64
  583. " dur=%" PRIu64 "\n",
  584. now,
  585. client->subgraph_wait_fd,
  586. now - then,
  587. status,
  588. ctl->signalled_at,
  589. ctl->awake_at,
  590. ctl->finished_at,
  591. ctl->finished_at? (ctl->finished_at -
  592. ctl->signalled_at): 0);
  593. /* we can only consider the timeout a client error if
  594. * it actually woke up. its possible that the kernel
  595. * scheduler screwed us up and never woke up the
  596. * client in time. sigh.
  597. */
  598. if (ctl->awake_at > 0) {
  599. ctl->timed_out++;
  600. }
  601. engine->process_errors++;
  602. return NULL; /* will stop the loop */
  603. } else {
  604. DEBUG ("reading byte from subgraph_wait_fd==%d",
  605. client->subgraph_wait_fd);
  606. if (read (client->subgraph_wait_fd, &c, sizeof(c))
  607. != sizeof (c)) {
  608. jack_error ("pp: cannot clean up byte from graph wait "
  609. "fd (%s)", strerror (errno));
  610. client->error++;
  611. return NULL; /* will stop the loop */
  612. }
  613. }
  614. /* Move to next internal client (or end of client list) */
  615. while (node) {
  616. if (jack_client_is_internal ((jack_client_internal_t *)
  617. node->data)) {
  618. break;
  619. }
  620. node = jack_slist_next (node);
  621. }
  622. return node;
  623. }
  624. #endif /* JACK_USE_MACH_THREADS */
  625. static int
  626. jack_engine_process (jack_engine_t *engine, jack_nframes_t nframes)
  627. {
  628. /* precondition: caller has graph_lock */
  629. jack_client_internal_t *client;
  630. JSList *node;
  631. engine->process_errors = 0;
  632. engine->watchdog_check = 1;
  633. for (node = engine->clients; node; node = jack_slist_next (node)) {
  634. jack_client_control_t *ctl =
  635. ((jack_client_internal_t *) node->data)->control;
  636. ctl->state = NotTriggered;
  637. ctl->nframes = nframes;
  638. ctl->timed_out = 0;
  639. }
  640. for (node = engine->clients; engine->process_errors == 0 && node; ) {
  641. client = (jack_client_internal_t *) node->data;
  642. DEBUG ("considering client %s for processing",
  643. client->control->name);
  644. if (!client->control->active || client->control->dead) {
  645. node = jack_slist_next (node);
  646. } else if (jack_client_is_internal (client)) {
  647. node = jack_process_internal (engine, node, nframes);
  648. } else {
  649. node = jack_process_external (engine, node);
  650. }
  651. }
  652. return engine->process_errors > 0;
  653. }
  654. static void
  655. jack_calc_cpu_load(jack_engine_t *engine)
  656. {
  657. jack_time_t cycle_end = jack_get_microseconds ();
  658. /* store the execution time for later averaging */
  659. engine->rolling_client_usecs[engine->rolling_client_usecs_index++] =
  660. cycle_end - engine->control->current_time.usecs;
  661. //printf ("cycle_end - engine->control->current_time.usecs %ld\n",
  662. // (long) (cycle_end - engine->control->current_time.usecs));
  663. if (engine->rolling_client_usecs_index >= JACK_ENGINE_ROLLING_COUNT) {
  664. engine->rolling_client_usecs_index = 0;
  665. }
  666. /* every so often, recompute the current maximum use over the
  667. last JACK_ENGINE_ROLLING_COUNT client iterations.
  668. */
  669. if (++engine->rolling_client_usecs_cnt
  670. % engine->rolling_interval == 0) {
  671. float max_usecs = 0.0f;
  672. int i;
  673. for (i = 0; i < JACK_ENGINE_ROLLING_COUNT; i++) {
  674. if (engine->rolling_client_usecs[i] > max_usecs) {
  675. max_usecs = engine->rolling_client_usecs[i];
  676. }
  677. }
  678. if (max_usecs > engine->max_usecs) {
  679. engine->max_usecs = max_usecs;
  680. }
  681. if (max_usecs < engine->driver->period_usecs) {
  682. engine->spare_usecs =
  683. engine->driver->period_usecs - max_usecs;
  684. } else {
  685. engine->spare_usecs = 0;
  686. }
  687. engine->control->cpu_load =
  688. (1.0f - (engine->spare_usecs /
  689. engine->driver->period_usecs)) * 50.0f
  690. + (engine->control->cpu_load * 0.5f);
  691. VERBOSE (engine, "load = %.4f max usecs: %.3f, "
  692. "spare = %.3f\n", engine->control->cpu_load,
  693. max_usecs, engine->spare_usecs);
  694. }
  695. }
  696. static void
  697. jack_engine_post_process (jack_engine_t *engine)
  698. {
  699. /* precondition: caller holds the graph lock. */
  700. jack_client_control_t *ctl;
  701. jack_client_internal_t *client;
  702. JSList *node;
  703. int need_remove = FALSE;
  704. jack_transport_cycle_end (engine);
  705. /* find any clients that need removal due to timeouts, etc. */
  706. for (node = engine->clients; node; node = jack_slist_next (node) ) {
  707. client = (jack_client_internal_t *) node->data;
  708. ctl = client->control;
  709. /* this check is invalid for internal clients and
  710. external clients with no process callback.
  711. */
  712. if (!jack_client_is_internal (client) && ctl->process) {
  713. if (ctl->awake_at != 0 &&
  714. ctl->state > NotTriggered &&
  715. ctl->state != Finished &&
  716. ctl->timed_out++) {
  717. VERBOSE(engine, "client %s error: awake_at = %"
  718. PRIu64
  719. " state = %d timed_out = %d\n",
  720. ctl->name,
  721. ctl->awake_at,
  722. ctl->state,
  723. ctl->timed_out);
  724. client->error++;
  725. }
  726. }
  727. if (client->error) {
  728. need_remove = TRUE;
  729. }
  730. }
  731. if (need_remove) {
  732. jack_remove_clients (engine);
  733. }
  734. jack_calc_cpu_load (engine);
  735. }
  736. #ifndef JACK_USE_MACH_THREADS
  737. static void *
  738. jack_watchdog_thread (void *arg)
  739. {
  740. jack_engine_t *engine = (jack_engine_t *) arg;
  741. engine->watchdog_check = 0;
  742. while (1) {
  743. usleep (1000 * JACKD_WATCHDOG_TIMEOUT);
  744. if (!engine->freewheeling && engine->watchdog_check == 0) {
  745. jack_error ("jackd watchdog: timeout - killing jackd");
  746. /* Kill the current client (guilt by association). */
  747. if (engine->current_client) {
  748. kill (engine->current_client->
  749. control->pid, SIGKILL);
  750. }
  751. /* kill our process group, try to get a dump */
  752. kill (-getpgrp(), SIGABRT);
  753. /*NOTREACHED*/
  754. exit (1);
  755. }
  756. engine->watchdog_check = 0;
  757. }
  758. }
  759. static int
  760. jack_start_watchdog (jack_engine_t *engine)
  761. {
  762. int watchdog_priority = engine->rtpriority + 10;
  763. int max_priority = sched_get_priority_max (SCHED_FIFO);
  764. if ((max_priority != -1) &&
  765. (max_priority < watchdog_priority))
  766. watchdog_priority = max_priority;
  767. if (jack_client_create_thread (NULL, &engine->watchdog_thread, watchdog_priority,
  768. TRUE, jack_watchdog_thread, engine)) {
  769. jack_error ("cannot start watchdog thread");
  770. return -1;
  771. }
  772. return 0;
  773. }
  774. #endif /* !JACK_USE_MACH_THREADS */
  775. void
  776. jack_engine_munge_backend_port_names (jack_engine_t* engine)
  777. {
  778. int out_cnt = 1;
  779. int in_cnt = 1;
  780. int i;
  781. char* backend_client_name = (char*) engine->driver->internal_client->control->name;
  782. size_t len = strlen (backend_client_name);
  783. for (i = 0; i < engine->port_max; i++) {
  784. jack_port_shared_t* port = &engine->control->ports[i];
  785. if (strncmp (port->name, backend_client_name, len) == 0) {
  786. /* save the backend's own name */
  787. char name[JACK_CLIENT_NAME_SIZE+JACK_PORT_NAME_SIZE];
  788. snprintf (name, sizeof (name), "%s", engine->control->ports[i].name);
  789. /* replace input port names, and use backend's original as an alias */
  790. if ((port->flags & (JackPortIsPhysical|JackPortIsInput)) == (JackPortIsPhysical|JackPortIsInput)) {
  791. snprintf (port->name, sizeof (port->name), "system:playback_%d", out_cnt++);
  792. strcpy (port->alias1, name);
  793. continue;
  794. }
  795. /* replace output port names, and use backend's original as an alias */
  796. if ((port->flags & (JackPortIsPhysical|JackPortIsOutput)) == (JackPortIsPhysical|JackPortIsOutput)) {
  797. snprintf (port->name, sizeof (port->name), "system:capture_%d", in_cnt++);
  798. strcpy (port->alias1, name);
  799. continue;
  800. }
  801. }
  802. }
  803. }
  804. static jack_driver_info_t *
  805. jack_load_driver (jack_engine_t *engine, jack_driver_desc_t * driver_desc)
  806. {
  807. const char *errstr;
  808. jack_driver_info_t *info;
  809. info = (jack_driver_info_t *) calloc (1, sizeof (*info));
  810. info->handle = dlopen (driver_desc->file, RTLD_NOW|RTLD_GLOBAL);
  811. if (info->handle == NULL) {
  812. if ((errstr = dlerror ()) != 0) {
  813. jack_error ("can't load \"%s\": %s", driver_desc->file,
  814. errstr);
  815. } else {
  816. jack_error ("bizarre error loading driver shared "
  817. "object %s", driver_desc->file);
  818. }
  819. goto fail;
  820. }
  821. info->initialize = dlsym (info->handle, "driver_initialize");
  822. if ((errstr = dlerror ()) != 0) {
  823. jack_error ("no initialize function in shared object %s\n",
  824. driver_desc->file);
  825. goto fail;
  826. }
  827. info->finish = dlsym (info->handle, "driver_finish");
  828. if ((errstr = dlerror ()) != 0) {
  829. jack_error ("no finish function in in shared driver object %s",
  830. driver_desc->file);
  831. goto fail;
  832. }
  833. info->client_name = (char *) dlsym (info->handle, "driver_client_name");
  834. if ((errstr = dlerror ()) != 0) {
  835. jack_error ("no client name in in shared driver object %s",
  836. driver_desc->file);
  837. goto fail;
  838. }
  839. return info;
  840. fail:
  841. if (info->handle) {
  842. dlclose (info->handle);
  843. }
  844. free (info);
  845. return NULL;
  846. }
  847. void
  848. jack_driver_unload (jack_driver_t *driver)
  849. {
  850. driver->finish (driver);
  851. dlclose (driver->handle);
  852. }
  853. int
  854. jack_engine_load_driver (jack_engine_t *engine,
  855. jack_driver_desc_t * driver_desc,
  856. JSList * driver_params)
  857. {
  858. jack_client_internal_t *client;
  859. jack_driver_t *driver;
  860. jack_driver_info_t *info;
  861. if ((info = jack_load_driver (engine, driver_desc)) == NULL) {
  862. return -1;
  863. }
  864. if ((client = jack_create_driver_client (engine, info->client_name)
  865. ) == NULL) {
  866. return -1;
  867. }
  868. if ((driver = info->initialize (client->control->private_client,
  869. driver_params)) == NULL) {
  870. free (info);
  871. return -1;
  872. }
  873. driver->handle = info->handle;
  874. driver->finish = info->finish;
  875. driver->internal_client = client;
  876. free (info);
  877. if (jack_use_driver (engine, driver)) {
  878. jack_driver_unload (driver);
  879. jack_client_delete (engine, client);
  880. return -1;
  881. }
  882. engine->driver_desc = driver_desc;
  883. engine->driver_params = driver_params;
  884. if (engine->control->real_time) {
  885. /* Stephane Letz : letz@grame.fr Watch dog thread is
  886. * not needed on MacOSX since CoreAudio drivers
  887. * already contains a similar mechanism.
  888. */
  889. #ifndef JACK_USE_MACH_THREADS
  890. if (jack_start_watchdog (engine)) {
  891. return -1;
  892. }
  893. engine->watchdog_check = 1;
  894. #endif
  895. }
  896. return 0;
  897. }
  898. #ifdef USE_CAPABILITIES
  899. static int check_capabilities (jack_engine_t *engine)
  900. {
  901. cap_t caps = cap_init();
  902. cap_flag_value_t cap;
  903. pid_t pid;
  904. int have_all_caps = 1;
  905. if (caps == NULL) {
  906. VERBOSE (engine, "check: could not allocate capability"
  907. " working storage\n");
  908. return 0;
  909. }
  910. pid = getpid ();
  911. cap_clear (caps);
  912. if (capgetp (pid, caps)) {
  913. VERBOSE (engine, "check: could not get capabilities "
  914. "for process %d\n", pid);
  915. return 0;
  916. }
  917. /* check that we are able to give capabilites to other processes */
  918. cap_get_flag(caps, CAP_SETPCAP, CAP_EFFECTIVE, &cap);
  919. if (cap == CAP_CLEAR) {
  920. have_all_caps = 0;
  921. goto done;
  922. }
  923. /* check that we have the capabilities we want to transfer */
  924. cap_get_flag(caps, CAP_SYS_NICE, CAP_EFFECTIVE, &cap);
  925. if (cap == CAP_CLEAR) {
  926. have_all_caps = 0;
  927. goto done;
  928. }
  929. cap_get_flag(caps, CAP_SYS_RESOURCE, CAP_EFFECTIVE, &cap);
  930. if (cap == CAP_CLEAR) {
  931. have_all_caps = 0;
  932. goto done;
  933. }
  934. cap_get_flag(caps, CAP_IPC_LOCK, CAP_EFFECTIVE, &cap);
  935. if (cap == CAP_CLEAR) {
  936. have_all_caps = 0;
  937. goto done;
  938. }
  939. done:
  940. cap_free (caps);
  941. return have_all_caps;
  942. }
  943. static int give_capabilities (jack_engine_t *engine, pid_t pid)
  944. {
  945. cap_t caps = cap_init();
  946. const unsigned caps_size = 3;
  947. cap_value_t cap_list[] = {CAP_SYS_NICE, CAP_SYS_RESOURCE, CAP_IPC_LOCK};
  948. if (caps == NULL) {
  949. VERBOSE (engine, "give: could not allocate capability"
  950. " working storage\n");
  951. return -1;
  952. }
  953. cap_clear(caps);
  954. if (capgetp (pid, caps)) {
  955. VERBOSE (engine, "give: could not get current "
  956. "capabilities for process %d\n", pid);
  957. cap_clear(caps);
  958. }
  959. cap_set_flag(caps, CAP_EFFECTIVE, caps_size, cap_list , CAP_SET);
  960. cap_set_flag(caps, CAP_INHERITABLE, caps_size, cap_list , CAP_SET);
  961. cap_set_flag(caps, CAP_PERMITTED, caps_size, cap_list , CAP_SET);
  962. if (capsetp (pid, caps)) {
  963. cap_free (caps);
  964. return -1;
  965. }
  966. cap_free (caps);
  967. return 0;
  968. }
  969. static int
  970. jack_set_client_capabilities (jack_engine_t *engine, pid_t cap_pid)
  971. {
  972. int ret = -1;
  973. /* before sending this request the client has
  974. already checked that the engine has
  975. realtime capabilities, that it is running
  976. realtime and that the pid is defined
  977. */
  978. if ((ret = give_capabilities (engine, cap_pid)) != 0) {
  979. jack_error ("could not give capabilities to "
  980. "process %d\n",
  981. cap_pid);
  982. } else {
  983. VERBOSE (engine, "gave capabilities to"
  984. " process %d\n",
  985. cap_pid);
  986. }
  987. return ret;
  988. }
  989. #endif /* USE_CAPABILITIES */
  990. /* perform internal or external client request
  991. *
  992. * reply_fd is NULL for internal requests
  993. */
  994. static void
  995. do_request (jack_engine_t *engine, jack_request_t *req, int *reply_fd)
  996. {
  997. /* The request_lock serializes internal requests (from any
  998. * server thread) with external requests (always from the
  999. * server thread). */
  1000. pthread_mutex_lock (&engine->request_lock);
  1001. DEBUG ("got a request of type %d", req->type);
  1002. switch (req->type) {
  1003. case RegisterPort:
  1004. req->status = jack_port_do_register (engine, req);
  1005. break;
  1006. case UnRegisterPort:
  1007. req->status = jack_port_do_unregister (engine, req);
  1008. break;
  1009. case ConnectPorts:
  1010. req->status = jack_port_do_connect
  1011. (engine, req->x.connect.source_port,
  1012. req->x.connect.destination_port);
  1013. break;
  1014. case DisconnectPort:
  1015. req->status = jack_port_do_disconnect_all
  1016. (engine, req->x.port_info.port_id);
  1017. break;
  1018. case DisconnectPorts:
  1019. req->status = jack_port_do_disconnect
  1020. (engine, req->x.connect.source_port,
  1021. req->x.connect.destination_port);
  1022. break;
  1023. case ActivateClient:
  1024. req->status = jack_client_activate (engine, req->x.client_id);
  1025. break;
  1026. case DeactivateClient:
  1027. req->status = jack_client_deactivate (engine, req->x.client_id);
  1028. break;
  1029. case SetTimeBaseClient:
  1030. req->status = jack_timebase_set (engine,
  1031. req->x.timebase.client_id,
  1032. req->x.timebase.conditional);
  1033. break;
  1034. case ResetTimeBaseClient:
  1035. req->status = jack_timebase_reset (engine, req->x.client_id);
  1036. break;
  1037. case SetSyncClient:
  1038. req->status =
  1039. jack_transport_client_set_sync (engine,
  1040. req->x.client_id);
  1041. break;
  1042. case ResetSyncClient:
  1043. req->status =
  1044. jack_transport_client_reset_sync (engine,
  1045. req->x.client_id);
  1046. break;
  1047. case SetSyncTimeout:
  1048. req->status = jack_transport_set_sync_timeout (engine,
  1049. req->x.timeout);
  1050. break;
  1051. #ifdef USE_CAPABILITIES
  1052. case SetClientCapabilities:
  1053. req->status = jack_set_client_capabilities (engine,
  1054. req->x.cap_pid);
  1055. break;
  1056. #endif /* USE_CAPABILITIES */
  1057. case GetPortConnections:
  1058. case GetPortNConnections:
  1059. //JOQ bug: reply_fd may be NULL if internal request
  1060. if ((req->status =
  1061. jack_do_get_port_connections (engine, req, *reply_fd))
  1062. == 0) {
  1063. /* we have already replied, don't do it again */
  1064. *reply_fd = -1;
  1065. }
  1066. break;
  1067. case FreeWheel:
  1068. req->status = jack_start_freewheeling (engine);
  1069. break;
  1070. case StopFreeWheel:
  1071. req->status = jack_stop_freewheeling (engine);
  1072. break;
  1073. case SetBufferSize:
  1074. req->status = jack_set_buffer_size_request (engine,
  1075. req->x.nframes);
  1076. break;
  1077. case IntClientHandle:
  1078. jack_intclient_handle_request (engine, req);
  1079. break;
  1080. case IntClientLoad:
  1081. jack_intclient_load_request (engine, req);
  1082. break;
  1083. case IntClientName:
  1084. jack_intclient_name_request (engine, req);
  1085. break;
  1086. case IntClientUnload:
  1087. jack_intclient_unload_request (engine, req);
  1088. break;
  1089. case RecomputeTotalLatencies:
  1090. jack_lock_graph (engine);
  1091. jack_compute_all_port_total_latencies (engine);
  1092. jack_unlock_graph (engine);
  1093. req->status = 0;
  1094. break;
  1095. default:
  1096. /* some requests are handled entirely on the client
  1097. * side, by adjusting the shared memory area(s) */
  1098. break;
  1099. }
  1100. pthread_mutex_unlock (&engine->request_lock);
  1101. DEBUG ("status of request: %d", req->status);
  1102. }
  1103. int
  1104. internal_client_request (void* ptr, jack_request_t *request)
  1105. {
  1106. do_request ((jack_engine_t*) ptr, request, NULL);
  1107. return request->status;
  1108. }
  1109. static int
  1110. handle_external_client_request (jack_engine_t *engine, int fd)
  1111. {
  1112. jack_request_t req;
  1113. jack_client_internal_t *client = 0;
  1114. int reply_fd;
  1115. JSList *node;
  1116. ssize_t r;
  1117. DEBUG ("HIT: before lock");
  1118. jack_lock_graph (engine);
  1119. DEBUG ("HIT: before for");
  1120. for (node = engine->clients; node; node = jack_slist_next (node)) {
  1121. if (((jack_client_internal_t *) node->data)->request_fd == fd) {
  1122. DEBUG ("HIT: in for");
  1123. client = (jack_client_internal_t *) node->data;
  1124. break;
  1125. }
  1126. }
  1127. DEBUG ("HIT: after for");
  1128. jack_unlock_graph (engine);
  1129. if (client == NULL) {
  1130. jack_error ("client input on unknown fd %d!", fd);
  1131. return -1;
  1132. }
  1133. if ((r = read (client->request_fd, &req, sizeof (req)))
  1134. < (ssize_t) sizeof (req)) {
  1135. jack_error ("cannot read request from client (%d/%d/%s)",
  1136. r, sizeof(req), strerror (errno));
  1137. client->error++;
  1138. return -1;
  1139. }
  1140. reply_fd = client->request_fd;
  1141. do_request (engine, &req, &reply_fd);
  1142. if (reply_fd >= 0) {
  1143. DEBUG ("replying to client");
  1144. if (write (reply_fd, &req, sizeof (req))
  1145. < (ssize_t) sizeof (req)) {
  1146. jack_error ("cannot write request result to client");
  1147. return -1;
  1148. }
  1149. } else {
  1150. DEBUG ("*not* replying to client");
  1151. }
  1152. return 0;
  1153. }
  1154. static int
  1155. handle_client_ack_connection (jack_engine_t *engine, int client_fd)
  1156. {
  1157. jack_client_internal_t *client;
  1158. jack_client_connect_ack_request_t req;
  1159. jack_client_connect_ack_result_t res;
  1160. if (read (client_fd, &req, sizeof (req)) != sizeof (req)) {
  1161. jack_error ("cannot read ACK connection request from client");
  1162. return -1;
  1163. }
  1164. if ((client = jack_client_internal_by_id (engine, req.client_id))
  1165. == NULL) {
  1166. jack_error ("unknown client ID in ACK connection request");
  1167. return -1;
  1168. }
  1169. client->event_fd = client_fd;
  1170. res.status = 0;
  1171. if (write (client->event_fd, &res, sizeof (res)) != sizeof (res)) {
  1172. jack_error ("cannot write ACK connection response to client");
  1173. return -1;
  1174. }
  1175. return 0;
  1176. }
  1177. static void *
  1178. jack_server_thread (void *arg)
  1179. {
  1180. jack_engine_t *engine = (jack_engine_t *) arg;
  1181. struct sockaddr_un client_addr;
  1182. socklen_t client_addrlen;
  1183. struct pollfd *pfd;
  1184. int client_socket;
  1185. int done = 0;
  1186. int i;
  1187. int max;
  1188. engine->pfd[0].fd = engine->fds[0];
  1189. engine->pfd[0].events = POLLIN|POLLERR;
  1190. engine->pfd[1].fd = engine->fds[1];
  1191. engine->pfd[1].events = POLLIN|POLLERR;
  1192. engine->pfd_max = 2;
  1193. pfd = engine->pfd;
  1194. max = engine->pfd_max;
  1195. while (!done) {
  1196. DEBUG ("start while");
  1197. if (poll (pfd, max, 10000) < 0) {
  1198. if (errno == EINTR) {
  1199. continue;
  1200. }
  1201. jack_error ("poll failed (%s)", strerror (errno));
  1202. break;
  1203. }
  1204. DEBUG("server thread back from poll");
  1205. /* Stephane Letz: letz@grame.fr : has to be added
  1206. * otherwise pthread_cancel() does not work on MacOSX */
  1207. pthread_testcancel();
  1208. /* check each client socket before handling other request*/
  1209. for (i = 2; i < max; i++) {
  1210. if (pfd[i].fd < 0) {
  1211. continue;
  1212. }
  1213. if (pfd[i].revents & ~POLLIN) {
  1214. jack_client_disconnect (engine, pfd[i].fd);
  1215. } else if (pfd[i].revents & POLLIN) {
  1216. if (handle_external_client_request
  1217. (engine, pfd[i].fd)) {
  1218. jack_error ("could not handle external"
  1219. " client request");
  1220. #ifdef JACK_USE_MACH_THREADS
  1221. /* poll is implemented using
  1222. select (see the macosx/fakepoll
  1223. code). When the socket is closed
  1224. select does not return any error,
  1225. POLLIN is true and the next read
  1226. will return 0 bytes. This
  1227. behaviour is diffrent from the
  1228. Linux poll behaviour. Thus we use
  1229. this condition as a socket error
  1230. and remove the client.
  1231. */
  1232. jack_client_disconnect(engine, pfd[i].fd);
  1233. #endif /* JACK_USE_MACH_THREADS */
  1234. }
  1235. }
  1236. }
  1237. /* check the master server socket */
  1238. if (pfd[0].revents & POLLERR) {
  1239. jack_error ("error on server socket");
  1240. break;
  1241. }
  1242. if (engine->control->engine_ok && pfd[0].revents & POLLIN) {
  1243. DEBUG ("pfd[0].revents & POLLIN");
  1244. memset (&client_addr, 0, sizeof (client_addr));
  1245. client_addrlen = sizeof (client_addr);
  1246. if ((client_socket =
  1247. accept (engine->fds[0],
  1248. (struct sockaddr *) &client_addr,
  1249. &client_addrlen)) < 0) {
  1250. jack_error ("cannot accept new connection (%s)",
  1251. strerror (errno));
  1252. } else if (jack_client_create (engine, client_socket) < 0) {
  1253. jack_error ("cannot complete client "
  1254. "connection process");
  1255. close (client_socket);
  1256. }
  1257. }
  1258. /* Possibly, jack_client_create() may have
  1259. * realloced engine->pfd. We depend on that being
  1260. * done within this thread. That is currently true,
  1261. * since external clients are only created here.
  1262. */
  1263. pfd = engine->pfd;
  1264. max = engine->pfd_max;
  1265. /* check the ACK server socket */
  1266. if (pfd[1].revents & POLLERR) {
  1267. jack_error ("error on server ACK socket");
  1268. break;
  1269. }
  1270. if (engine->control->engine_ok && pfd[1].revents & POLLIN) {
  1271. DEBUG ("pfd[1].revents & POLLIN");
  1272. memset (&client_addr, 0, sizeof (client_addr));
  1273. client_addrlen = sizeof (client_addr);
  1274. if ((client_socket =
  1275. accept (engine->fds[1],
  1276. (struct sockaddr *) &client_addr,
  1277. &client_addrlen)) < 0) {
  1278. jack_error ("cannot accept new ACK connection"
  1279. " (%s)", strerror (errno));
  1280. } else if (handle_client_ack_connection
  1281. (engine, client_socket)) {
  1282. jack_error ("cannot complete client ACK "
  1283. "connection process");
  1284. close (client_socket);
  1285. }
  1286. }
  1287. }
  1288. return 0;
  1289. }
  1290. jack_engine_t *
  1291. jack_engine_new (int realtime, int rtpriority, int do_mlock, int do_unlock,
  1292. const char *server_name, int temporary, int verbose,
  1293. int client_timeout, unsigned int port_max, pid_t wait_pid,
  1294. jack_nframes_t frame_time_offset, JSList *drivers)
  1295. {
  1296. jack_engine_t *engine;
  1297. unsigned int i;
  1298. char server_dir[PATH_MAX+1] = "";
  1299. #ifdef USE_CAPABILITIES
  1300. uid_t uid = getuid ();
  1301. uid_t euid = geteuid ();
  1302. #endif /* USE_CAPABILITIES */
  1303. /* before we start allocating resources, make sure that if realtime was requested that we can
  1304. actually do it.
  1305. */
  1306. if (realtime) {
  1307. if (jack_acquire_real_time_scheduling (pthread_self(), 10) != 0) {
  1308. /* can't run realtime - time to bomb */
  1309. return NULL;
  1310. }
  1311. jack_drop_real_time_scheduling (pthread_self());
  1312. #ifdef USE_MLOCK
  1313. if (do_mlock && (mlockall (MCL_CURRENT | MCL_FUTURE) != 0)) {
  1314. jack_error ("cannot lock down memory for jackd (%s)",
  1315. strerror (errno));
  1316. #ifdef ENSURE_MLOCK
  1317. return NULL;
  1318. #endif /* ENSURE_MLOCK */
  1319. }
  1320. #endif /* USE_MLOCK */
  1321. }
  1322. /* start a thread to display messages from realtime threads */
  1323. jack_messagebuffer_init();
  1324. jack_init_time ();
  1325. engine = (jack_engine_t *) malloc (sizeof (jack_engine_t));
  1326. engine->drivers = drivers;
  1327. engine->driver = NULL;
  1328. engine->driver_desc = NULL;
  1329. engine->driver_params = NULL;
  1330. engine->set_sample_rate = jack_set_sample_rate;
  1331. engine->set_buffer_size = jack_driver_buffer_size;
  1332. engine->run_cycle = jack_run_cycle;
  1333. engine->delay = jack_engine_delay;
  1334. engine->driver_exit = jack_engine_driver_exit;
  1335. engine->transport_cycle_start = jack_transport_cycle_start;
  1336. engine->client_timeout_msecs = client_timeout;
  1337. engine->next_client_id = 1; /* 0 is a NULL client ID */
  1338. engine->port_max = port_max;
  1339. engine->rtpriority = rtpriority;
  1340. engine->silent_buffer = 0;
  1341. engine->verbose = verbose;
  1342. engine->server_name = server_name;
  1343. engine->temporary = temporary;
  1344. engine->freewheeling = 0;
  1345. engine->feedbackcount = 0;
  1346. engine->wait_pid = wait_pid;
  1347. jack_engine_reset_rolling_usecs (engine);
  1348. engine->max_usecs = 0.0f;
  1349. pthread_mutex_init (&engine->client_lock, 0);
  1350. pthread_mutex_init (&engine->port_lock, 0);
  1351. pthread_mutex_init (&engine->request_lock, 0);
  1352. engine->clients = 0;
  1353. engine->pfd_size = 16;
  1354. engine->pfd_max = 0;
  1355. engine->pfd = (struct pollfd *) malloc (sizeof (struct pollfd)
  1356. * engine->pfd_size);
  1357. engine->fifo_size = 16;
  1358. engine->fifo = (int *) malloc (sizeof (int) * engine->fifo_size);
  1359. for (i = 0; i < engine->fifo_size; i++) {
  1360. engine->fifo[i] = -1;
  1361. }
  1362. engine->external_client_cnt = 0;
  1363. srandom (time ((time_t *) 0));
  1364. if (jack_shmalloc (sizeof (jack_control_t)
  1365. + ((sizeof (jack_port_shared_t) * engine->port_max)),
  1366. &engine->control_shm)) {
  1367. jack_error ("cannot create engine control shared memory "
  1368. "segment (%s)", strerror (errno));
  1369. return NULL;
  1370. }
  1371. if (jack_attach_shm (&engine->control_shm)) {
  1372. jack_error ("cannot attach to engine control shared memory"
  1373. " (%s)", strerror (errno));
  1374. jack_destroy_shm (&engine->control_shm);
  1375. return NULL;
  1376. }
  1377. engine->control = (jack_control_t *)
  1378. jack_shm_addr (&engine->control_shm);
  1379. /* Setup port type information from builtins. buffer space is
  1380. * allocated when the driver calls jack_driver_buffer_size().
  1381. */
  1382. for (i = 0; jack_builtin_port_types[i].type_name[0]; ++i) {
  1383. memcpy (&engine->control->port_types[i],
  1384. &jack_builtin_port_types[i],
  1385. sizeof (jack_port_type_info_t));
  1386. VERBOSE (engine, "registered builtin port type %s\n",
  1387. engine->control->port_types[i].type_name);
  1388. /* the port type id is index into port_types array */
  1389. engine->control->port_types[i].ptype_id = i;
  1390. /* be sure to initialize mutex correctly */
  1391. pthread_mutex_init (&engine->port_buffers[i].lock, NULL);
  1392. /* set buffer list info correctly */
  1393. engine->port_buffers[i].freelist = NULL;
  1394. engine->port_buffers[i].info = NULL;
  1395. /* mark each port segment as not allocated */
  1396. engine->port_segment[i].index = -1;
  1397. engine->port_segment[i].attached_at = 0;
  1398. }
  1399. engine->control->n_port_types = i;
  1400. /* Mark all ports as available */
  1401. for (i = 0; i < engine->port_max; i++) {
  1402. engine->control->ports[i].in_use = 0;
  1403. engine->control->ports[i].id = i;
  1404. engine->control->ports[i].alias1[0] = '\0';
  1405. engine->control->ports[i].alias2[0] = '\0';
  1406. }
  1407. /* allocate internal port structures so that we can keep track
  1408. * of port connections.
  1409. */
  1410. engine->internal_ports = (jack_port_internal_t *)
  1411. malloc (sizeof (jack_port_internal_t) * engine->port_max);
  1412. for (i = 0; i < engine->port_max; i++) {
  1413. engine->internal_ports[i].connections = 0;
  1414. }
  1415. if (make_sockets (engine->server_name, engine->fds) < 0) {
  1416. jack_error ("cannot create server sockets");
  1417. return NULL;
  1418. }
  1419. engine->control->port_max = engine->port_max;
  1420. engine->control->real_time = realtime;
  1421. engine->control->client_priority = (realtime
  1422. ? engine->rtpriority - 1
  1423. : 0);
  1424. engine->control->do_mlock = do_mlock;
  1425. engine->control->do_munlock = do_unlock;
  1426. engine->control->cpu_load = 0;
  1427. engine->control->xrun_delayed_usecs = 0;
  1428. engine->control->max_delayed_usecs = 0;
  1429. jack_set_clock_source (clock_source);
  1430. engine->control->clock_source = clock_source;
  1431. VERBOSE (engine, "clock source = %s\n", jack_clock_source_name (clock_source));
  1432. engine->control->frame_timer.frames = frame_time_offset;
  1433. engine->control->frame_timer.reset_pending = 0;
  1434. engine->control->frame_timer.current_wakeup = 0;
  1435. engine->control->frame_timer.next_wakeup = 0;
  1436. engine->control->frame_timer.initialized = 0;
  1437. engine->control->frame_timer.filter_coefficient = 0.01;
  1438. engine->control->frame_timer.second_order_integrator = 0;
  1439. engine->first_wakeup = 1;
  1440. engine->control->buffer_size = 0;
  1441. jack_transport_init (engine);
  1442. jack_set_sample_rate (engine, 0);
  1443. engine->control->internal = 0;
  1444. engine->control->has_capabilities = 0;
  1445. #ifdef JACK_USE_MACH_THREADS
  1446. /* specific resources for server/client real-time thread
  1447. * communication */
  1448. engine->servertask = mach_task_self();
  1449. if (task_get_bootstrap_port(engine->servertask, &engine->bp)){
  1450. jack_error("Jackd: Can't find bootstrap mach port");
  1451. return NULL;
  1452. }
  1453. engine->portnum = 0;
  1454. #endif /* JACK_USE_MACH_THREADS */
  1455. #ifdef USE_CAPABILITIES
  1456. if (uid == 0 || euid == 0) {
  1457. VERBOSE (engine, "running with uid=%d and euid=%d, "
  1458. "will not try to use capabilites\n",
  1459. uid, euid);
  1460. } else {
  1461. /* only try to use capabilities if not running as root */
  1462. engine->control->has_capabilities = check_capabilities (engine);
  1463. if (engine->control->has_capabilities == 0) {
  1464. VERBOSE (engine, "required capabilities not "
  1465. "available\n");
  1466. }
  1467. if (engine->verbose) {
  1468. size_t size;
  1469. cap_t cap = cap_init();
  1470. capgetp(0, cap);
  1471. VERBOSE (engine, "capabilities: %s\n",
  1472. cap_to_text(cap, &size));
  1473. }
  1474. }
  1475. #endif /* USE_CAPABILITIES */
  1476. engine->control->engine_ok = 1;
  1477. snprintf (engine->fifo_prefix, sizeof (engine->fifo_prefix),
  1478. "%s/jack-ack-fifo-%d",
  1479. jack_server_dir (engine->server_name, server_dir), getpid ());
  1480. (void) jack_get_fifo_fd (engine, 0);
  1481. jack_client_create_thread (NULL, &engine->server_thread, 0, FALSE,
  1482. &jack_server_thread, engine);
  1483. return engine;
  1484. }
  1485. static void
  1486. jack_engine_delay (jack_engine_t *engine, float delayed_usecs)
  1487. {
  1488. JSList *node;
  1489. jack_event_t event;
  1490. engine->control->frame_timer.reset_pending = 1;
  1491. engine->control->xrun_delayed_usecs = delayed_usecs;
  1492. if (delayed_usecs > engine->control->max_delayed_usecs)
  1493. engine->control->max_delayed_usecs = delayed_usecs;
  1494. event.type = XRun;
  1495. jack_lock_graph (engine);
  1496. for (node = engine->clients; node; node = jack_slist_next (node)) {
  1497. jack_deliver_event (engine,
  1498. (jack_client_internal_t *) node->data,
  1499. &event);
  1500. }
  1501. jack_unlock_graph (engine);
  1502. }
  1503. static inline void
  1504. jack_inc_frame_time (jack_engine_t *engine, jack_nframes_t nframes)
  1505. {
  1506. jack_frame_timer_t *timer = &engine->control->frame_timer;
  1507. jack_time_t now = engine->driver->last_wait_ust; // effective time
  1508. float delta;
  1509. // really need a memory barrier here
  1510. timer->guard1++;
  1511. delta = (int64_t) now - (int64_t) timer->next_wakeup;
  1512. timer->current_wakeup = timer->next_wakeup;
  1513. timer->frames += nframes;
  1514. timer->second_order_integrator += 0.5f *
  1515. timer->filter_coefficient * delta;
  1516. timer->next_wakeup = timer->current_wakeup +
  1517. engine->driver->period_usecs +
  1518. (int64_t) floorf ((timer->filter_coefficient *
  1519. (delta + timer->second_order_integrator)));
  1520. timer->initialized = 1;
  1521. // might need a memory barrier here
  1522. timer->guard2++;
  1523. }
  1524. static void*
  1525. jack_engine_freewheel (void *arg)
  1526. {
  1527. jack_engine_t* engine = (jack_engine_t *) arg;
  1528. VERBOSE (engine, "freewheel thread starting ...\n");
  1529. /* we should not be running SCHED_FIFO, so we don't
  1530. have to do anything about scheduling.
  1531. */
  1532. while (engine->freewheeling) {
  1533. jack_lock_graph (engine);
  1534. if (jack_engine_process (engine,
  1535. engine->control->buffer_size)) {
  1536. jack_error ("process cycle within freewheel failed");
  1537. jack_unlock_graph (engine);
  1538. break;
  1539. }
  1540. jack_unlock_graph (engine);
  1541. }
  1542. VERBOSE (engine, "freewheel came to an end, naturally\n");
  1543. return 0;
  1544. }
  1545. static int
  1546. jack_start_freewheeling (jack_engine_t* engine)
  1547. {
  1548. jack_event_t event;
  1549. if (engine->freewheeling) {
  1550. return 0;
  1551. }
  1552. if (engine->driver == NULL) {
  1553. jack_error ("cannot start freewheeling without a driver!");
  1554. return -1;
  1555. }
  1556. /* stop driver before telling anyone about it so
  1557. there are no more process() calls being handled.
  1558. */
  1559. if (engine->driver->stop (engine->driver)) {
  1560. jack_error ("could not stop driver for freewheeling");
  1561. return -1;
  1562. }
  1563. engine->freewheeling = 1;
  1564. event.type = StartFreewheel;
  1565. jack_deliver_event_to_all (engine, &event);
  1566. if (jack_client_create_thread (NULL, &engine->freewheel_thread, 0, FALSE,
  1567. jack_engine_freewheel, engine)) {
  1568. jack_error ("could not start create freewheel thread");
  1569. return -1;
  1570. }
  1571. return 0;
  1572. }
  1573. static int
  1574. jack_stop_freewheeling (jack_engine_t* engine)
  1575. {
  1576. jack_event_t event;
  1577. void *ftstatus;
  1578. if (!engine->freewheeling) {
  1579. return 0;
  1580. }
  1581. if (engine->driver == NULL) {
  1582. jack_error ("cannot start freewheeling without a driver!");
  1583. return -1;
  1584. }
  1585. if (!engine->freewheeling) {
  1586. VERBOSE (engine, "stop freewheel when not freewheeling\n");
  1587. return 0;
  1588. }
  1589. /* tell the freewheel thread to stop, and wait for it
  1590. to exit.
  1591. */
  1592. engine->freewheeling = 0;
  1593. VERBOSE (engine, "freewheeling stopped, waiting for thread\n");
  1594. pthread_join (engine->freewheel_thread, &ftstatus);
  1595. VERBOSE (engine, "freewheel thread has returned\n");
  1596. /* tell everyone we've stopped */
  1597. event.type = StopFreewheel;
  1598. jack_deliver_event_to_all (engine, &event);
  1599. /* restart the driver */
  1600. if (engine->driver->start (engine->driver)) {
  1601. jack_error ("could not restart driver after freewheeling");
  1602. return -1;
  1603. }
  1604. return 0;
  1605. }
  1606. static int
  1607. jack_run_one_cycle (jack_engine_t *engine, jack_nframes_t nframes,
  1608. float delayed_usecs)
  1609. {
  1610. jack_driver_t* driver = engine->driver;
  1611. int ret = -1;
  1612. static int consecutive_excessive_delays = 0;
  1613. #define WORK_SCALE 1.0f
  1614. if (engine->control->real_time &&
  1615. engine->spare_usecs &&
  1616. ((WORK_SCALE * engine->spare_usecs) <= delayed_usecs)) {
  1617. MESSAGE("delay of %.3f usecs exceeds estimated spare"
  1618. " time of %.3f; restart ...\n",
  1619. delayed_usecs, WORK_SCALE * engine->spare_usecs);
  1620. if (++consecutive_excessive_delays > 10) {
  1621. jack_error ("too many consecutive interrupt delays "
  1622. "... engine pausing");
  1623. return -1; /* will exit the thread loop */
  1624. }
  1625. jack_engine_delay (engine, delayed_usecs);
  1626. return 0;
  1627. } else {
  1628. consecutive_excessive_delays = 0;
  1629. }
  1630. if (jack_try_lock_graph (engine)) {
  1631. /* engine can't run. just throw away an entire cycle */
  1632. driver->null_cycle (driver, nframes);
  1633. return 0;
  1634. }
  1635. if (!engine->freewheeling) {
  1636. DEBUG("waiting for driver read\n");
  1637. if (driver->read (driver, nframes)) {
  1638. goto unlock;
  1639. }
  1640. }
  1641. DEBUG("run process\n");
  1642. if (jack_engine_process (engine, nframes) == 0) {
  1643. if (!engine->freewheeling) {
  1644. if (driver->write (driver, nframes)) {
  1645. goto unlock;
  1646. }
  1647. }
  1648. } else {
  1649. JSList *node;
  1650. DEBUG ("engine process cycle failed");
  1651. /* we are already late, or something else went wrong,
  1652. so it can't hurt to check the existence of all
  1653. clients.
  1654. */
  1655. for (node = engine->clients; node;
  1656. node = jack_slist_next (node)) {
  1657. jack_client_internal_t *client =
  1658. (jack_client_internal_t *) node->data;
  1659. if (client->control->type == ClientExternal) {
  1660. if (kill (client->control->pid, 0)) {
  1661. VERBOSE(engine,
  1662. "client %s has died/exited\n",
  1663. client->control->name);
  1664. client->error++;
  1665. }
  1666. }
  1667. DEBUG ("client %s errors = %d", client->control->name,
  1668. client->error);
  1669. }
  1670. }
  1671. jack_engine_post_process (engine);
  1672. if (delayed_usecs > engine->control->max_delayed_usecs)
  1673. engine->control->max_delayed_usecs = delayed_usecs;
  1674. ret = 0;
  1675. unlock:
  1676. jack_unlock_graph (engine);
  1677. DEBUG("cycle finished, status = %d", ret);
  1678. return ret;
  1679. }
  1680. static void
  1681. jack_engine_driver_exit (jack_engine_t* engine)
  1682. {
  1683. /* tell anyone waiting that the driver exited. */
  1684. kill (engine->wait_pid, SIGUSR2);
  1685. engine->driver = NULL;
  1686. }
  1687. static int
  1688. jack_run_cycle (jack_engine_t *engine, jack_nframes_t nframes,
  1689. float delayed_usecs)
  1690. {
  1691. jack_nframes_t left;
  1692. jack_nframes_t b_size = engine->control->buffer_size;
  1693. jack_frame_timer_t* timer = &engine->control->frame_timer;
  1694. int no_increment = 0;
  1695. if (engine->first_wakeup) {
  1696. /* the first wakeup */
  1697. timer->next_wakeup =
  1698. engine->driver->last_wait_ust +
  1699. engine->driver->period_usecs;
  1700. engine->first_wakeup = 0;
  1701. /* if we got an xrun/delayed wakeup on the first cycle,
  1702. reset the pending flag (we have no predicted wakeups
  1703. to use), but avoid incrementing the frame timer.
  1704. */
  1705. if (timer->reset_pending) {
  1706. timer->reset_pending = 0;
  1707. no_increment = 1;
  1708. }
  1709. }
  1710. if (timer->reset_pending) {
  1711. /* post xrun-handling */
  1712. /* don't bother to increment the frame counter, because we missed 1 or more
  1713. deadlines in the backend anyway.
  1714. */
  1715. timer->current_wakeup = engine->driver->last_wait_ust;
  1716. timer->next_wakeup = engine->driver->last_wait_ust +
  1717. engine->driver->period_usecs;
  1718. timer->reset_pending = 0;
  1719. } else {
  1720. /* normal condition */
  1721. if (!no_increment) {
  1722. jack_inc_frame_time (engine, nframes);
  1723. }
  1724. }
  1725. if (engine->verbose) {
  1726. if (nframes != b_size) {
  1727. VERBOSE (engine,
  1728. "late driver wakeup: nframes to process = %"
  1729. PRIu32 ".\n", nframes);
  1730. }
  1731. }
  1732. /* run as many cycles as it takes to consume nframes */
  1733. for (left = nframes; left >= b_size; left -= b_size) {
  1734. if (jack_run_one_cycle (engine, b_size, delayed_usecs)) {
  1735. jack_error ("cycle execution failure, exiting");
  1736. return EIO;
  1737. }
  1738. }
  1739. return 0;
  1740. }
  1741. void
  1742. jack_engine_delete (jack_engine_t *engine)
  1743. {
  1744. int i;
  1745. if (engine == NULL)
  1746. return;
  1747. VERBOSE (engine, "starting server engine shutdown\n");
  1748. engine->control->engine_ok = 0; /* tell clients we're going away */
  1749. /* shutdown master socket to prevent new clients arriving */
  1750. shutdown (engine->fds[0], SHUT_RDWR);
  1751. // close (engine->fds[0]);
  1752. /* now really tell them we're going away */
  1753. for (i = 0; i < engine->pfd_max; ++i) {
  1754. shutdown (engine->pfd[i].fd, SHUT_RDWR);
  1755. }
  1756. if (engine->driver) {
  1757. jack_driver_t* driver = engine->driver;
  1758. VERBOSE (engine, "stopping driver\n");
  1759. driver->stop (driver);
  1760. // VERBOSE (engine, "detaching driver\n");
  1761. // driver->detach (driver, engine);
  1762. VERBOSE (engine, "unloading driver\n");
  1763. jack_driver_unload (driver);
  1764. engine->driver = NULL;
  1765. }
  1766. VERBOSE (engine, "freeing shared port segments\n");
  1767. for (i = 0; i < engine->control->n_port_types; ++i) {
  1768. jack_release_shm (&engine->port_segment[i]);
  1769. jack_destroy_shm (&engine->port_segment[i]);
  1770. }
  1771. /* stop the other engine threads */
  1772. VERBOSE (engine, "stopping server thread\n");
  1773. #if JACK_USE_MACH_THREADS
  1774. // MacOSX pthread_cancel still not implemented correctly in Darwin
  1775. mach_port_t machThread = pthread_mach_thread_np (engine->server_thread);
  1776. thread_terminate (machThread);
  1777. #else
  1778. pthread_cancel (engine->server_thread);
  1779. pthread_join (engine->server_thread, NULL);
  1780. #endif
  1781. #ifndef JACK_USE_MACH_THREADS
  1782. /* Cancel the watchdog thread and wait for it to terminate.
  1783. *
  1784. * The watchdog thread is not used on MacOSX since CoreAudio
  1785. * drivers already contain a similar mechanism.
  1786. */
  1787. if (engine->control->real_time && engine->watchdog_thread) {
  1788. VERBOSE (engine, "stopping watchdog thread\n");
  1789. pthread_cancel (engine->watchdog_thread);
  1790. pthread_join (engine->watchdog_thread, NULL);
  1791. }
  1792. #endif
  1793. VERBOSE (engine, "last xrun delay: %.3f usecs\n",
  1794. engine->control->xrun_delayed_usecs);
  1795. VERBOSE (engine, "max delay reported by backend: %.3f usecs\n",
  1796. engine->control->max_delayed_usecs);
  1797. /* free engine control shm segment */
  1798. engine->control = NULL;
  1799. VERBOSE (engine, "freeing engine shared memory\n");
  1800. jack_release_shm (&engine->control_shm);
  1801. jack_destroy_shm (&engine->control_shm);
  1802. VERBOSE (engine, "max usecs: %.3f, ", engine->max_usecs);
  1803. VERBOSE (engine, "engine deleted\n");
  1804. free (engine);
  1805. jack_messagebuffer_exit();
  1806. }
  1807. void
  1808. jack_port_clear_connections (jack_engine_t *engine,
  1809. jack_port_internal_t *port)
  1810. {
  1811. JSList *node, *next;
  1812. for (node = port->connections; node; ) {
  1813. next = jack_slist_next (node);
  1814. jack_port_disconnect_internal (
  1815. engine, ((jack_connection_internal_t *)
  1816. node->data)->source,
  1817. ((jack_connection_internal_t *)
  1818. node->data)->destination);
  1819. node = next;
  1820. }
  1821. jack_slist_free (port->connections);
  1822. port->connections = 0;
  1823. }
  1824. static void
  1825. jack_deliver_event_to_all (jack_engine_t *engine, jack_event_t *event)
  1826. {
  1827. JSList *node;
  1828. jack_lock_graph (engine);
  1829. for (node = engine->clients; node; node = jack_slist_next (node)) {
  1830. jack_deliver_event (engine,
  1831. (jack_client_internal_t *) node->data,
  1832. event);
  1833. }
  1834. jack_unlock_graph (engine);
  1835. }
  1836. static int
  1837. jack_deliver_event (jack_engine_t *engine, jack_client_internal_t *client,
  1838. jack_event_t *event)
  1839. {
  1840. char status;
  1841. /* caller must hold the graph lock */
  1842. DEBUG ("delivering event (type %d)", event->type);
  1843. /* we are not RT-constrained here, so use kill(2) to beef up
  1844. our check on a client's continued well-being
  1845. */
  1846. if (client->control->dead
  1847. || (client->control->type == ClientExternal
  1848. && kill (client->control->pid, 0))) {
  1849. DEBUG ("client %s is dead - no event sent",
  1850. client->control->name);
  1851. return 0;
  1852. }
  1853. DEBUG ("client %s is still alive", client->control->name);
  1854. if (jack_client_is_internal (client)) {
  1855. switch (event->type) {
  1856. case PortConnected:
  1857. case PortDisconnected:
  1858. jack_client_handle_port_connection
  1859. (client->control->private_client, event);
  1860. break;
  1861. case BufferSizeChange:
  1862. jack_client_invalidate_port_buffers
  1863. (client->control->private_client);
  1864. if (client->control->bufsize) {
  1865. client->control->bufsize
  1866. (event->x.n,
  1867. client->control->bufsize_arg);
  1868. }
  1869. break;
  1870. case SampleRateChange:
  1871. if (client->control->srate) {
  1872. client->control->srate
  1873. (event->x.n,
  1874. client->control->srate_arg);
  1875. }
  1876. break;
  1877. case GraphReordered:
  1878. if (client->control->graph_order) {
  1879. client->control->graph_order
  1880. (client->control->graph_order_arg);
  1881. }
  1882. break;
  1883. case XRun:
  1884. if (client->control->xrun) {
  1885. client->control->xrun
  1886. (client->control->xrun_arg);
  1887. }
  1888. break;
  1889. default:
  1890. /* internal clients don't need to know */
  1891. break;
  1892. }
  1893. } else {
  1894. if (client->control->active) {
  1895. /* there's a thread waiting for events, so
  1896. * it's worth telling the client */
  1897. DEBUG ("engine writing on event fd");
  1898. if (write (client->event_fd, event, sizeof (*event))
  1899. != sizeof (*event)) {
  1900. jack_error ("cannot send event to client [%s]"
  1901. " (%s)", client->control->name,
  1902. strerror (errno));
  1903. client->error++;
  1904. }
  1905. DEBUG ("engine reading from event fd");
  1906. if (!client->error &&
  1907. (read (client->event_fd, &status, sizeof (status))
  1908. != sizeof (status))) {
  1909. jack_error ("cannot read event response from "
  1910. "client [%s] (%s)",
  1911. client->control->name,
  1912. strerror (errno));
  1913. client->error++;
  1914. }
  1915. if (status != 0) {
  1916. jack_error ("bad status for client event "
  1917. "handling (type = %d)",
  1918. event->type);
  1919. client->error++;
  1920. }
  1921. }
  1922. }
  1923. DEBUG ("event delivered");
  1924. return 0;
  1925. }
  1926. int
  1927. jack_rechain_graph (jack_engine_t *engine)
  1928. {
  1929. JSList *node, *next;
  1930. unsigned long n;
  1931. int err = 0;
  1932. jack_client_internal_t *client, *subgraph_client, *next_client;
  1933. jack_event_t event;
  1934. int upstream_is_jackd;
  1935. jack_clear_fifos (engine);
  1936. subgraph_client = 0;
  1937. VERBOSE(engine, "++ jack_rechain_graph():\n");
  1938. event.type = GraphReordered;
  1939. for (n = 0, node = engine->clients, next = NULL; node; node = next) {
  1940. next = jack_slist_next (node);
  1941. if (((jack_client_internal_t *) node->data)->control->active) {
  1942. client = (jack_client_internal_t *) node->data;
  1943. /* find the next active client. its ok for
  1944. * this to be NULL */
  1945. while (next) {
  1946. if (((jack_client_internal_t *)
  1947. next->data)->control->active) {
  1948. break;
  1949. }
  1950. next = jack_slist_next (next);
  1951. };
  1952. if (next == NULL) {
  1953. next_client = NULL;
  1954. } else {
  1955. next_client = (jack_client_internal_t *)
  1956. next->data;
  1957. }
  1958. client->execution_order = n;
  1959. client->next_client = next_client;
  1960. if (jack_client_is_internal (client)) {
  1961. /* break the chain for the current
  1962. * subgraph. the server will wait for
  1963. * chain on the nth FIFO, and will
  1964. * then execute this internal
  1965. * client. */
  1966. if (subgraph_client) {
  1967. subgraph_client->subgraph_wait_fd =
  1968. jack_get_fifo_fd (engine, n);
  1969. VERBOSE (engine, "client %s: wait_fd="
  1970. "%d, execution_order="
  1971. "%lu.\n",
  1972. subgraph_client->
  1973. control->name,
  1974. subgraph_client->
  1975. subgraph_wait_fd, n);
  1976. n++;
  1977. }
  1978. VERBOSE (engine, "client %s: internal "
  1979. "client, execution_order="
  1980. "%lu.\n",
  1981. client->control->name, n);
  1982. /* this does the right thing for
  1983. * internal clients too
  1984. */
  1985. jack_deliver_event (engine, client, &event);
  1986. subgraph_client = 0;
  1987. } else {
  1988. if (subgraph_client == NULL) {
  1989. /* start a new subgraph. the
  1990. * engine will start the chain
  1991. * by writing to the nth
  1992. * FIFO.
  1993. */
  1994. subgraph_client = client;
  1995. subgraph_client->subgraph_start_fd =
  1996. jack_get_fifo_fd (engine, n);
  1997. VERBOSE (engine, "client %s: "
  1998. "start_fd=%d, execution"
  1999. "_order=%lu.\n",
  2000. subgraph_client->
  2001. control->name,
  2002. subgraph_client->
  2003. subgraph_start_fd, n);
  2004. /* this external client after
  2005. this will have jackd as its
  2006. upstream connection.
  2007. */
  2008. upstream_is_jackd = 1;
  2009. }
  2010. else {
  2011. VERBOSE (engine, "client %s: in"
  2012. " subgraph after %s, "
  2013. "execution_order="
  2014. "%lu.\n",
  2015. client->control->name,
  2016. subgraph_client->
  2017. control->name, n);
  2018. subgraph_client->subgraph_wait_fd = -1;
  2019. /* this external client after
  2020. this will have another
  2021. client as its upstream
  2022. connection.
  2023. */
  2024. upstream_is_jackd = 0;
  2025. }
  2026. /* make sure fifo for 'n + 1' exists
  2027. * before issuing client reorder
  2028. */
  2029. (void) jack_get_fifo_fd(
  2030. engine, client->execution_order + 1);
  2031. event.x.n = client->execution_order;
  2032. event.y.n = upstream_is_jackd;
  2033. jack_deliver_event (engine, client, &event);
  2034. n++;
  2035. }
  2036. }
  2037. }
  2038. if (subgraph_client) {
  2039. subgraph_client->subgraph_wait_fd =
  2040. jack_get_fifo_fd (engine, n);
  2041. VERBOSE (engine, "client %s: wait_fd=%d, "
  2042. "execution_order=%lu (last client).\n",
  2043. subgraph_client->control->name,
  2044. subgraph_client->subgraph_wait_fd, n);
  2045. }
  2046. VERBOSE (engine, "-- jack_rechain_graph()\n");
  2047. return err;
  2048. }
  2049. static jack_nframes_t
  2050. jack_get_port_total_latency (jack_engine_t *engine,
  2051. jack_port_internal_t *port, int hop_count,
  2052. int toward_port)
  2053. {
  2054. JSList *node;
  2055. jack_nframes_t latency;
  2056. jack_nframes_t max_latency = 0;
  2057. #ifdef DEBUG_TOTAL_LATENCY_COMPUTATION
  2058. char prefix[32];
  2059. int i;
  2060. for (i = 0; i < hop_count; ++i) {
  2061. prefix[i] = '\t';
  2062. }
  2063. prefix[i] = '\0';
  2064. #endif
  2065. /* call tree must hold engine->client_lock. */
  2066. latency = port->shared->latency;
  2067. /* we don't prevent cyclic graphs, so we have to do something
  2068. to bottom out in the event that they are created.
  2069. */
  2070. if (hop_count > 8) {
  2071. return latency;
  2072. }
  2073. #ifdef DEBUG_TOTAL_LATENCY_COMPUTATION
  2074. fprintf (stderr, "\n%sFor port %s (%s)\n", prefix, port->shared->name, (toward_port ? "toward" : "away"));
  2075. #endif
  2076. for (node = port->connections; node; node = jack_slist_next (node)) {
  2077. jack_nframes_t this_latency;
  2078. jack_connection_internal_t *connection;
  2079. connection = (jack_connection_internal_t *) node->data;
  2080. if ((toward_port &&
  2081. (connection->source->shared == port->shared)) ||
  2082. (!toward_port &&
  2083. (connection->destination->shared == port->shared))) {
  2084. #ifdef DEBUG_TOTAL_LATENCY_COMPUTATION
  2085. fprintf (stderr, "%s\tskip connection %s->%s\n",
  2086. prefix,
  2087. connection->source->shared->name,
  2088. connection->destination->shared->name);
  2089. #endif
  2090. continue;
  2091. }
  2092. #ifdef DEBUG_TOTAL_LATENCY_COMPUTATION
  2093. fprintf (stderr, "%s\tconnection %s->%s ... ",
  2094. prefix,
  2095. connection->source->shared->name,
  2096. connection->destination->shared->name);
  2097. #endif
  2098. /* if we're a destination in the connection, recurse
  2099. on the source to get its total latency
  2100. */
  2101. if (connection->destination == port) {
  2102. if (connection->source->shared->flags
  2103. & JackPortIsTerminal) {
  2104. this_latency = connection->source->
  2105. shared->latency;
  2106. } else {
  2107. this_latency =
  2108. jack_get_port_total_latency (
  2109. engine, connection->source,
  2110. hop_count + 1,
  2111. toward_port);
  2112. }
  2113. } else {
  2114. /* "port" is the source, so get the latency of
  2115. * the destination */
  2116. if (connection->destination->shared->flags
  2117. & JackPortIsTerminal) {
  2118. this_latency = connection->destination->
  2119. shared->latency;
  2120. } else {
  2121. this_latency =
  2122. jack_get_port_total_latency (
  2123. engine,
  2124. connection->destination,
  2125. hop_count + 1,
  2126. toward_port);
  2127. }
  2128. }
  2129. if (this_latency > max_latency) {
  2130. max_latency = this_latency;
  2131. }
  2132. }
  2133. #ifdef DEBUG_TOTAL_LATENCY_COMPUTATION
  2134. fprintf (stderr, "%s\treturn %lu + %lu = %lu\n", prefix, latency, max_latency, latency + max_latency);
  2135. #endif
  2136. return latency + max_latency;
  2137. }
  2138. static void
  2139. jack_compute_all_port_total_latencies (jack_engine_t *engine)
  2140. {
  2141. jack_port_shared_t *shared = engine->control->ports;
  2142. unsigned int i;
  2143. int toward_port;
  2144. for (i = 0; i < engine->control->port_max; i++) {
  2145. if (shared[i].in_use) {
  2146. if (shared[i].flags & JackPortIsOutput) {
  2147. toward_port = FALSE;
  2148. } else {
  2149. toward_port = TRUE;
  2150. }
  2151. shared[i].total_latency =
  2152. jack_get_port_total_latency (
  2153. engine, &engine->internal_ports[i],
  2154. 0, toward_port);
  2155. }
  2156. }
  2157. }
  2158. /* How the sort works:
  2159. *
  2160. * Each client has a "sortfeeds" list of clients indicating which clients
  2161. * it should be considered as feeding for the purposes of sorting the
  2162. * graph. This list differs from the clients it /actually/ feeds in the
  2163. * following ways:
  2164. *
  2165. * 1. Connections from a client to itself are disregarded
  2166. *
  2167. * 2. Connections to a driver client are disregarded
  2168. *
  2169. * 3. If a connection from A to B is a feedback connection (ie there was
  2170. * already a path from B to A when the connection was made) then instead
  2171. * of B appearing on A's sortfeeds list, A will appear on B's sortfeeds
  2172. * list.
  2173. *
  2174. * If client A is on client B's sortfeeds list, client A must come after
  2175. * client B in the execution order. The above 3 rules ensure that the
  2176. * sortfeeds relation is always acyclic so that all ordering constraints
  2177. * can actually be met.
  2178. *
  2179. * Each client also has a "truefeeds" list which is the same as sortfeeds
  2180. * except that feedback connections appear normally instead of reversed.
  2181. * This is used to detect whether the graph has become acyclic.
  2182. *
  2183. */
  2184. void
  2185. jack_sort_graph (jack_engine_t *engine)
  2186. {
  2187. /* called, obviously, must hold engine->client_lock */
  2188. engine->clients = jack_slist_sort (engine->clients,
  2189. (JCompareFunc) jack_client_sort);
  2190. jack_compute_all_port_total_latencies (engine);
  2191. jack_rechain_graph (engine);
  2192. }
  2193. static int
  2194. jack_client_sort (jack_client_internal_t *a, jack_client_internal_t *b)
  2195. {
  2196. /* drivers are forced to the front, ie considered as sources
  2197. rather than sinks for purposes of the sort */
  2198. if (jack_client_feeds_transitive (a, b) ||
  2199. (a->control->type == ClientDriver &&
  2200. b->control->type != ClientDriver)) {
  2201. return -1;
  2202. } else if (jack_client_feeds_transitive (b, a) ||
  2203. (b->control->type == ClientDriver &&
  2204. a->control->type != ClientDriver)) {
  2205. return 1;
  2206. } else {
  2207. return 0;
  2208. }
  2209. }
  2210. /* transitive closure of the relation expressed by the sortfeeds lists. */
  2211. static int
  2212. jack_client_feeds_transitive (jack_client_internal_t *source,
  2213. jack_client_internal_t *dest )
  2214. {
  2215. jack_client_internal_t *med;
  2216. JSList *node;
  2217. if (jack_slist_find (source->sortfeeds, dest)) {
  2218. return 1;
  2219. }
  2220. for (node = source->sortfeeds; node; node = jack_slist_next (node)) {
  2221. med = (jack_client_internal_t *) node->data;
  2222. if (jack_client_feeds_transitive (med, dest)) {
  2223. return 1;
  2224. }
  2225. }
  2226. return 0;
  2227. }
  2228. /**
  2229. * Checks whether the graph has become acyclic and if so modifies client
  2230. * sortfeeds lists to turn leftover feedback connections into normal ones.
  2231. * This lowers latency, but at the expense of some data corruption.
  2232. */
  2233. static void
  2234. jack_check_acyclic (jack_engine_t *engine)
  2235. {
  2236. JSList *srcnode, *dstnode, *portnode, *connnode;
  2237. jack_client_internal_t *src, *dst;
  2238. jack_port_internal_t *port;
  2239. jack_connection_internal_t *conn;
  2240. int stuck;
  2241. int unsortedclients = 0;
  2242. VERBOSE (engine, "checking for graph become acyclic\n");
  2243. for (srcnode = engine->clients; srcnode;
  2244. srcnode = jack_slist_next (srcnode)) {
  2245. src = (jack_client_internal_t *) srcnode->data;
  2246. src->tfedcount = src->fedcount;
  2247. unsortedclients++;
  2248. }
  2249. stuck = FALSE;
  2250. /* find out whether a normal sort would have been possible */
  2251. while (unsortedclients && !stuck) {
  2252. stuck = TRUE;
  2253. for (srcnode = engine->clients; srcnode;
  2254. srcnode = jack_slist_next (srcnode)) {
  2255. src = (jack_client_internal_t *) srcnode->data;
  2256. if (!src->tfedcount) {
  2257. stuck = FALSE;
  2258. unsortedclients--;
  2259. src->tfedcount = -1;
  2260. for (dstnode = src->truefeeds; dstnode;
  2261. dstnode = jack_slist_next (dstnode)) {
  2262. dst = (jack_client_internal_t *)
  2263. dstnode->data;
  2264. dst->tfedcount--;
  2265. }
  2266. }
  2267. }
  2268. }
  2269. if (stuck) {
  2270. VERBOSE (engine, "graph is still cyclic\n" );
  2271. } else {
  2272. VERBOSE (engine, "graph has become acyclic\n");
  2273. /* turn feedback connections around in sortfeeds */
  2274. for (srcnode = engine->clients; srcnode;
  2275. srcnode = jack_slist_next (srcnode)) {
  2276. src = (jack_client_internal_t *) srcnode->data;
  2277. for (portnode = src->ports; portnode;
  2278. portnode = jack_slist_next (portnode)) {
  2279. port = (jack_port_internal_t *) portnode->data;
  2280. for (connnode = port->connections; connnode;
  2281. connnode = jack_slist_next (connnode)) {
  2282. conn = (jack_connection_internal_t*)
  2283. connnode->data;
  2284. if (conn->dir == -1 )
  2285. /*&&
  2286. conn->srcclient == src) */{
  2287. VERBOSE (engine,
  2288. "reversing connection from "
  2289. "%s to %s\n",
  2290. conn->srcclient->control->name,
  2291. conn->dstclient->control->name);
  2292. conn->dir = 1;
  2293. conn->dstclient->sortfeeds =
  2294. jack_slist_remove
  2295. (conn->dstclient->sortfeeds,
  2296. conn->srcclient);
  2297. conn->srcclient->sortfeeds =
  2298. jack_slist_prepend
  2299. (conn->srcclient->sortfeeds,
  2300. conn->dstclient );
  2301. }
  2302. }
  2303. }
  2304. }
  2305. engine->feedbackcount = 0;
  2306. }
  2307. }
  2308. /**
  2309. * Dumps current engine configuration to stderr.
  2310. */
  2311. void jack_dump_configuration(jack_engine_t *engine, int take_lock)
  2312. {
  2313. JSList *clientnode, *portnode, *connectionnode;
  2314. jack_client_internal_t *client;
  2315. jack_client_control_t *ctl;
  2316. jack_port_internal_t *port;
  2317. jack_connection_internal_t* connection;
  2318. int n, m, o;
  2319. fprintf(stderr, "engine.c: <-- dump begins -->\n");
  2320. if (take_lock) {
  2321. jack_lock_graph (engine);
  2322. }
  2323. for (n = 0, clientnode = engine->clients; clientnode;
  2324. clientnode = jack_slist_next (clientnode)) {
  2325. client = (jack_client_internal_t *) clientnode->data;
  2326. ctl = client->control;
  2327. fprintf (stderr, "client #%d: %s (type: %d, process? %s,"
  2328. " start=%d wait=%d\n",
  2329. ++n,
  2330. ctl->name,
  2331. ctl->type,
  2332. ctl->process ? "yes" : "no",
  2333. client->subgraph_start_fd,
  2334. client->subgraph_wait_fd);
  2335. for(m = 0, portnode = client->ports; portnode;
  2336. portnode = jack_slist_next (portnode)) {
  2337. port = (jack_port_internal_t *) portnode->data;
  2338. fprintf(stderr, "\t port #%d: %s\n", ++m,
  2339. port->shared->name);
  2340. for(o = 0, connectionnode = port->connections;
  2341. connectionnode;
  2342. connectionnode =
  2343. jack_slist_next (connectionnode)) {
  2344. connection = (jack_connection_internal_t *)
  2345. connectionnode->data;
  2346. fprintf(stderr, "\t\t connection #%d: %s %s\n",
  2347. ++o,
  2348. (port->shared->flags
  2349. & JackPortIsInput)? "<-": "->",
  2350. (port->shared->flags & JackPortIsInput)?
  2351. connection->source->shared->name:
  2352. connection->destination->shared->name);
  2353. }
  2354. }
  2355. }
  2356. if (take_lock) {
  2357. jack_unlock_graph (engine);
  2358. }
  2359. fprintf(stderr, "engine.c: <-- dump ends -->\n");
  2360. }
  2361. static int
  2362. jack_port_do_connect (jack_engine_t *engine,
  2363. const char *source_port,
  2364. const char *destination_port)
  2365. {
  2366. jack_connection_internal_t *connection;
  2367. jack_port_internal_t *srcport, *dstport;
  2368. jack_port_id_t src_id, dst_id;
  2369. jack_client_internal_t *srcclient, *dstclient;
  2370. JSList *it;
  2371. if ((srcport = jack_get_port_by_name (engine, source_port)) == NULL) {
  2372. jack_error ("unknown source port in attempted connection [%s]",
  2373. source_port);
  2374. return -1;
  2375. }
  2376. if ((dstport = jack_get_port_by_name (engine, destination_port))
  2377. == NULL) {
  2378. jack_error ("unknown destination port in attempted connection"
  2379. " [%s]", destination_port);
  2380. return -1;
  2381. }
  2382. if ((dstport->shared->flags & JackPortIsInput) == 0) {
  2383. jack_error ("destination port in attempted connection of"
  2384. " %s and %s is not an input port",
  2385. source_port, destination_port);
  2386. return -1;
  2387. }
  2388. if ((srcport->shared->flags & JackPortIsOutput) == 0) {
  2389. jack_error ("source port in attempted connection of %s and"
  2390. " %s is not an output port",
  2391. source_port, destination_port);
  2392. return -1;
  2393. }
  2394. if (srcport->shared->ptype_id != dstport->shared->ptype_id) {
  2395. jack_error ("ports used in attemped connection are not of "
  2396. "the same data type");
  2397. return -1;
  2398. }
  2399. if ((srcclient = jack_client_internal_by_id (engine,
  2400. srcport->shared->client_id))
  2401. == 0) {
  2402. jack_error ("unknown client set as owner of port - "
  2403. "cannot connect");
  2404. return -1;
  2405. }
  2406. if (!srcclient->control->active) {
  2407. jack_error ("cannot connect ports owned by inactive clients;"
  2408. " \"%s\" is not active", srcclient->control->name);
  2409. return -1;
  2410. }
  2411. if ((dstclient = jack_client_internal_by_id (engine,
  2412. dstport->shared->client_id))
  2413. == 0) {
  2414. jack_error ("unknown client set as owner of port - cannot "
  2415. "connect");
  2416. return -1;
  2417. }
  2418. if (!dstclient->control->active) {
  2419. jack_error ("cannot connect ports owned by inactive clients;"
  2420. " \"%s\" is not active", dstclient->control->name);
  2421. return -1;
  2422. }
  2423. for (it = srcport->connections; it; it = it->next) {
  2424. if (((jack_connection_internal_t *)it->data)->destination
  2425. == dstport) {
  2426. return EEXIST;
  2427. }
  2428. }
  2429. connection = (jack_connection_internal_t *)
  2430. malloc (sizeof (jack_connection_internal_t));
  2431. connection->source = srcport;
  2432. connection->destination = dstport;
  2433. connection->srcclient = srcclient;
  2434. connection->dstclient = dstclient;
  2435. src_id = srcport->shared->id;
  2436. dst_id = dstport->shared->id;
  2437. jack_lock_graph (engine);
  2438. if (dstport->connections && !dstport->shared->has_mixdown) {
  2439. jack_port_type_info_t *port_type =
  2440. jack_port_type_info (engine, dstport);
  2441. jack_error ("cannot make multiple connections to a port of"
  2442. " type [%s]", port_type->type_name);
  2443. free (connection);
  2444. jack_unlock_graph (engine);
  2445. return -1;
  2446. } else {
  2447. if (dstclient->control->type == ClientDriver)
  2448. {
  2449. /* Ignore output connections to drivers for purposes
  2450. of sorting. Drivers are executed first in the sort
  2451. order anyway, and we don't want to treat graphs
  2452. such as driver -> client -> driver as containing
  2453. feedback */
  2454. VERBOSE (engine,
  2455. "connect %s and %s (output)\n",
  2456. srcport->shared->name,
  2457. dstport->shared->name);
  2458. connection->dir = 1;
  2459. }
  2460. else if (srcclient != dstclient) {
  2461. srcclient->truefeeds = jack_slist_prepend
  2462. (srcclient->truefeeds, dstclient);
  2463. dstclient->fedcount++;
  2464. if (jack_client_feeds_transitive (dstclient,
  2465. srcclient ) ||
  2466. (dstclient->control->type == ClientDriver &&
  2467. srcclient->control->type != ClientDriver)) {
  2468. /* dest is running before source so
  2469. this is a feedback connection */
  2470. VERBOSE (engine,
  2471. "connect %s and %s (feedback)\n",
  2472. srcport->shared->name,
  2473. dstport->shared->name);
  2474. dstclient->sortfeeds = jack_slist_prepend
  2475. (dstclient->sortfeeds, srcclient);
  2476. connection->dir = -1;
  2477. engine->feedbackcount++;
  2478. VERBOSE (engine,
  2479. "feedback count up to %d\n",
  2480. engine->feedbackcount);
  2481. } else {
  2482. /* this is not a feedback connection */
  2483. VERBOSE (engine,
  2484. "connect %s and %s (forward)\n",
  2485. srcport->shared->name,
  2486. dstport->shared->name);
  2487. srcclient->sortfeeds = jack_slist_prepend
  2488. (srcclient->sortfeeds, dstclient);
  2489. connection->dir = 1;
  2490. }
  2491. }
  2492. else
  2493. {
  2494. /* this is a connection to self */
  2495. VERBOSE (engine,
  2496. "connect %s and %s (self)\n",
  2497. srcport->shared->name,
  2498. dstport->shared->name);
  2499. connection->dir = 0;
  2500. }
  2501. dstport->connections =
  2502. jack_slist_prepend (dstport->connections, connection);
  2503. srcport->connections =
  2504. jack_slist_prepend (srcport->connections, connection);
  2505. DEBUG ("actually sorted the graph...");
  2506. jack_send_connection_notification (engine,
  2507. srcport->shared->client_id,
  2508. src_id, dst_id, TRUE);
  2509. jack_send_connection_notification (engine,
  2510. dstport->shared->client_id,
  2511. dst_id, src_id, TRUE);
  2512. jack_sort_graph (engine);
  2513. }
  2514. jack_unlock_graph (engine);
  2515. return 0;
  2516. }
  2517. int
  2518. jack_port_disconnect_internal (jack_engine_t *engine,
  2519. jack_port_internal_t *srcport,
  2520. jack_port_internal_t *dstport )
  2521. {
  2522. JSList *node;
  2523. jack_connection_internal_t *connect;
  2524. int ret = -1;
  2525. jack_port_id_t src_id, dst_id;
  2526. int check_acyclic = engine->feedbackcount;
  2527. /* call tree **** MUST HOLD **** engine->client_lock. */
  2528. for (node = srcport->connections; node;
  2529. node = jack_slist_next (node)) {
  2530. connect = (jack_connection_internal_t *) node->data;
  2531. if (connect->source == srcport &&
  2532. connect->destination == dstport) {
  2533. VERBOSE (engine, "DIS-connect %s and %s\n",
  2534. srcport->shared->name,
  2535. dstport->shared->name);
  2536. srcport->connections =
  2537. jack_slist_remove (srcport->connections,
  2538. connect);
  2539. dstport->connections =
  2540. jack_slist_remove (dstport->connections,
  2541. connect);
  2542. src_id = srcport->shared->id;
  2543. dst_id = dstport->shared->id;
  2544. /* this is a bit harsh, but it basically says
  2545. that if we actually do a disconnect, and
  2546. its the last one, then make sure that any
  2547. input monitoring is turned off on the
  2548. srcport. this isn't ideal for all
  2549. situations, but it works better for most of
  2550. them.
  2551. */
  2552. if (srcport->connections == NULL) {
  2553. srcport->shared->monitor_requests = 0;
  2554. }
  2555. jack_send_connection_notification (
  2556. engine, srcport->shared->client_id, src_id,
  2557. dst_id, FALSE);
  2558. jack_send_connection_notification (
  2559. engine, dstport->shared->client_id, dst_id,
  2560. src_id, FALSE);
  2561. if (connect->dir) {
  2562. jack_client_internal_t *src;
  2563. jack_client_internal_t *dst;
  2564. src = jack_client_internal_by_id
  2565. (engine, srcport->shared->client_id);
  2566. dst = jack_client_internal_by_id
  2567. (engine, dstport->shared->client_id);
  2568. src->truefeeds = jack_slist_remove
  2569. (src->truefeeds, dst);
  2570. dst->fedcount--;
  2571. if (connect->dir == 1) {
  2572. /* normal connection: remove dest from
  2573. source's sortfeeds list */
  2574. src->sortfeeds = jack_slist_remove
  2575. (src->sortfeeds, dst);
  2576. } else {
  2577. /* feedback connection: remove source
  2578. from dest's sortfeeds list */
  2579. dst->sortfeeds = jack_slist_remove
  2580. (dst->sortfeeds, src);
  2581. engine->feedbackcount--;
  2582. VERBOSE (engine,
  2583. "feedback count down to %d\n",
  2584. engine->feedbackcount);
  2585. }
  2586. } /* else self-connection: do nothing */
  2587. free (connect);
  2588. ret = 0;
  2589. break;
  2590. }
  2591. }
  2592. if (check_acyclic) {
  2593. jack_check_acyclic (engine);
  2594. }
  2595. jack_sort_graph (engine);
  2596. return ret;
  2597. }
  2598. static int
  2599. jack_port_do_disconnect_all (jack_engine_t *engine,
  2600. jack_port_id_t port_id)
  2601. {
  2602. if (port_id >= engine->control->port_max) {
  2603. jack_error ("illegal port ID in attempted disconnection [%"
  2604. PRIu32 "]", port_id);
  2605. return -1;
  2606. }
  2607. VERBOSE (engine, "clear connections for %s\n",
  2608. engine->internal_ports[port_id].shared->name);
  2609. jack_lock_graph (engine);
  2610. jack_port_clear_connections (engine, &engine->internal_ports[port_id]);
  2611. jack_sort_graph (engine);
  2612. jack_unlock_graph (engine);
  2613. return 0;
  2614. }
  2615. static int
  2616. jack_port_do_disconnect (jack_engine_t *engine,
  2617. const char *source_port,
  2618. const char *destination_port)
  2619. {
  2620. jack_port_internal_t *srcport, *dstport;
  2621. int ret = -1;
  2622. if ((srcport = jack_get_port_by_name (engine, source_port)) == NULL) {
  2623. jack_error ("unknown source port in attempted disconnection"
  2624. " [%s]", source_port);
  2625. return -1;
  2626. }
  2627. if ((dstport = jack_get_port_by_name (engine, destination_port))
  2628. == NULL) {
  2629. jack_error ("unknown destination port in attempted"
  2630. " disconnection [%s]", destination_port);
  2631. return -1;
  2632. }
  2633. jack_lock_graph (engine);
  2634. ret = jack_port_disconnect_internal (engine, srcport, dstport);
  2635. jack_unlock_graph (engine);
  2636. return ret;
  2637. }
  2638. int
  2639. jack_get_fifo_fd (jack_engine_t *engine, unsigned int which_fifo)
  2640. {
  2641. /* caller must hold client_lock */
  2642. char path[PATH_MAX+1];
  2643. struct stat statbuf;
  2644. snprintf (path, sizeof (path), "%s-%d", engine->fifo_prefix,
  2645. which_fifo);
  2646. DEBUG ("%s", path);
  2647. if (stat (path, &statbuf)) {
  2648. if (errno == ENOENT) {
  2649. if (mkfifo(path, 0666) < 0){
  2650. jack_error ("cannot create inter-client FIFO"
  2651. " [%s] (%s)\n", path,
  2652. strerror (errno));
  2653. return -1;
  2654. }
  2655. } else {
  2656. jack_error ("cannot check on FIFO %d\n", which_fifo);
  2657. return -1;
  2658. }
  2659. } else {
  2660. if (!S_ISFIFO(statbuf.st_mode)) {
  2661. jack_error ("FIFO %d (%s) already exists, but is not"
  2662. " a FIFO!\n", which_fifo, path);
  2663. return -1;
  2664. }
  2665. }
  2666. if (which_fifo >= engine->fifo_size) {
  2667. unsigned int i;
  2668. engine->fifo = (int *)
  2669. realloc (engine->fifo,
  2670. sizeof (int) * (engine->fifo_size + 16));
  2671. for (i = engine->fifo_size; i < engine->fifo_size + 16; i++) {
  2672. engine->fifo[i] = -1;
  2673. }
  2674. engine->fifo_size += 16;
  2675. }
  2676. if (engine->fifo[which_fifo] < 0) {
  2677. if ((engine->fifo[which_fifo] =
  2678. open (path, O_RDWR|O_CREAT|O_NONBLOCK, 0666)) < 0) {
  2679. jack_error ("cannot open fifo [%s] (%s)", path,
  2680. strerror (errno));
  2681. return -1;
  2682. }
  2683. DEBUG ("opened engine->fifo[%d] == %d (%s)",
  2684. which_fifo, engine->fifo[which_fifo], path);
  2685. }
  2686. return engine->fifo[which_fifo];
  2687. }
  2688. static void
  2689. jack_clear_fifos (jack_engine_t *engine)
  2690. {
  2691. /* caller must hold client_lock */
  2692. unsigned int i;
  2693. char buf[16];
  2694. /* this just drains the existing FIFO's of any data left in
  2695. them by aborted clients, etc. there is only ever going to
  2696. be 0, 1 or 2 bytes in them, but we'll allow for up to 16.
  2697. */
  2698. for (i = 0; i < engine->fifo_size; i++) {
  2699. if (engine->fifo[i] >= 0) {
  2700. int nread = read (engine->fifo[i], buf, sizeof (buf));
  2701. if (nread < 0 && errno != EAGAIN) {
  2702. jack_error ("clear fifo[%d] error: %s",
  2703. i, strerror (errno));
  2704. }
  2705. }
  2706. }
  2707. }
  2708. static int
  2709. jack_use_driver (jack_engine_t *engine, jack_driver_t *driver)
  2710. {
  2711. if (engine->driver) {
  2712. engine->driver->detach (engine->driver, engine);
  2713. engine->driver = 0;
  2714. }
  2715. if (driver) {
  2716. if (driver->attach (driver, engine))
  2717. return -1;
  2718. engine->rolling_interval =
  2719. jack_rolling_interval (driver->period_usecs);
  2720. }
  2721. engine->driver = driver;
  2722. return 0;
  2723. }
  2724. /* PORT RELATED FUNCTIONS */
  2725. static jack_port_id_t
  2726. jack_get_free_port (jack_engine_t *engine)
  2727. {
  2728. jack_port_id_t i;
  2729. pthread_mutex_lock (&engine->port_lock);
  2730. for (i = 0; i < engine->port_max; i++) {
  2731. if (engine->control->ports[i].in_use == 0) {
  2732. engine->control->ports[i].in_use = 1;
  2733. break;
  2734. }
  2735. }
  2736. pthread_mutex_unlock (&engine->port_lock);
  2737. if (i == engine->port_max) {
  2738. return (jack_port_id_t) -1;
  2739. }
  2740. return i;
  2741. }
  2742. void
  2743. jack_port_release (jack_engine_t *engine, jack_port_internal_t *port)
  2744. {
  2745. pthread_mutex_lock (&engine->port_lock);
  2746. port->shared->in_use = 0;
  2747. port->shared->alias1[0] = '\0';
  2748. port->shared->alias2[0] = '\0';
  2749. if (port->buffer_info) {
  2750. jack_port_buffer_list_t *blist =
  2751. jack_port_buffer_list (engine, port);
  2752. pthread_mutex_lock (&blist->lock);
  2753. blist->freelist =
  2754. jack_slist_prepend (blist->freelist,
  2755. port->buffer_info);
  2756. port->buffer_info = NULL;
  2757. pthread_mutex_unlock (&blist->lock);
  2758. }
  2759. pthread_mutex_unlock (&engine->port_lock);
  2760. }
  2761. jack_port_internal_t *
  2762. jack_get_port_internal_by_name (jack_engine_t *engine, const char *name)
  2763. {
  2764. jack_port_id_t id;
  2765. pthread_mutex_lock (&engine->port_lock);
  2766. for (id = 0; id < engine->port_max; id++) {
  2767. if (jack_port_name_equals (&engine->control->ports[id], name)) {
  2768. break;
  2769. }
  2770. }
  2771. pthread_mutex_unlock (&engine->port_lock);
  2772. if (id != engine->port_max) {
  2773. return &engine->internal_ports[id];
  2774. } else {
  2775. return NULL;
  2776. }
  2777. }
  2778. int
  2779. jack_port_do_register (jack_engine_t *engine, jack_request_t *req)
  2780. {
  2781. jack_port_id_t port_id;
  2782. jack_port_shared_t *shared;
  2783. jack_port_internal_t *port;
  2784. jack_client_internal_t *client;
  2785. unsigned long i;
  2786. for (i = 0; i < engine->control->n_port_types; ++i) {
  2787. if (strcmp (req->x.port_info.type,
  2788. engine->control->port_types[i].type_name) == 0) {
  2789. break;
  2790. }
  2791. }
  2792. if (i == engine->control->n_port_types) {
  2793. jack_error ("cannot register a port of type \"%s\"",
  2794. req->x.port_info.type);
  2795. return -1;
  2796. }
  2797. jack_lock_graph (engine);
  2798. if ((client = jack_client_internal_by_id (engine,
  2799. req->x.port_info.client_id))
  2800. == NULL) {
  2801. jack_error ("unknown client id in port registration request");
  2802. return -1;
  2803. }
  2804. jack_unlock_graph (engine);
  2805. if ((port_id = jack_get_free_port (engine)) == (jack_port_id_t) -1) {
  2806. jack_error ("no ports available!");
  2807. return -1;
  2808. }
  2809. shared = &engine->control->ports[port_id];
  2810. strcpy (shared->name, req->x.port_info.name);
  2811. shared->ptype_id = engine->control->port_types[i].ptype_id;
  2812. shared->client_id = req->x.port_info.client_id;
  2813. shared->flags = req->x.port_info.flags;
  2814. shared->latency = 0;
  2815. shared->monitor_requests = 0;
  2816. port = &engine->internal_ports[port_id];
  2817. port->shared = shared;
  2818. port->connections = 0;
  2819. port->buffer_info = NULL;
  2820. if (jack_port_assign_buffer (engine, port)) {
  2821. jack_error ("cannot assign buffer for port");
  2822. return -1;
  2823. }
  2824. jack_lock_graph (engine);
  2825. client->ports = jack_slist_prepend (client->ports, port);
  2826. jack_port_registration_notify (engine, port_id, TRUE);
  2827. jack_unlock_graph (engine);
  2828. VERBOSE (engine, "registered port %s, offset = %u\n",
  2829. shared->name, (unsigned int)shared->offset);
  2830. req->x.port_info.port_id = port_id;
  2831. return 0;
  2832. }
  2833. int
  2834. jack_port_do_unregister (jack_engine_t *engine, jack_request_t *req)
  2835. {
  2836. jack_client_internal_t *client;
  2837. jack_port_shared_t *shared;
  2838. jack_port_internal_t *port;
  2839. if (req->x.port_info.port_id < 0 ||
  2840. req->x.port_info.port_id > engine->port_max) {
  2841. jack_error ("invalid port ID %" PRIu32
  2842. " in unregister request",
  2843. req->x.port_info.port_id);
  2844. return -1;
  2845. }
  2846. shared = &engine->control->ports[req->x.port_info.port_id];
  2847. if (shared->client_id != req->x.port_info.client_id) {
  2848. jack_error ("Client %" PRIu32
  2849. " is not allowed to remove port %s",
  2850. req->x.port_info.client_id, shared->name);
  2851. return -1;
  2852. }
  2853. jack_lock_graph (engine);
  2854. if ((client = jack_client_internal_by_id (engine, shared->client_id))
  2855. == NULL) {
  2856. jack_error ("unknown client id in port registration request");
  2857. jack_unlock_graph (engine);
  2858. return -1;
  2859. }
  2860. port = &engine->internal_ports[req->x.port_info.port_id];
  2861. jack_port_clear_connections (engine, port);
  2862. jack_port_release (engine,
  2863. &engine->internal_ports[req->x.port_info.port_id]);
  2864. client->ports = jack_slist_remove (client->ports, port);
  2865. jack_port_registration_notify (engine, req->x.port_info.port_id,
  2866. FALSE);
  2867. jack_unlock_graph (engine);
  2868. return 0;
  2869. }
  2870. int
  2871. jack_do_get_port_connections (jack_engine_t *engine, jack_request_t *req,
  2872. int reply_fd)
  2873. {
  2874. jack_port_internal_t *port;
  2875. JSList *node;
  2876. unsigned int i;
  2877. int ret = -1;
  2878. int internal = FALSE;
  2879. jack_lock_graph (engine);
  2880. port = &engine->internal_ports[req->x.port_info.port_id];
  2881. DEBUG ("Getting connections for port '%s'.", port->shared->name);
  2882. req->x.port_connections.nports = jack_slist_length (port->connections);
  2883. req->status = 0;
  2884. /* figure out if this is an internal or external client */
  2885. for (node = engine->clients; node; node = jack_slist_next (node)) {
  2886. if (((jack_client_internal_t *) node->data)->request_fd
  2887. == reply_fd) {
  2888. internal = jack_client_is_internal(
  2889. (jack_client_internal_t *) node->data);
  2890. break;
  2891. }
  2892. }
  2893. if (!internal) {
  2894. if (write (reply_fd, req, sizeof (*req))
  2895. < (ssize_t) sizeof (req)) {
  2896. jack_error ("cannot write GetPortConnections result "
  2897. "to client via fd = %d (%s)",
  2898. reply_fd, strerror (errno));
  2899. goto out;
  2900. }
  2901. } else {
  2902. req->x.port_connections.ports = (const char **)
  2903. malloc (sizeof (char *)
  2904. * req->x.port_connections.nports);
  2905. }
  2906. if (req->type == GetPortConnections) {
  2907. for (i = 0, node = port->connections; node;
  2908. node = jack_slist_next (node), ++i) {
  2909. jack_port_id_t port_id;
  2910. if (((jack_connection_internal_t *) node->data)->source
  2911. == port) {
  2912. port_id = ((jack_connection_internal_t *)
  2913. node->data)->destination->shared->id;
  2914. } else {
  2915. port_id = ((jack_connection_internal_t *)
  2916. node->data)->source->shared->id;
  2917. }
  2918. if (internal) {
  2919. /* internal client asking for
  2920. * names. store in malloc'ed space,
  2921. * client frees
  2922. */
  2923. req->x.port_connections.ports[i] =
  2924. engine->control->ports[port_id].name;
  2925. } else {
  2926. /* external client asking for
  2927. * names. we write the port id's to
  2928. * the reply fd.
  2929. */
  2930. if (write (reply_fd, &port_id,
  2931. sizeof (port_id))
  2932. < (ssize_t) sizeof (port_id)) {
  2933. jack_error ("cannot write port id "
  2934. "to client");
  2935. goto out;
  2936. }
  2937. }
  2938. }
  2939. }
  2940. ret = 0;
  2941. out:
  2942. req->status = ret;
  2943. jack_unlock_graph (engine);
  2944. return ret;
  2945. }
  2946. void
  2947. jack_port_registration_notify (jack_engine_t *engine,
  2948. jack_port_id_t port_id, int yn)
  2949. {
  2950. jack_event_t event;
  2951. jack_client_internal_t *client;
  2952. JSList *node;
  2953. event.type = (yn ? PortRegistered : PortUnregistered);
  2954. event.x.port_id = port_id;
  2955. for (node = engine->clients; node; node = jack_slist_next (node)) {
  2956. client = (jack_client_internal_t *) node->data;
  2957. if (!client->control->active) {
  2958. continue;
  2959. }
  2960. if (client->control->port_register) {
  2961. if (jack_deliver_event (engine, client, &event)) {
  2962. jack_error ("cannot send port registration"
  2963. " notification to %s (%s)",
  2964. client->control->name,
  2965. strerror (errno));
  2966. }
  2967. }
  2968. }
  2969. }
  2970. void
  2971. jack_client_registration_notify (jack_engine_t *engine,
  2972. const char* name, int yn)
  2973. {
  2974. jack_event_t event;
  2975. jack_client_internal_t *client;
  2976. JSList *node;
  2977. event.type = (yn ? ClientRegistered : ClientUnregistered);
  2978. snprintf (event.x.name, sizeof (event.x.name), "%s", name);
  2979. for (node = engine->clients; node; node = jack_slist_next (node)) {
  2980. client = (jack_client_internal_t *) node->data;
  2981. if (!client->control->active) {
  2982. continue;
  2983. }
  2984. if (strcmp ((char*) client->control->name, (char*) name) == 0) {
  2985. /* do not notify client of its own registration */
  2986. continue;
  2987. }
  2988. if (client->control->client_register) {
  2989. if (jack_deliver_event (engine, client, &event)) {
  2990. jack_error ("cannot send client registration"
  2991. " notification to %s (%s)",
  2992. client->control->name,
  2993. strerror (errno));
  2994. }
  2995. }
  2996. }
  2997. }
  2998. int
  2999. jack_port_assign_buffer (jack_engine_t *engine, jack_port_internal_t *port)
  3000. {
  3001. jack_port_buffer_list_t *blist =
  3002. jack_port_buffer_list (engine, port);
  3003. jack_port_buffer_info_t *bi;
  3004. if (port->shared->flags & JackPortIsInput) {
  3005. port->shared->offset = 0;
  3006. return 0;
  3007. }
  3008. pthread_mutex_lock (&blist->lock);
  3009. if (blist->freelist == NULL) {
  3010. jack_port_type_info_t *port_type =
  3011. jack_port_type_info (engine, port);
  3012. jack_error ("all %s port buffers in use!",
  3013. port_type->type_name);
  3014. pthread_mutex_unlock (&blist->lock);
  3015. return -1;
  3016. }
  3017. bi = (jack_port_buffer_info_t *) blist->freelist->data;
  3018. blist->freelist = jack_slist_remove (blist->freelist, bi);
  3019. port->shared->offset = bi->offset;
  3020. port->buffer_info = bi;
  3021. pthread_mutex_unlock (&blist->lock);
  3022. return 0;
  3023. }
  3024. static jack_port_internal_t *
  3025. jack_get_port_by_name (jack_engine_t *engine, const char *name)
  3026. {
  3027. jack_port_id_t id;
  3028. /* Note the potential race on "in_use". Other design
  3029. elements prevent this from being a problem.
  3030. */
  3031. for (id = 0; id < engine->port_max; id++) {
  3032. if (engine->control->ports[id].in_use &&
  3033. jack_port_name_equals (&engine->control->ports[id], name)) {
  3034. return &engine->internal_ports[id];
  3035. }
  3036. }
  3037. return NULL;
  3038. }
  3039. static int
  3040. jack_send_connection_notification (jack_engine_t *engine,
  3041. jack_client_id_t client_id,
  3042. jack_port_id_t self_id,
  3043. jack_port_id_t other_id, int connected)
  3044. {
  3045. jack_client_internal_t *client;
  3046. jack_event_t event;
  3047. if ((client = jack_client_internal_by_id (engine, client_id)) == NULL) {
  3048. jack_error ("no such client %" PRIu32
  3049. " during connection notification", client_id);
  3050. return -1;
  3051. }
  3052. if (client->control->active) {
  3053. event.type = (connected ? PortConnected : PortDisconnected);
  3054. event.x.self_id = self_id;
  3055. event.y.other_id = other_id;
  3056. if (jack_deliver_event (engine, client, &event)) {
  3057. jack_error ("cannot send port connection notification"
  3058. " to client %s (%s)",
  3059. client->control->name, strerror (errno));
  3060. return -1;
  3061. }
  3062. }
  3063. return 0;
  3064. }