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.

3744 lines
91KB

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