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.

4232 lines
105KB

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