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.

4262 lines
106KB

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