2 * jackwsmeter - jack meter over websockets
4 * Copyright (C) 2014 Frederic Peters <fpeters@0d.be>
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License as
8 * published by the Free Software Foundation; either version 2 of the
9 * License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * General Public License for more details.
16 * You should have received a copy of the GNU General Public
17 * License along with this program; if not, see
18 * <http://www.gnu.org/licenses/>.
23 * from the libwebsockets test server: LGPL 2.1
24 * Copyright (C) 2010-2011 Andy Green <andy@warmcat.com>
25 * from jackmeter, GPL 2+
26 * Copyright (C) 2005 Nicholas J. Humfrey
41 #include <libwebsockets.h>
43 #include <jack/jack.h>
45 int max_poll_elements;
47 struct pollfd *pollfds;
57 float peaks[MAX_METERS];
58 float sent_peaks[MAX_METERS];
60 jack_port_t *input_ports[MAX_METERS];
61 jack_client_t *client = NULL;
64 /* Read and reset the recent peak sample */
65 static void read_peaks()
67 memcpy(sent_peaks, peaks, sizeof(peaks));
68 memset(peaks, 0, sizeof(peaks));
72 /* this protocol server (always the first one) just knows how to do HTTP */
74 static int callback_http(struct libwebsocket_context *context,
75 struct libwebsocket *wsi,
76 enum libwebsocket_callback_reasons reason, void *user,
82 struct libwebsocket_pollargs *pa = (struct libwebsocket_pollargs *)in;
84 int fd = (int)(long)user;
88 case LWS_CALLBACK_HTTP:
89 html_filepath = malloc(strlen(DATADIR "/jackwsmeter.html") + 1);
90 strcpy(html_filepath, DATADIR "jackwsmeter.html\n\n");
91 if (access(html_filepath, F_OK) != 0) {
92 /* it doesn't exist in the system directory, fall back
93 * on the current directory. */
94 strcpy(html_filepath, "jackwsmeter.html");
97 if (libwebsockets_serve_http_file(context, wsi, html_filepath, "text/html", NULL)) {
99 if (libwebsockets_serve_http_file(context, wsi, html_filepath, "text/html")) {
102 return 1; /* through completion or error, close the socket */
108 case LWS_CALLBACK_HTTP_FILE_COMPLETION:
111 case LWS_CALLBACK_ADD_POLL_FD:
113 if (count_pollfds >= max_poll_elements) {
114 lwsl_err("LWS_CALLBACK_ADD_POLL_FD: too many sockets to track\n");
119 fd_lookup[pa->fd] = count_pollfds;
120 pollfds[count_pollfds].fd = pa->fd;
121 pollfds[count_pollfds].events = pa->events;
123 fd_lookup[fd] = count_pollfds;
124 pollfds[count_pollfds].fd = fd;
125 pollfds[count_pollfds].events = (int)(long)len;
127 pollfds[count_pollfds++].revents = 0;
130 case LWS_CALLBACK_DEL_POLL_FD:
131 if (!--count_pollfds)
134 m = fd_lookup[pa->fd];
138 /* have the last guy take up the vacant slot */
139 pollfds[m] = pollfds[count_pollfds];
140 fd_lookup[pollfds[count_pollfds].fd] = m;
144 case LWS_CALLBACK_CHANGE_MODE_POLL_FD:
145 pollfds[fd_lookup[pa->fd]].events = pa->events;
148 case LWS_CALLBACK_SET_MODE_POLL_FD:
149 pollfds[fd_lookup[fd]].events |= (int)(long)len;
152 case LWS_CALLBACK_CLEAR_MODE_POLL_FD:
153 pollfds[fd_lookup[fd]].events &= ~(int)(long)len;
165 callback_meter(struct libwebsocket_context *context,
166 struct libwebsocket *wsi,
167 enum libwebsocket_callback_reasons reason,
168 void *user, void *in, size_t len)
174 char buf[LWS_SEND_BUFFER_PRE_PADDING + 512 + LWS_SEND_BUFFER_POST_PADDING];
175 char *p = &buf[LWS_SEND_BUFFER_PRE_PADDING];
179 case LWS_CALLBACK_ESTABLISHED:
182 case LWS_CALLBACK_SERVER_WRITEABLE:
184 for (i=0; i<num_meters; i++) {
185 db = 20.0f * log10f(sent_peaks[i] * bias);
186 snprintf(one_peak, 100, "%f ", db);
187 strcat((char*)p, one_peak);
190 p[n-1] = '\0'; /* remove trailing space */
192 n = libwebsocket_write(wsi, (unsigned char*)p, n, LWS_WRITE_TEXT);
194 lwsl_err("ERROR %d writing to socket\n", n);
206 /* list of supported protocols and callbacks */
208 static struct libwebsocket_protocols protocols[] = {
209 /* first protocol must always be HTTP handler */
212 "http-only", /* name */
213 callback_http, /* callback */
214 0, /* per_session_data_size */
215 0, /* max frame size / rx buffer */
218 "jack-wsmeter-protocol",
223 { NULL, NULL, 0, 0 } /* terminator */
226 void sighandler(int sig)
231 static struct option options[] = {
232 { "help", no_argument, NULL, 'h' },
233 { "debug", required_argument, NULL, 'd' },
234 { "port", required_argument, NULL, 'p' },
235 { "ssl-cert", required_argument, NULL, 'E' },
236 { "ssl-key", required_argument, NULL, 'k' },
237 { "interface", required_argument, NULL, 'i' },
238 #ifndef LWS_NO_DAEMONIZE
239 { "daemonize", no_argument, NULL, 'D' },
241 { "name", required_argument, NULL, 'n' },
246 /* Callback called by JACK when audio is available.
247 Stores value of peak sample */
248 static int process_peak(jack_nframes_t nframes, void *arg)
250 unsigned int i, port;
252 for (port = 0; port < num_meters; port++) {
253 jack_default_audio_sample_t *in;
255 /* just incase the port isn't registered yet */
256 if (input_ports[port] == 0) {
260 in = (jack_default_audio_sample_t *) jack_port_get_buffer(input_ports[port], nframes);
262 for (i = 0; i < nframes; i++) {
263 const float s = fabs(in[i]);
264 if (s > peaks[port]) {
274 /* Close down JACK when exiting */
275 static void cleanup()
277 const char **all_ports;
280 lwsl_debug("cleanup()\n");
282 for (i=0; i<num_meters; i++) {
283 all_ports = jack_port_get_all_connections(client, input_ports[i]);
285 for (j=0; all_ports && all_ports[j]; j++) {
286 jack_disconnect(client, all_ports[j], jack_port_name(input_ports[i]));
290 /* Leave the jack graph */
291 jack_client_close(client);
297 int main(int argc, char **argv)
300 struct libwebsocket_context *context;
302 char interface_name[128] = "";
303 char jack_name[128] = "wsmeter";
304 const char *iface = NULL;
305 int syslog_options = LOG_PID | LOG_PERROR;
306 unsigned int oldus = 0;
307 struct lws_context_creation_info info;
310 #ifndef LWS_NO_DAEMONIZE
314 jack_status_t status;
316 memset(&info, 0, sizeof info);
320 n = getopt_long(argc, argv, "ci:hsp:d:Dn:", options, NULL);
324 #ifndef LWS_NO_DAEMONIZE
327 syslog_options &= ~LOG_PERROR;
331 debug_level = atoi(optarg);
334 info.ssl_cert_filepath = strdup(optarg);
337 info.ssl_private_key_filepath = strdup(optarg);
340 info.port = atoi(optarg);
343 strncpy(interface_name, optarg, sizeof interface_name);
344 interface_name[(sizeof interface_name) - 1] = '\0';
345 iface = interface_name;
348 strncpy(jack_name, optarg, sizeof jack_name);
349 jack_name[(sizeof jack_name) - 1] = '\0';
352 fprintf(stderr, "Usage: jackwsserver "
353 "[--port=<p>] [--ssl-cert FILEPATH] [--ssl-key FILEPATH] "
354 "[-d <log bitfield>] <port>+\n");
359 #if !defined(LWS_NO_DAEMONIZE)
361 * normally lock path would be /var/lock/jwsm or similar, to
362 * simplify getting started without having to take care about
363 * permissions or running as root, set to /tmp/.jwsm-lock
365 if (daemonize && lws_daemonize("/tmp/.jwsm-lock")) {
366 fprintf(stderr, "Failed to daemonize\n");
371 signal(SIGINT, sighandler);
373 /* we will only try to log things according to our debug_level */
374 setlogmask(LOG_UPTO (LOG_DEBUG));
375 openlog("jackwsmeter", syslog_options, LOG_DAEMON);
377 /* tell the library what debug level to emit and to send it to syslog */
378 lws_set_log_level(debug_level, lwsl_emit_syslog);
380 max_poll_elements = getdtablesize();
381 pollfds = malloc(max_poll_elements * sizeof (struct pollfd));
382 fd_lookup = malloc(max_poll_elements * sizeof (int));
383 if (pollfds == NULL || fd_lookup == NULL) {
384 lwsl_err("Out of memory pollfds=%d\n", max_poll_elements);
389 info.protocols = protocols;
390 #ifndef LWS_NO_EXTENSIONS
391 info.extensions = libwebsocket_get_internal_extensions();
397 // Register with Jack
398 if ((client = jack_client_open(jack_name, JackNullOption, &status)) == 0) {
399 lwsl_err("Failed to start jack client: %d\n", status);
402 lwsl_debug("Registering as '%s'.\n", jack_get_client_name(client));
404 // Register the cleanup function to be called when program exits
407 // Register the peak signal callback
408 jack_set_process_callback(client, process_peak, 0);
411 if (jack_activate(client)) {
412 lwsl_err("Cannot activate client.\n");
421 // Create our input port
422 snprintf(in_name, 255, "in_%d", num_meters);
423 if (!(input_ports[num_meters] = jack_port_register(client, in_name,
424 JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0))) {
425 lwsl_err("Cannot register input port '%s'.\n", in_name);
429 port = jack_port_by_name(client, argv[opts]);
431 lwsl_err("Can't find port '%s'\n", argv[opts]);
433 if (jack_connect(client, jack_port_name(port), jack_port_name(input_ports[num_meters]))) {
434 lwsl_err("failed to connect to port '%s'\n", argv[opts]);
439 if (num_meters == MAX_METERS) {
440 lwsl_err("maximum number of meters (%d) reached.\n", MAX_METERS);
446 if (num_meters == 0) {
447 lwsl_err("You must specify at least one port, aborting.");
451 context = libwebsocket_create_context(&info);
452 if (context == NULL) {
453 lwsl_err("libwebsocket init failed\n");
458 while (n >= 0 && !force_exit) {
461 gettimeofday(&tv, NULL);
466 * This provokes the LWS_CALLBACK_SERVER_WRITEABLE for every
467 * live websocket connection as soon as it can take more packets
468 * (usually immediately)
471 if (((unsigned int)tv.tv_usec - oldus) > 100000) {
472 libwebsocket_callback_on_writable_all_protocol(&protocols[1]);
476 n = poll(pollfds, count_pollfds, 25);
482 for (n = 0; n < count_pollfds; n++)
483 if (pollfds[n].revents)
484 if (libwebsocket_service_fd(context,
489 n = libwebsocket_service(context, 25);
493 libwebsocket_context_destroy(context);
495 lwsl_notice("jackwsserver exited cleanly\n");