summaryrefslogtreecommitdiffstats
path: root/src/utils
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-27 16:03:18 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-27 16:03:18 +0000
commit2dd5bc6a074165ddfbd57c4bd52c2d2dac8f47a1 (patch)
tree465b29cb405d3af0b0ad50c78e1dccc636594fec /src/utils
parentInitial commit. (diff)
downloadpulseaudio-2dd5bc6a074165ddfbd57c4bd52c2d2dac8f47a1.tar.xz
pulseaudio-2dd5bc6a074165ddfbd57c4bd52c2d2dac8f47a1.zip
Adding upstream version 14.2.upstream/14.2upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to '')
-rw-r--r--src/utils/meson.build117
-rwxr-xr-xsrc/utils/pa-info78
-rw-r--r--src/utils/pacat.c1251
-rw-r--r--src/utils/pacmd.c359
-rw-r--r--src/utils/pactl.c2165
-rw-r--r--src/utils/padsp.c2747
-rwxr-xr-xsrc/utils/padsp.in84
-rw-r--r--src/utils/pasuspender.c343
-rw-r--r--src/utils/pax11publish.c220
-rwxr-xr-xsrc/utils/qpaeq574
10 files changed, 7938 insertions, 0 deletions
diff --git a/src/utils/meson.build b/src/utils/meson.build
new file mode 100644
index 0000000..dedf4e4
--- /dev/null
+++ b/src/utils/meson.build
@@ -0,0 +1,117 @@
+pacat_sources = [
+ 'pacat.c',
+]
+
+pacat_aliases = [
+ 'pamon',
+ 'paplay',
+ 'parec',
+ 'parecord',
+]
+
+executable('pacat',
+ pacat_sources,
+ install: true,
+ install_rpath : privlibdir,
+ include_directories : [configinc, topinc],
+ link_with : [libpulsecommon, libpulse],
+ dependencies : [sndfile_dep, libintl_dep],
+ c_args : pa_c_args,
+)
+
+foreach alias : pacat_aliases
+ # FIXME How to handle extension (.exe on windows)?
+ dst = join_paths(bindir, alias)
+ cmd = 'ln -fs @0@ $DESTDIR@1@'.format('pacat', dst)
+ meson.add_install_script('sh', '-c', cmd)
+endforeach
+
+pactl_sources = [
+ 'pactl.c',
+]
+
+executable('pactl',
+ pactl_sources,
+ install: true,
+ install_rpath : privlibdir,
+ include_directories : [configinc, topinc],
+ link_with : [libpulsecommon, libpulse],
+ dependencies : [sndfile_dep, libintl_dep],
+ c_args : pa_c_args,
+)
+
+pasuspender_sources = [
+ 'pasuspender.c',
+]
+
+executable('pasuspender',
+ pasuspender_sources,
+ install: true,
+ install_rpath : privlibdir,
+ include_directories : [configinc, topinc],
+ link_with : [libpulsecommon, libpulse],
+ dependencies: [libintl_dep],
+ c_args : pa_c_args,
+)
+
+pacmd_sources = [
+ 'pacmd.c',
+]
+
+executable('pacmd',
+ pacmd_sources,
+ install: true,
+ install_rpath : privlibdir,
+ include_directories : [configinc, topinc],
+ link_with : [libpulsecommon, libpulse],
+ dependencies: [libintl_dep],
+ c_args : pa_c_args,
+)
+
+if x11_dep.found()
+ pax11publish_sources = [
+ 'pax11publish.c',
+ ]
+
+ executable('pax11publish',
+ pax11publish_sources,
+ install: true,
+ install_rpath : privlibdir,
+ include_directories : [configinc, topinc],
+ link_with : [libpulsecommon, libpulse],
+ dependencies : [x11_dep, libintl_dep],
+ c_args : pa_c_args,
+ )
+endif
+
+if cc.has_header('sys/soundcard.h')
+ libpulsecommon_sources = [
+ 'padsp.c',
+ ]
+
+ libpulsedsp = shared_library('pulsedsp',
+ libpulsecommon_sources,
+ install: true,
+ install_dir : padsplibdir,
+ install_rpath : privlibdir,
+ include_directories : [configinc, topinc],
+ link_with : [libpulsecommon, libpulse],
+ link_args : [nodelete_link_args],
+ dependencies: [thread_dep, dl_dep],
+ c_args : [pa_c_args, '-Wno-nonnull-compare']
+ )
+
+ configure_file(
+ input : 'padsp.in',
+ output : 'padsp',
+ configuration : cdata,
+ install : true,
+ install_dir : bindir,
+ )
+endif
+
+if dbus_dep.found() and fftw_dep.found()
+ install_data('qpaeq', install_dir : bindir)
+endif
+
+install_data('pa-info', install_dir : bindir)
diff --git a/src/utils/pa-info b/src/utils/pa-info
new file mode 100755
index 0000000..1b1cc29
--- /dev/null
+++ b/src/utils/pa-info
@@ -0,0 +1,78 @@
+#!/bin/bash
+
+# This file is part of PulseAudio.
+#
+# Copyright 2019 Russell Treleaven <rtreleaven@bunnykick.ca>
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+export LC_ALL=C
+header='________________'
+function cards_get {
+ local line
+ local re='/proc/asound/card([0-9])'
+ local cards=()
+ while read -r line; do
+ [[ $line =~ $re ]] && cards+="${BASH_REMATCH[1]} "
+ done <<< "$(ls --directory /proc/asound/card[0-9])"
+ echo $cards
+}
+function jacks_do {
+ local cards=($(cards_get))
+ for card in "${cards[@]}" ; do
+ echo "card=$card"
+ while read -r line; do
+ [[ $line != "" ]] && amixer -c$card cget "$line";
+ done <<< "$(amixer -c$card controls | grep Jack)"
+ done
+}
+function alsa_info_do {
+ alsa_info=$(which alsa-info.sh)
+ [ $alsa_info ] || alsa_info=$(which alsa-info)
+ [ $alsa_info ] || alsa_info='/usr/share/alsa-base/alsa-info.sh'
+ [ -f $alsa_info ] && {
+ $alsa_info --stdout
+ return
+ }
+ echo "neither alsa-info.sh or alsa-info were found"
+}
+function pulseaudio_ps_do {
+ ps aux | grep pulseaudio
+}
+function cmd_do {
+ echo "$header"
+ echo "> $1"
+ $1
+}
+cmds=(
+ 'pulseaudio_ps_do'
+ 'which pulseaudio'
+ 'pidof pulseaudio'
+ 'pulseaudio --version'
+ 'pactl info'
+ 'pactl list'
+ 'cat /etc/pulse/daemon.conf'
+ 'cat /etc/pulse/client.conf'
+ 'cat /etc/pulse/default.pa'
+ 'cat /etc/pulse/system.pa'
+ 'ls -alt /dev/snd/*'
+ 'lsof /dev/snd/*'
+ 'jacks_do'
+ 'aplay -L'
+ 'arecord -L'
+ 'alsa_info_do'
+)
+for cmd in "${cmds[@]}" ; do
+ cmd_do "$cmd"
+done
diff --git a/src/utils/pacat.c b/src/utils/pacat.c
new file mode 100644
index 0000000..4d2ecf7
--- /dev/null
+++ b/src/utils/pacat.c
@@ -0,0 +1,1251 @@
+/***
+ This file is part of PulseAudio.
+
+ Copyright 2004-2006 Lennart Poettering
+ Copyright 2006 Pierre Ossman <ossman@cendio.se> for Cendio AB
+
+ PulseAudio is free software; you can redistribute it and/or modify
+ it under the terms of the GNU Lesser General Public License as published
+ by the Free Software Foundation; either version 2.1 of the License,
+ or (at your option) any later version.
+
+ PulseAudio is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+***/
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <signal.h>
+#include <string.h>
+#include <errno.h>
+#include <unistd.h>
+#include <assert.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <getopt.h>
+#include <fcntl.h>
+#include <locale.h>
+
+#include <sndfile.h>
+
+#include <pulse/pulseaudio.h>
+#include <pulse/rtclock.h>
+
+#include <pulsecore/core-util.h>
+#include <pulsecore/i18n.h>
+#include <pulsecore/log.h>
+#include <pulsecore/macro.h>
+#include <pulsecore/sndfile-util.h>
+#include <pulsecore/sample-util.h>
+
+#define TIME_EVENT_USEC 50000
+
+#define CLEAR_LINE "\x1B[K"
+
+static enum { RECORD, PLAYBACK } mode = PLAYBACK;
+static const char *purpose = NULL;
+
+static pa_context *context = NULL;
+static pa_stream *stream = NULL;
+static pa_mainloop_api *mainloop_api = NULL;
+
+/* Playback Mode (raw):
+ *
+ * We can only write audio to the PA stream in multiples of the stream's
+ * sample-spec frame size. Meanwhile, the STDIN read(2) system call can return
+ * a length much smaller than the frame-aligned size requested - leading to
+ * invalid writes. This can be reproduced by choosing a starved STDIN backend
+ * (e.g. "pacat /dev/random", "echo 1234 | pacat"), or an incomplete WAV file
+ * in raw non-paplay mode.
+ *
+ * Solve this by writing only frame-aligned sizes, while caching the resulting
+ * trailing partial frames here. This partial frame is then directly written
+ * in the next stream write iteration. Rinse and repeat.
+ */
+static void *partialframe_buf = NULL;
+static size_t partialframe_len = 0;
+
+/* Recording Mode buffers */
+static void *buffer = NULL;
+static size_t buffer_length = 0, buffer_index = 0;
+
+static void *silence_buffer = NULL;
+static size_t silence_buffer_length = 0;
+
+static pa_io_event* stdio_event = NULL;
+
+static pa_proplist *proplist = NULL;
+static char *device = NULL;
+
+static SNDFILE* sndfile = NULL;
+
+static bool verbose = false;
+static pa_volume_t volume = PA_VOLUME_NORM;
+static bool volume_is_set = false;
+
+static pa_sample_spec sample_spec = {
+ .format = PA_SAMPLE_S16LE,
+ .rate = 44100,
+ .channels = 2
+};
+static bool sample_spec_set = false;
+
+static pa_channel_map channel_map;
+static bool channel_map_set = false;
+
+static sf_count_t (*readf_function)(SNDFILE *_sndfile, void *ptr, sf_count_t frames) = NULL;
+static sf_count_t (*writef_function)(SNDFILE *_sndfile, const void *ptr, sf_count_t frames) = NULL;
+
+static pa_stream_flags_t flags = 0;
+
+static size_t latency = 0, process_time = 0;
+static int32_t latency_msec = 0, process_time_msec = 0;
+
+static bool raw = true;
+static int file_format = -1;
+
+static uint32_t monitor_stream = PA_INVALID_INDEX;
+
+static uint32_t cork_requests = 0;
+
+/* A shortcut for terminating the application */
+static void quit(int ret) {
+ pa_assert(mainloop_api);
+ mainloop_api->quit(mainloop_api, ret);
+}
+
+/* Connection draining complete */
+static void context_drain_complete(pa_context*c, void *userdata) {
+ pa_context_disconnect(c);
+}
+
+/* Stream draining complete */
+static void stream_drain_complete(pa_stream*s, int success, void *userdata) {
+ pa_operation *o = NULL;
+
+ if (!success) {
+ pa_log(_("Failed to drain stream: %s"), pa_strerror(pa_context_errno(context)));
+ quit(1);
+ }
+
+ if (verbose)
+ pa_log(_("Playback stream drained."));
+
+ pa_stream_disconnect(stream);
+ pa_stream_unref(stream);
+ stream = NULL;
+
+ if (!(o = pa_context_drain(context, context_drain_complete, NULL)))
+ pa_context_disconnect(context);
+ else {
+ pa_operation_unref(o);
+ if (verbose)
+ pa_log(_("Draining connection to server."));
+ }
+}
+
+/* Start draining */
+static void start_drain(void) {
+
+ if (stream) {
+ pa_operation *o;
+
+ pa_stream_set_write_callback(stream, NULL, NULL);
+
+ if (!(o = pa_stream_drain(stream, stream_drain_complete, NULL))) {
+ pa_log(_("pa_stream_drain(): %s"), pa_strerror(pa_context_errno(context)));
+ quit(1);
+ return;
+ }
+
+ pa_operation_unref(o);
+ } else
+ quit(0);
+}
+
+/* This is called whenever new data may be written to the stream */
+static void stream_write_callback(pa_stream *s, size_t length, void *userdata) {
+ pa_assert(s);
+ pa_assert(length > 0);
+
+ if (raw) {
+ pa_assert(!sndfile);
+
+ if (stdio_event)
+ mainloop_api->io_enable(stdio_event, PA_IO_EVENT_INPUT);
+
+ } else {
+ sf_count_t bytes;
+ void *data;
+
+ pa_assert(sndfile);
+
+ for (;;) {
+ size_t data_length = length;
+
+ if (pa_stream_begin_write(s, &data, &data_length) < 0) {
+ pa_log(_("pa_stream_begin_write() failed: %s"), pa_strerror(pa_context_errno(context)));
+ quit(1);
+ return;
+ }
+
+ if (readf_function) {
+ size_t k = pa_frame_size(&sample_spec);
+
+ if ((bytes = readf_function(sndfile, data, (sf_count_t) (data_length/k))) > 0)
+ bytes *= (sf_count_t) k;
+
+ } else
+ bytes = sf_read_raw(sndfile, data, (sf_count_t) data_length);
+
+ if (bytes > 0)
+ pa_stream_write(s, data, (size_t) bytes, NULL, 0, PA_SEEK_RELATIVE);
+ else
+ pa_stream_cancel_write(s);
+
+ /* EOF? */
+ if (bytes < (sf_count_t) data_length) {
+ start_drain();
+ break;
+ }
+
+ /* Request fulfilled */
+ if ((size_t) bytes >= length)
+ break;
+
+ length -= bytes;
+ }
+ }
+}
+
+/* This is called whenever new data is available */
+static void stream_read_callback(pa_stream *s, size_t length, void *userdata) {
+
+ pa_assert(s);
+ pa_assert(length > 0);
+
+ if (raw) {
+ pa_assert(!sndfile);
+
+ if (stdio_event)
+ mainloop_api->io_enable(stdio_event, PA_IO_EVENT_OUTPUT);
+
+ while (pa_stream_readable_size(s) > 0) {
+ const void *data;
+
+ if (pa_stream_peek(s, &data, &length) < 0) {
+ pa_log(_("pa_stream_peek() failed: %s"), pa_strerror(pa_context_errno(context)));
+ quit(1);
+ return;
+ }
+
+ pa_assert(length > 0);
+
+ /* If there is a hole in the stream, we generate silence, except
+ * if it's a passthrough stream in which case we skip the hole. */
+ if (data || !(flags & PA_STREAM_PASSTHROUGH)) {
+ buffer = pa_xrealloc(buffer, buffer_index + buffer_length + length);
+ if (data)
+ memcpy((uint8_t *) buffer + buffer_index + buffer_length, data, length);
+ else
+ pa_silence_memory((uint8_t *) buffer + buffer_index + buffer_length, length, &sample_spec);
+
+ buffer_length += length;
+ }
+
+ pa_stream_drop(s);
+ }
+
+ } else {
+ pa_assert(sndfile);
+
+ while (pa_stream_readable_size(s) > 0) {
+ sf_count_t bytes;
+ const void *data;
+
+ if (pa_stream_peek(s, &data, &length) < 0) {
+ pa_log(_("pa_stream_peek() failed: %s"), pa_strerror(pa_context_errno(context)));
+ quit(1);
+ return;
+ }
+
+ pa_assert(length > 0);
+
+ if (!data && (flags & PA_STREAM_PASSTHROUGH)) {
+ pa_stream_drop(s);
+ continue;
+ }
+
+ if (!data && length > silence_buffer_length) {
+ silence_buffer = pa_xrealloc(silence_buffer, length);
+ pa_silence_memory((uint8_t *) silence_buffer + silence_buffer_length, length - silence_buffer_length, &sample_spec);
+ silence_buffer_length = length;
+ }
+
+ if (writef_function) {
+ size_t k = pa_frame_size(&sample_spec);
+
+ if ((bytes = writef_function(sndfile, data ? data : silence_buffer, (sf_count_t) (length/k))) > 0)
+ bytes *= (sf_count_t) k;
+
+ } else
+ bytes = sf_write_raw(sndfile, data ? data : silence_buffer, (sf_count_t) length);
+
+ if (bytes < (sf_count_t) length)
+ quit(1);
+
+ pa_stream_drop(s);
+ }
+ }
+}
+
+/* This routine is called whenever the stream state changes */
+static void stream_state_callback(pa_stream *s, void *userdata) {
+ pa_assert(s);
+
+ switch (pa_stream_get_state(s)) {
+ case PA_STREAM_CREATING:
+ case PA_STREAM_TERMINATED:
+ break;
+
+ case PA_STREAM_READY:
+
+ if (verbose) {
+ const pa_buffer_attr *a;
+ char cmt[PA_CHANNEL_MAP_SNPRINT_MAX], sst[PA_SAMPLE_SPEC_SNPRINT_MAX];
+
+ pa_log(_("Stream successfully created."));
+
+ if (!(a = pa_stream_get_buffer_attr(s)))
+ pa_log(_("pa_stream_get_buffer_attr() failed: %s"), pa_strerror(pa_context_errno(pa_stream_get_context(s))));
+ else {
+
+ if (mode == PLAYBACK)
+ pa_log(_("Buffer metrics: maxlength=%u, tlength=%u, prebuf=%u, minreq=%u"), a->maxlength, a->tlength, a->prebuf, a->minreq);
+ else {
+ pa_assert(mode == RECORD);
+ pa_log(_("Buffer metrics: maxlength=%u, fragsize=%u"), a->maxlength, a->fragsize);
+ }
+ }
+
+ pa_log(_("Using sample spec '%s', channel map '%s'."),
+ pa_sample_spec_snprint(sst, sizeof(sst), pa_stream_get_sample_spec(s)),
+ pa_channel_map_snprint(cmt, sizeof(cmt), pa_stream_get_channel_map(s)));
+
+ pa_log(_("Connected to device %s (index: %u, suspended: %s)."),
+ pa_stream_get_device_name(s),
+ pa_stream_get_device_index(s),
+ pa_yes_no(pa_stream_is_suspended(s)));
+ }
+
+ break;
+
+ case PA_STREAM_FAILED:
+ default:
+ pa_log(_("Stream error: %s"), pa_strerror(pa_context_errno(pa_stream_get_context(s))));
+ quit(1);
+ }
+}
+
+static void stream_suspended_callback(pa_stream *s, void *userdata) {
+ pa_assert(s);
+
+ if (verbose) {
+ if (pa_stream_is_suspended(s))
+ pa_log(_("Stream device suspended.%s"), CLEAR_LINE);
+ else
+ pa_log(_("Stream device resumed.%s"), CLEAR_LINE);
+ }
+}
+
+static void stream_underflow_callback(pa_stream *s, void *userdata) {
+ pa_assert(s);
+
+ if (verbose)
+ pa_log(_("Stream underrun.%s"), CLEAR_LINE);
+}
+
+static void stream_overflow_callback(pa_stream *s, void *userdata) {
+ pa_assert(s);
+
+ if (verbose)
+ pa_log(_("Stream overrun.%s"), CLEAR_LINE);
+}
+
+static void stream_started_callback(pa_stream *s, void *userdata) {
+ pa_assert(s);
+
+ if (verbose)
+ pa_log(_("Stream started.%s"), CLEAR_LINE);
+}
+
+static void stream_moved_callback(pa_stream *s, void *userdata) {
+ pa_assert(s);
+
+ if (verbose)
+ pa_log(_("Stream moved to device %s (%u, %ssuspended).%s"), pa_stream_get_device_name(s), pa_stream_get_device_index(s), pa_stream_is_suspended(s) ? "" : _("not "), CLEAR_LINE);
+}
+
+static void stream_buffer_attr_callback(pa_stream *s, void *userdata) {
+ pa_assert(s);
+
+ if (verbose)
+ pa_log(_("Stream buffer attributes changed.%s"), CLEAR_LINE);
+}
+
+static void stream_event_callback(pa_stream *s, const char *name, pa_proplist *pl, void *userdata) {
+ char *t;
+
+ pa_assert(s);
+ pa_assert(name);
+ pa_assert(pl);
+
+ t = pa_proplist_to_string_sep(pl, ", ");
+ pa_log("Got event '%s', properties '%s'", name, t);
+
+ if (pa_streq(name, PA_STREAM_EVENT_REQUEST_CORK)) {
+ if (cork_requests == 0) {
+ pa_log(_("Cork request stack is empty: corking stream"));
+ pa_operation_unref(pa_stream_cork(s, 1, NULL, NULL));
+ }
+ cork_requests++;
+ } else if (pa_streq(name, PA_STREAM_EVENT_REQUEST_UNCORK)) {
+ if (cork_requests == 1) {
+ pa_log(_("Cork request stack is empty: uncorking stream"));
+ pa_operation_unref(pa_stream_cork(s, 0, NULL, NULL));
+ }
+ if (cork_requests == 0)
+ pa_log(_("Warning: Received more uncork requests than cork requests."));
+ else
+ cork_requests--;
+ }
+
+ pa_xfree(t);
+}
+
+/* This is called whenever the context status changes */
+static void context_state_callback(pa_context *c, void *userdata) {
+ pa_assert(c);
+
+ switch (pa_context_get_state(c)) {
+ case PA_CONTEXT_CONNECTING:
+ case PA_CONTEXT_AUTHORIZING:
+ case PA_CONTEXT_SETTING_NAME:
+ break;
+
+ case PA_CONTEXT_READY: {
+ pa_buffer_attr buffer_attr;
+
+ pa_assert(c);
+ pa_assert(!stream);
+
+ if (verbose)
+ pa_log(_("Connection established.%s"), CLEAR_LINE);
+
+ if (!(stream = pa_stream_new_with_proplist(c, NULL, &sample_spec, &channel_map, proplist))) {
+ pa_log(_("pa_stream_new() failed: %s"), pa_strerror(pa_context_errno(c)));
+ goto fail;
+ }
+
+ pa_stream_set_state_callback(stream, stream_state_callback, NULL);
+ pa_stream_set_write_callback(stream, stream_write_callback, NULL);
+ pa_stream_set_read_callback(stream, stream_read_callback, NULL);
+ pa_stream_set_suspended_callback(stream, stream_suspended_callback, NULL);
+ pa_stream_set_moved_callback(stream, stream_moved_callback, NULL);
+ pa_stream_set_underflow_callback(stream, stream_underflow_callback, NULL);
+ pa_stream_set_overflow_callback(stream, stream_overflow_callback, NULL);
+ pa_stream_set_started_callback(stream, stream_started_callback, NULL);
+ pa_stream_set_event_callback(stream, stream_event_callback, NULL);
+ pa_stream_set_buffer_attr_callback(stream, stream_buffer_attr_callback, NULL);
+
+ pa_zero(buffer_attr);
+ buffer_attr.maxlength = (uint32_t) -1;
+ buffer_attr.prebuf = (uint32_t) -1;
+
+ if (latency_msec > 0) {
+ buffer_attr.fragsize = buffer_attr.tlength = pa_usec_to_bytes(latency_msec * PA_USEC_PER_MSEC, &sample_spec);
+ flags |= PA_STREAM_ADJUST_LATENCY;
+ } else if (latency > 0) {
+ buffer_attr.fragsize = buffer_attr.tlength = (uint32_t) latency;
+ flags |= PA_STREAM_ADJUST_LATENCY;
+ } else
+ buffer_attr.fragsize = buffer_attr.tlength = (uint32_t) -1;
+
+ if (process_time_msec > 0) {
+ buffer_attr.minreq = pa_usec_to_bytes(process_time_msec * PA_USEC_PER_MSEC, &sample_spec);
+ } else if (process_time > 0)
+ buffer_attr.minreq = (uint32_t) process_time;
+ else
+ buffer_attr.minreq = (uint32_t) -1;
+
+ if (mode == PLAYBACK) {
+ pa_cvolume cv;
+ if (pa_stream_connect_playback(stream, device, &buffer_attr, flags, volume_is_set ? pa_cvolume_set(&cv, sample_spec.channels, volume) : NULL, NULL) < 0) {
+ pa_log(_("pa_stream_connect_playback() failed: %s"), pa_strerror(pa_context_errno(c)));
+ goto fail;
+ }
+
+ } else {
+ if (monitor_stream != PA_INVALID_INDEX && (pa_stream_set_monitor_stream(stream, monitor_stream) < 0)) {
+ pa_log(_("Failed to set monitor stream: %s"), pa_strerror(pa_context_errno(c)));
+ goto fail;
+ }
+ if (pa_stream_connect_record(stream, device, &buffer_attr, flags) < 0) {
+ pa_log(_("pa_stream_connect_record() failed: %s"), pa_strerror(pa_context_errno(c)));
+ goto fail;
+ }
+ }
+ break;
+ }
+
+ case PA_CONTEXT_TERMINATED:
+ quit(0);
+ break;
+
+ case PA_CONTEXT_FAILED:
+ default:
+ pa_log(_("Connection failure: %s"), pa_strerror(pa_context_errno(c)));
+ goto fail;
+ }
+
+ return;
+
+fail:
+ quit(1);
+
+}
+
+/* New data on STDIN **/
+static void stdin_callback(pa_mainloop_api*a, pa_io_event *e, int fd, pa_io_event_flags_t f, void *userdata) {
+ uint8_t *buf = NULL;
+ size_t writable, towrite, r;
+
+ pa_assert(a == mainloop_api);
+ pa_assert(e);
+ pa_assert(stdio_event == e);
+
+ /* Stream not ready? */
+ if (!stream || pa_stream_get_state(stream) != PA_STREAM_READY ||
+ !(writable = pa_stream_writable_size(stream))) {
+
+ mainloop_api->io_enable(stdio_event, PA_IO_EVENT_NULL);
+ return;
+ }
+
+ if (pa_stream_begin_write(stream, (void **)&buf, &writable) < 0) {
+ pa_log(_("pa_stream_begin_write() failed: %s"), pa_strerror(pa_context_errno(context)));
+ quit(1);
+ return;
+ }
+
+ /* Partial frame cached from a previous write iteration? */
+ if (partialframe_len) {
+ pa_assert(partialframe_len < pa_frame_size(&sample_spec));
+ memcpy(buf, partialframe_buf, partialframe_len);
+ }
+
+ if ((r = pa_read(fd, buf + partialframe_len, writable - partialframe_len, userdata)) <= 0) {
+ if (r == 0) {
+ if (verbose)
+ pa_log(_("Got EOF."));
+
+ start_drain();
+
+ } else {
+ pa_log(_("read() failed: %s"), strerror(errno));
+ quit(1);
+ }
+
+ mainloop_api->io_free(stdio_event);
+ stdio_event = NULL;
+ return;
+ }
+ r += partialframe_len;
+
+ /* Cache any trailing partial frames for the next write */
+ towrite = pa_frame_align(r, &sample_spec);
+ partialframe_len = r - towrite;
+
+ if (partialframe_len)
+ memcpy(partialframe_buf, buf + towrite, partialframe_len);
+
+ if (towrite) {
+ if (pa_stream_write(stream, buf, towrite, NULL, 0, PA_SEEK_RELATIVE) < 0) {
+ pa_log(_("pa_stream_write() failed: %s"), pa_strerror(pa_context_errno(context)));
+ quit(1);
+ return;
+ }
+ } else
+ pa_stream_cancel_write(stream);
+}
+
+/* Some data may be written to STDOUT */
+static void stdout_callback(pa_mainloop_api*a, pa_io_event *e, int fd, pa_io_event_flags_t f, void *userdata) {
+ ssize_t r;
+
+ pa_assert(a == mainloop_api);
+ pa_assert(e);
+ pa_assert(stdio_event == e);
+
+ if (!buffer) {
+ mainloop_api->io_enable(stdio_event, PA_IO_EVENT_NULL);
+ return;
+ }
+
+ pa_assert(buffer_length);
+
+ if ((r = pa_write(fd, (uint8_t*) buffer+buffer_index, buffer_length, userdata)) <= 0) {
+ pa_log(_("write() failed: %s"), strerror(errno));
+ quit(1);
+
+ mainloop_api->io_free(stdio_event);
+ stdio_event = NULL;
+ return;
+ }
+
+ buffer_length -= (uint32_t) r;
+ buffer_index += (uint32_t) r;
+
+ if (!buffer_length) {
+ pa_xfree(buffer);
+ buffer = NULL;
+ buffer_length = buffer_index = 0;
+ }
+}
+
+/* UNIX signal to quit received */
+static void exit_signal_callback(pa_mainloop_api*m, pa_signal_event *e, int sig, void *userdata) {
+ if (verbose)
+ pa_log(_("Got signal, exiting."));
+ quit(0);
+}
+
+/* Show the current latency */
+static void stream_update_timing_callback(pa_stream *s, int success, void *userdata) {
+ pa_usec_t l, usec;
+ int negative = 0;
+
+ pa_assert(s);
+
+ if (!success ||
+ pa_stream_get_time(s, &usec) < 0 ||
+ pa_stream_get_latency(s, &l, &negative) < 0) {
+ pa_log(_("Failed to get latency: %s"), pa_strerror(pa_context_errno(context)));
+ quit(1);
+ return;
+ }
+
+ fprintf(stderr, _("Time: %0.3f sec; Latency: %0.0f usec."),
+ (float) usec / 1000000,
+ (float) l * (negative?-1.0f:1.0f));
+ fprintf(stderr, " \r");
+}
+
+#ifdef SIGUSR1
+/* Someone requested that the latency is shown */
+static void sigusr1_signal_callback(pa_mainloop_api*m, pa_signal_event *e, int sig, void *userdata) {
+
+ if (!stream)
+ return;
+
+ pa_operation_unref(pa_stream_update_timing_info(stream, stream_update_timing_callback, NULL));
+}
+#endif
+
+static void time_event_callback(pa_mainloop_api *m, pa_time_event *e, const struct timeval *t, void *userdata) {
+ if (stream && pa_stream_get_state(stream) == PA_STREAM_READY) {
+ pa_operation *o;
+ if (!(o = pa_stream_update_timing_info(stream, stream_update_timing_callback, NULL)))
+ pa_log(_("pa_stream_update_timing_info() failed: %s"), pa_strerror(pa_context_errno(context)));
+ else
+ pa_operation_unref(o);
+ }
+
+ pa_context_rttime_restart(context, e, pa_rtclock_now() + TIME_EVENT_USEC);
+}
+
+static void help(const char *argv0) {
+
+ printf(_("%s [options]\n"
+ "%s\n\n"
+ " -h, --help Show this help\n"
+ " --version Show version\n\n"
+ " -r, --record Create a connection for recording\n"
+ " -p, --playback Create a connection for playback\n\n"
+ " -v, --verbose Enable verbose operations\n\n"
+ " -s, --server=SERVER The name of the server to connect to\n"
+ " -d, --device=DEVICE The name of the sink/source to connect to\n"
+ " -n, --client-name=NAME How to call this client on the server\n"
+ " --stream-name=NAME How to call this stream on the server\n"
+ " --volume=VOLUME Specify the initial (linear) volume in range 0...65536\n"
+ " --rate=SAMPLERATE The sample rate in Hz (defaults to 44100)\n"
+ " --format=SAMPLEFORMAT The sample format, see\n"
+ " https://www.freedesktop.org/wiki/Software/PulseAudio/Documentation/User/SupportedAudioFormats/\n"
+ " for possible values (defaults to s16ne)\n"
+ " --channels=CHANNELS The number of channels, 1 for mono, 2 for stereo\n"
+ " (defaults to 2)\n"
+ " --channel-map=CHANNELMAP Channel map to use instead of the default\n"
+ " --fix-format Take the sample format from the sink/source the stream is\n"
+ " being connected to.\n"
+ " --fix-rate Take the sampling rate from the sink/source the stream is\n"
+ " being connected to.\n"
+ " --fix-channels Take the number of channels and the channel map\n"
+ " from the sink/source the stream is being connected to.\n"
+ " --no-remix Don't upmix or downmix channels.\n"
+ " --no-remap Map channels by index instead of name.\n"
+ " --latency=BYTES Request the specified latency in bytes.\n"
+ " --process-time=BYTES Request the specified process time per request in bytes.\n"
+ " --latency-msec=MSEC Request the specified latency in msec.\n"
+ " --process-time-msec=MSEC Request the specified process time per request in msec.\n"
+ " --property=PROPERTY=VALUE Set the specified property to the specified value.\n"
+ " --raw Record/play raw PCM data.\n"
+ " --passthrough Passthrough data.\n"
+ " --file-format[=FFORMAT] Record/play formatted PCM data.\n"
+ " --list-file-formats List available file formats.\n"
+ " --monitor-stream=INDEX Record from the sink input with index INDEX.\n")
+ , argv0, purpose);
+}
+
+enum {
+ ARG_VERSION = 256,
+ ARG_STREAM_NAME,
+ ARG_VOLUME,
+ ARG_SAMPLERATE,
+ ARG_SAMPLEFORMAT,
+ ARG_CHANNELS,
+ ARG_CHANNELMAP,
+ ARG_FIX_FORMAT,
+ ARG_FIX_RATE,
+ ARG_FIX_CHANNELS,
+ ARG_NO_REMAP,
+ ARG_NO_REMIX,
+ ARG_LATENCY,
+ ARG_PROCESS_TIME,
+ ARG_RAW,
+ ARG_PASSTHROUGH,
+ ARG_PROPERTY,
+ ARG_FILE_FORMAT,
+ ARG_LIST_FILE_FORMATS,
+ ARG_LATENCY_MSEC,
+ ARG_PROCESS_TIME_MSEC,
+ ARG_MONITOR_STREAM,
+};
+
+int main(int argc, char *argv[]) {
+ pa_mainloop* m = NULL;
+ int ret = 1, c;
+ char *bn, *server = NULL;
+ pa_time_event *time_event = NULL;
+ const char *filename = NULL;
+ /* type for pa_read/_write. passed as userdata to the callbacks */
+ unsigned long type = 0;
+
+ static const struct option long_options[] = {
+ {"record", 0, NULL, 'r'},
+ {"playback", 0, NULL, 'p'},
+ {"device", 1, NULL, 'd'},
+ {"server", 1, NULL, 's'},
+ {"client-name", 1, NULL, 'n'},
+ {"stream-name", 1, NULL, ARG_STREAM_NAME},
+ {"version", 0, NULL, ARG_VERSION},
+ {"help", 0, NULL, 'h'},
+ {"verbose", 0, NULL, 'v'},
+ {"volume", 1, NULL, ARG_VOLUME},
+ {"rate", 1, NULL, ARG_SAMPLERATE},
+ {"format", 1, NULL, ARG_SAMPLEFORMAT},
+ {"channels", 1, NULL, ARG_CHANNELS},
+ {"channel-map", 1, NULL, ARG_CHANNELMAP},
+ {"fix-format", 0, NULL, ARG_FIX_FORMAT},
+ {"fix-rate", 0, NULL, ARG_FIX_RATE},
+ {"fix-channels", 0, NULL, ARG_FIX_CHANNELS},
+ {"no-remap", 0, NULL, ARG_NO_REMAP},
+ {"no-remix", 0, NULL, ARG_NO_REMIX},
+ {"latency", 1, NULL, ARG_LATENCY},
+ {"process-time", 1, NULL, ARG_PROCESS_TIME},
+ {"property", 1, NULL, ARG_PROPERTY},
+ {"raw", 0, NULL, ARG_RAW},
+ {"passthrough", 0, NULL, ARG_PASSTHROUGH},
+ {"file-format", 2, NULL, ARG_FILE_FORMAT},
+ {"list-file-formats", 0, NULL, ARG_LIST_FILE_FORMATS},
+ {"latency-msec", 1, NULL, ARG_LATENCY_MSEC},
+ {"process-time-msec", 1, NULL, ARG_PROCESS_TIME_MSEC},
+ {"monitor-stream", 1, NULL, ARG_MONITOR_STREAM},
+ {NULL, 0, NULL, 0}
+ };
+
+ setlocale(LC_ALL, "");
+#ifdef ENABLE_NLS
+ bindtextdomain(GETTEXT_PACKAGE, PULSE_LOCALEDIR);
+#endif
+
+ bn = pa_path_get_filename(argv[0]);
+
+ if (strstr(bn, "play")) {
+ mode = PLAYBACK;
+ raw = false;
+ purpose = _("Play back encoded audio files on a PulseAudio sound server.");
+ } else if (strstr(bn, "record")) {
+ mode = RECORD;
+ raw = false;
+ purpose = _("Capture audio data from a PulseAudio sound server and write it to a file.");
+ } else if (strstr(bn, "rec") || strstr(bn, "mon")) {
+ mode = RECORD;
+ raw = true;
+ purpose = _("Capture audio data from a PulseAudio sound server and write it to STDOUT or the specified file.");
+ } else { /* pacat */
+ mode = PLAYBACK;
+ raw = true;
+ purpose = _("Play back audio data from STDIN or the specified file on a PulseAudio sound server.");
+ }
+
+ proplist = pa_proplist_new();
+
+ while ((c = getopt_long(argc, argv, "rpd:s:n:hv", long_options, NULL)) != -1) {
+
+ switch (c) {
+ case 'h':
+ help(bn);
+ ret = 0;
+ goto quit;
+
+ case ARG_VERSION:
+ printf(_("pacat %s\n"
+ "Compiled with libpulse %s\n"
+ "Linked with libpulse %s\n"),
+ PACKAGE_VERSION,
+ pa_get_headers_version(),
+ pa_get_library_version());
+ ret = 0;
+ goto quit;
+
+ case 'r':
+ mode = RECORD;
+ break;
+
+ case 'p':
+ mode = PLAYBACK;
+ break;
+
+ case 'd':
+ pa_xfree(device);
+ device = pa_xstrdup(optarg);
+ break;
+
+ case 's':
+ pa_xfree(server);
+ server = pa_xstrdup(optarg);
+ break;
+
+ case 'n': {
+ char *t;
+
+ if (!(t = pa_locale_to_utf8(optarg)) ||
+ pa_proplist_sets(proplist, PA_PROP_APPLICATION_NAME, t) < 0) {
+
+ pa_log(_("Invalid client name '%s'"), t ? t : optarg);
+ pa_xfree(t);
+ goto quit;
+ }
+
+ pa_xfree(t);
+ break;
+ }
+
+ case ARG_STREAM_NAME: {
+ char *t;
+
+ if (!(t = pa_locale_to_utf8(optarg)) ||
+ pa_proplist_sets(proplist, PA_PROP_MEDIA_NAME, t) < 0) {
+
+ pa_log(_("Invalid stream name '%s'"), t ? t : optarg);
+ pa_xfree(t);
+ goto quit;
+ }
+
+ pa_xfree(t);
+ break;
+ }
+
+ case 'v':
+ verbose = 1;
+ break;
+
+ case ARG_VOLUME: {
+ int v = atoi(optarg);
+ volume = v < 0 ? 0U : (pa_volume_t) v;
+ volume_is_set = true;
+ break;
+ }
+
+ case ARG_CHANNELS:
+ sample_spec.channels = (uint8_t) atoi(optarg);
+ sample_spec_set = true;
+ break;
+
+ case ARG_SAMPLEFORMAT:
+ sample_spec.format = pa_parse_sample_format(optarg);
+ sample_spec_set = true;
+ break;
+
+ case ARG_SAMPLERATE:
+ sample_spec.rate = (uint32_t) atoi(optarg);
+ sample_spec_set = true;
+ break;
+
+ case ARG_CHANNELMAP:
+ if (!pa_channel_map_parse(&channel_map, optarg)) {
+ pa_log(_("Invalid channel map '%s'"), optarg);
+ goto quit;
+ }
+
+ channel_map_set = true;
+ break;
+
+ case ARG_FIX_CHANNELS:
+ flags |= PA_STREAM_FIX_CHANNELS;
+ break;
+
+ case ARG_FIX_RATE:
+ flags |= PA_STREAM_FIX_RATE;
+ break;
+
+ case ARG_FIX_FORMAT:
+ flags |= PA_STREAM_FIX_FORMAT;
+ break;
+
+ case ARG_NO_REMIX:
+ flags |= PA_STREAM_NO_REMIX_CHANNELS;
+ break;
+
+ case ARG_NO_REMAP:
+ flags |= PA_STREAM_NO_REMAP_CHANNELS;
+ break;
+
+ case ARG_LATENCY:
+ if (((latency = (size_t) atoi(optarg))) <= 0) {
+ pa_log(_("Invalid latency specification '%s'"), optarg);
+ goto quit;
+ }
+ break;
+
+ case ARG_PROCESS_TIME:
+ if (((process_time = (size_t) atoi(optarg))) <= 0) {
+ pa_log(_("Invalid process time specification '%s'"), optarg);
+ goto quit;
+ }
+ break;
+
+ case ARG_LATENCY_MSEC:
+ if (((latency_msec = (int32_t) atoi(optarg))) <= 0) {
+ pa_log(_("Invalid latency specification '%s'"), optarg);
+ goto quit;
+ }
+ break;
+
+ case ARG_PROCESS_TIME_MSEC:
+ if (((process_time_msec = (int32_t) atoi(optarg))) <= 0) {
+ pa_log(_("Invalid process time specification '%s'"), optarg);
+ goto quit;
+ }
+ break;
+
+ case ARG_PROPERTY: {
+ char *t;
+
+ if (!(t = pa_locale_to_utf8(optarg)) ||
+ pa_proplist_setp(proplist, t) < 0) {
+
+ pa_xfree(t);
+ pa_log(_("Invalid property '%s'"), optarg);
+ goto quit;
+ }
+
+ pa_xfree(t);
+ break;
+ }
+
+ case ARG_RAW:
+ raw = true;
+ break;
+
+ case ARG_PASSTHROUGH:
+ flags |= PA_STREAM_PASSTHROUGH;
+ break;
+
+ case ARG_FILE_FORMAT:
+ if (optarg) {
+ if ((file_format = pa_sndfile_format_from_string(optarg)) < 0) {
+ pa_log(_("Unknown file format %s."), optarg);
+ goto quit;
+ }
+ }
+
+ raw = false;
+ break;
+
+ case ARG_LIST_FILE_FORMATS:
+ pa_sndfile_dump_formats();
+ ret = 0;
+ goto quit;
+
+ case ARG_MONITOR_STREAM:
+ if (pa_atou(optarg, &monitor_stream) < 0) {
+ pa_log(_("Failed to parse the argument for --monitor-stream"));
+ goto quit;
+ }
+ break;
+
+ default:
+ goto quit;
+ }
+ }
+
+ if (!pa_sample_spec_valid(&sample_spec)) {
+ pa_log(_("Invalid sample specification"));
+ goto quit;
+ }
+
+ if (optind+1 == argc) {
+ int fd;
+
+ filename = argv[optind];
+
+ if ((fd = pa_open_cloexec(argv[optind], mode == PLAYBACK ? O_RDONLY : O_WRONLY|O_TRUNC|O_CREAT, 0666)) < 0) {
+ pa_log(_("open(): %s"), strerror(errno));
+ goto quit;
+ }
+
+ if (dup2(fd, mode == PLAYBACK ? STDIN_FILENO : STDOUT_FILENO) < 0) {
+ pa_log(_("dup2(): %s"), strerror(errno));
+ goto quit;
+ }
+
+ pa_close(fd);
+
+ } else if (optind+1 <= argc) {
+ pa_log(_("Too many arguments."));
+ goto quit;
+ }
+
+ if (!raw) {
+ SF_INFO sfi;
+ pa_zero(sfi);
+
+ if (mode == RECORD) {
+ /* This might patch up the sample spec */
+ if (pa_sndfile_write_sample_spec(&sfi, &sample_spec) < 0) {
+ pa_log(_("Failed to generate sample specification for file."));
+ goto quit;
+ }
+
+ if (file_format <= 0) {
+ char *extension;
+ if (filename && (extension = strrchr(filename, '.')))
+ file_format = pa_sndfile_format_from_string(extension+1);
+ if (file_format <= 0)
+ file_format = SF_FORMAT_WAV;
+ /* Transparently upgrade classic .wav to wavex for multichannel audio */
+ if (file_format == SF_FORMAT_WAV &&
+ (sample_spec.channels > 2 ||
+ (channel_map_set &&
+ !(sample_spec.channels == 1 && channel_map.map[0] == PA_CHANNEL_POSITION_MONO) &&
+ !(sample_spec.channels == 2 && channel_map.map[0] == PA_CHANNEL_POSITION_LEFT
+ && channel_map.map[1] == PA_CHANNEL_POSITION_RIGHT))))
+ file_format = SF_FORMAT_WAVEX;
+ }
+
+ sfi.format |= file_format;
+ }
+
+ if (!(sndfile = sf_open_fd(mode == RECORD ? STDOUT_FILENO : STDIN_FILENO,
+ mode == RECORD ? SFM_WRITE : SFM_READ,
+ &sfi, 0))) {
+ pa_log(_("Failed to open audio file."));
+ goto quit;
+ }
+
+ if (mode == PLAYBACK) {
+ if (sample_spec_set)
+ pa_log(_("Warning: specified sample specification will be overwritten with specification from file."));
+
+ if (pa_sndfile_read_sample_spec(sndfile, &sample_spec) < 0) {
+ pa_log(_("Failed to determine sample specification from file."));
+ goto quit;
+ }
+ sample_spec_set = true;
+
+ if (!channel_map_set) {
+ /* Allow the user to overwrite the channel map on the command line */
+ if (pa_sndfile_read_channel_map(sndfile, &channel_map) < 0) {
+ if (sample_spec.channels > 2)
+ pa_log(_("Warning: Failed to determine channel map from file."));
+ } else
+ channel_map_set = true;
+ }
+ }
+ }
+
+ if (!channel_map_set)
+ pa_channel_map_init_extend(&channel_map, sample_spec.channels, PA_CHANNEL_MAP_DEFAULT);
+
+ if (!pa_channel_map_compatible(&channel_map, &sample_spec)) {
+ pa_log(_("Channel map doesn't match sample specification"));
+ goto quit;
+ }
+
+ if (!raw) {
+ pa_proplist *sfp;
+
+ if (mode == PLAYBACK)
+ readf_function = pa_sndfile_readf_function(&sample_spec);
+ else {
+ if (pa_sndfile_write_channel_map(sndfile, &channel_map) < 0)
+ pa_log(_("Warning: failed to write channel map to file."));
+
+ writef_function = pa_sndfile_writef_function(&sample_spec);
+ }
+
+ /* Fill in libsndfile prop list data */
+ sfp = pa_proplist_new();
+ pa_sndfile_init_proplist(sndfile, sfp);
+ pa_proplist_update(proplist, PA_UPDATE_MERGE, sfp);
+ pa_proplist_free(sfp);
+ }
+
+ if (verbose) {
+ char tss[PA_SAMPLE_SPEC_SNPRINT_MAX], tcm[PA_CHANNEL_MAP_SNPRINT_MAX];
+
+ pa_log(_("Opening a %s stream with sample specification '%s' and channel map '%s'."),
+ mode == RECORD ? _("recording") : _("playback"),
+ pa_sample_spec_snprint(tss, sizeof(tss), &sample_spec),
+ pa_channel_map_snprint(tcm, sizeof(tcm), &channel_map));
+ }
+
+ /* Fill in client name if none was set */
+ if (!pa_proplist_contains(proplist, PA_PROP_APPLICATION_NAME)) {
+ char *t;
+
+ if ((t = pa_locale_to_utf8(bn))) {
+ pa_proplist_sets(proplist, PA_PROP_APPLICATION_NAME, t);
+ pa_xfree(t);
+ }
+ }
+
+ /* Fill in media name if none was set */
+ if (!pa_proplist_contains(proplist, PA_PROP_MEDIA_NAME)) {
+ const char *t;
+
+ if ((t = filename) ||
+ (t = pa_proplist_gets(proplist, PA_PROP_APPLICATION_NAME)))
+ pa_proplist_sets(proplist, PA_PROP_MEDIA_NAME, t);
+
+ if (!pa_proplist_contains(proplist, PA_PROP_MEDIA_NAME)) {
+ pa_log(_("Failed to set media name."));
+ goto quit;
+ }
+ }
+
+ if (raw && mode == PLAYBACK)
+ partialframe_buf = pa_xmalloc(pa_frame_size(&sample_spec));
+
+ /* Set up a new main loop */
+ if (!(m = pa_mainloop_new())) {
+ pa_log(_("pa_mainloop_new() failed."));
+ goto quit;
+ }
+
+ mainloop_api = pa_mainloop_get_api(m);
+
+ pa_assert_se(pa_signal_init(mainloop_api) == 0);
+ pa_signal_new(SIGINT, exit_signal_callback, NULL);
+ pa_signal_new(SIGTERM, exit_signal_callback, NULL);
+#ifdef SIGUSR1
+ pa_signal_new(SIGUSR1, sigusr1_signal_callback, NULL);
+#endif
+ pa_disable_sigpipe();
+
+ if (raw) {
+#ifdef OS_IS_WIN32
+ /* need to turn on binary mode for stdio io. Windows, meh */
+ setmode(mode == PLAYBACK ? STDIN_FILENO : STDOUT_FILENO, O_BINARY);
+#endif
+ if (!(stdio_event = mainloop_api->io_new(mainloop_api,
+ mode == PLAYBACK ? STDIN_FILENO : STDOUT_FILENO,
+ mode == PLAYBACK ? PA_IO_EVENT_INPUT : PA_IO_EVENT_OUTPUT,
+ mode == PLAYBACK ? stdin_callback : stdout_callback, &type))) {
+ pa_log(_("io_new() failed."));
+ goto quit;
+ }
+ }
+
+ /* Create a new connection context */
+ if (!(context = pa_context_new_with_proplist(mainloop_api, NULL, proplist))) {
+ pa_log(_("pa_context_new() failed."));
+ goto quit;
+ }
+
+ pa_context_set_state_callback(context, context_state_callback, NULL);
+
+ /* Connect the context */
+ if (pa_context_connect(context, server, 0, NULL) < 0) {
+ pa_log(_("pa_context_connect() failed: %s"), pa_strerror(pa_context_errno(context)));
+ goto quit;
+ }
+
+ if (verbose) {
+ if (!(time_event = pa_context_rttime_new(context, pa_rtclock_now() + TIME_EVENT_USEC, time_event_callback, NULL))) {
+ pa_log(_("pa_context_rttime_new() failed."));
+ goto quit;
+ }
+ }
+
+ /* Run the main loop */
+ if (pa_mainloop_run(m, &ret) < 0) {
+ pa_log(_("pa_mainloop_run() failed."));
+ goto quit;
+ }
+
+quit:
+ if (stream)
+ pa_stream_unref(stream);
+
+ if (context)
+ pa_context_unref(context);
+
+ if (stdio_event) {
+ pa_assert(mainloop_api);
+ mainloop_api->io_free(stdio_event);
+ }
+
+ if (time_event) {
+ pa_assert(mainloop_api);
+ mainloop_api->time_free(time_event);
+ }
+
+ if (m) {
+ pa_signal_done();
+ pa_mainloop_free(m);
+ }
+
+ pa_xfree(silence_buffer);
+ pa_xfree(buffer);
+ pa_xfree(partialframe_buf);
+
+ pa_xfree(server);
+ pa_xfree(device);
+
+ if (sndfile)
+ sf_close(sndfile);
+
+ if (proplist)
+ pa_proplist_free(proplist);
+
+ return ret;
+}
diff --git a/src/utils/pacmd.c b/src/utils/pacmd.c
new file mode 100644
index 0000000..616573c
--- /dev/null
+++ b/src/utils/pacmd.c
@@ -0,0 +1,359 @@
+/***
+ This file is part of PulseAudio.
+
+ Copyright 2004-2006 Lennart Poettering
+
+ PulseAudio is free software; you can redistribute it and/or modify
+ it under the terms of the GNU Lesser General Public License as published
+ by the Free Software Foundation; either version 2.1 of the License,
+ or (at your option) any later version.
+
+ PulseAudio is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+***/
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <assert.h>
+#include <signal.h>
+#include <sys/socket.h>
+#include <unistd.h>
+#include <errno.h>
+#include <string.h>
+#include <sys/un.h>
+#include <getopt.h>
+#include <locale.h>
+
+#include <pulse/util.h>
+#include <pulse/xmalloc.h>
+
+#include <pulsecore/i18n.h>
+#include <pulsecore/poll.h>
+#include <pulsecore/macro.h>
+#include <pulsecore/core-util.h>
+#include <pulsecore/log.h>
+#include <pulsecore/pid.h>
+
+static void help(const char *argv0) {
+ printf("%s %s\n", argv0, "exit");
+ printf("%s %s\n", argv0, "help");
+ printf("%s %s\n", argv0, "list-(modules|sinks|sources|clients|cards|samples)");
+ printf("%s %s\n", argv0, "list-(sink-inputs|source-outputs)");
+ printf("%s %s\n", argv0, "stat");
+ printf("%s %s\n", argv0, "info");
+ printf("%s %s %s\n", argv0, "load-module", _("NAME [ARGS ...]"));
+ printf("%s %s %s\n", argv0, "unload-module", _("NAME|#N"));
+ printf("%s %s %s\n", argv0, "describe-module", _("NAME"));
+ printf("%s %s %s\n", argv0, "set-(sink|source)-volume", _("NAME|#N VOLUME"));
+ printf("%s %s %s\n", argv0, "set-(sink-input|source-output)-volume", _("#N VOLUME"));
+ printf("%s %s %s\n", argv0, "set-(sink|source)-mute", _("NAME|#N 1|0"));
+ printf("%s %s %s\n", argv0, "set-(sink-input|source-output)-mute", _("#N 1|0"));
+ printf("%s %s %s\n", argv0, "update-(sink|source)-proplist", _("NAME|#N KEY=VALUE"));
+ printf("%s %s %s\n", argv0, "update-(sink-input|source-output)-proplist", _("#N KEY=VALUE"));
+ printf("%s %s %s\n", argv0, "set-default-(sink|source)", _("NAME|#N"));
+ printf("%s %s %s\n", argv0, "kill-(client|sink-input|source-output)", _("#N"));
+ printf("%s %s %s\n", argv0, "play-sample", _("NAME SINK|#N"));
+ printf("%s %s %s\n", argv0, "remove-sample", _("NAME"));
+ printf("%s %s %s\n", argv0, "load-sample", _("NAME FILENAME"));
+ printf("%s %s %s\n", argv0, "load-sample-lazy", _("NAME FILENAME"));
+ printf("%s %s %s\n", argv0, "load-sample-dir-lazy", _("PATHNAME"));
+ printf("%s %s %s\n", argv0, "play-file", _("FILENAME SINK|#N"));
+ printf("%s %s\n", argv0, "dump");
+ printf("%s %s %s\n", argv0, "move-(sink-input|source-output)", _("#N SINK|SOURCE"));
+ printf("%s %s %s\n", argv0, "suspend-(sink|source)", _("NAME|#N 1|0"));
+ printf("%s %s %s\n", argv0, "suspend", _("1|0"));
+ printf("%s %s %s\n", argv0, "set-card-profile", _("CARD PROFILE"));
+ printf("%s %s %s\n", argv0, "set-(sink|source)-port", _("NAME|#N PORT"));
+ printf("%s %s %s\n", argv0, "set-port-latency-offset", _("CARD-NAME|CARD-#N PORT OFFSET"));
+ printf("%s %s %s\n", argv0, "set-log-target", _("TARGET"));
+ printf("%s %s %s\n", argv0, "set-log-level", _("NUMERIC-LEVEL"));
+ printf("%s %s %s\n", argv0, "set-log-meta", _("1|0"));
+ printf("%s %s %s\n", argv0, "set-log-time", _("1|0"));
+ printf("%s %s %s\n", argv0, "set-log-backtrace", _("FRAMES"));
+
+ printf(_("\n"
+ " -h, --help Show this help\n"
+ " --version Show version\n"
+ "When no command is given pacmd starts in the interactive mode.\n" ));
+}
+
+enum {
+ ARG_VERSION = 256
+};
+
+int main(int argc, char*argv[]) {
+ pid_t pid;
+ int fd = -1;
+ int ret = 1, i;
+ struct sockaddr_un sa;
+ char *ibuf = NULL;
+ char *obuf = NULL;
+ size_t buf_size, ibuf_size, ibuf_index, ibuf_length, obuf_size, obuf_index, obuf_length;
+ char *cli;
+ bool ibuf_eof, obuf_eof, ibuf_closed, obuf_closed;
+ struct pollfd pollfd[3];
+ struct pollfd *watch_socket, *watch_stdin, *watch_stdout;
+ int stdin_type = 0, stdout_type = 0, fd_type = 0;
+
+ char *bn = NULL;
+ int c;
+
+ static const struct option long_options[] = {
+ {"version", 0, NULL, ARG_VERSION},
+ {"help", 0, NULL, 'h'},
+ {NULL, 0, NULL, 0}
+ };
+
+ setlocale(LC_ALL, "");
+#ifdef ENABLE_NLS
+ bindtextdomain(GETTEXT_PACKAGE, PULSE_LOCALEDIR);
+#endif
+
+ bn = pa_path_get_filename(argv[0]);
+
+ while ((c = getopt_long(argc, argv, "h", long_options, NULL)) != -1) {
+ switch (c) {
+ case 'h' :
+ help(bn);
+ ret = 0;
+ goto quit;
+ case ARG_VERSION:
+ printf(_("pacmd %s\n"
+ "Compiled with libpulse %s\n"
+ "Linked with libpulse %s\n"),
+ PACKAGE_VERSION,
+ pa_get_headers_version(),
+ pa_get_library_version());
+ ret = 0;
+ goto quit;
+ default:
+ goto quit;
+ }
+ }
+
+ if (pa_pid_file_check_running(&pid, "pulseaudio") < 0) {
+ pa_log(_("No PulseAudio daemon running, or not running as session daemon."));
+ goto quit;
+ }
+
+ if ((fd = pa_socket_cloexec(PF_UNIX, SOCK_STREAM, 0)) < 0) {
+ pa_log(_("socket(PF_UNIX, SOCK_STREAM, 0): %s"), strerror(errno));
+ goto quit;
+ }
+
+ pa_zero(sa);
+ sa.sun_family = AF_UNIX;
+
+ if (!(cli = pa_runtime_path("cli")))
+ goto quit;
+
+ pa_strlcpy(sa.sun_path, cli, sizeof(sa.sun_path));
+ pa_xfree(cli);
+
+ for (i = 0; i < 5; i++) {
+ int r;
+
+ if ((r = connect(fd, (struct sockaddr*) &sa, sizeof(sa))) < 0 && (errno != ECONNREFUSED && errno != ENOENT)) {
+ pa_log(_("connect(): %s"), strerror(errno));
+ goto quit;
+ }
+
+ if (r >= 0)
+ break;
+
+ if (pa_pid_file_kill(SIGUSR2, NULL, "pulseaudio") < 0) {
+ pa_log(_("Failed to kill PulseAudio daemon."));
+ goto quit;
+ }
+
+ pa_msleep(300);
+ }
+
+ if (i >= 5) {
+ pa_log(_("Daemon not responding."));
+ goto quit;
+ }
+
+ buf_size = pa_pipe_buf(fd);
+ ibuf_size = PA_MIN(buf_size, pa_pipe_buf(STDIN_FILENO));
+ ibuf = pa_xmalloc(ibuf_size);
+ obuf_size = PA_MIN(buf_size, pa_pipe_buf(STDOUT_FILENO));
+ obuf = pa_xmalloc(obuf_size);
+ ibuf_index = ibuf_length = obuf_index = obuf_length = 0;
+ ibuf_eof = obuf_eof = ibuf_closed = obuf_closed = false;
+
+ if (argc > 1) {
+ for (i = 1; i < argc; i++) {
+ size_t k;
+
+ k = PA_MIN(ibuf_size - ibuf_length, strlen(argv[i]));
+ memcpy(ibuf + ibuf_length, argv[i], k);
+ ibuf_length += k;
+
+ if (ibuf_length < ibuf_size) {
+ ibuf[ibuf_length] = i < argc-1 ? ' ' : '\n';
+ ibuf_length++;
+ }
+ }
+
+ ibuf_eof = true;
+ }
+
+ if (!ibuf_eof && isatty(STDIN_FILENO)) {
+ /* send hello to enable interactive mode (welcome message, prompt) */
+ if (pa_write(fd, "hello\n", 6, &fd_type) < 0) {
+ pa_log(_("write(): %s"), strerror(errno));
+ goto quit;
+ }
+ }
+
+ for (;;) {
+ struct pollfd *p;
+
+ if (ibuf_eof &&
+ obuf_eof &&
+ ibuf_length <= 0 &&
+ obuf_length <= 0)
+ break;
+
+ if (ibuf_length <= 0 && ibuf_eof && !ibuf_closed) {
+ shutdown(fd, SHUT_WR);
+ ibuf_closed = true;
+ }
+
+ if (obuf_length <= 0 && obuf_eof && !obuf_closed) {
+ shutdown(fd, SHUT_RD);
+ obuf_closed = true;
+ }
+
+ pa_zero(pollfd);
+
+ p = pollfd;
+
+ if (ibuf_length > 0 || (!obuf_eof && obuf_length <= 0)) {
+ watch_socket = p++;
+ watch_socket->fd = fd;
+ watch_socket->events =
+ (ibuf_length > 0 ? POLLOUT : 0) |
+ (!obuf_eof && obuf_length <= 0 ? POLLIN : 0);
+ } else
+ watch_socket = NULL;
+
+ if (!ibuf_eof && ibuf_length <= 0) {
+ watch_stdin = p++;
+ watch_stdin->fd = STDIN_FILENO;
+ watch_stdin->events = POLLIN;
+ } else
+ watch_stdin = NULL;
+
+ if (obuf_length > 0) {
+ watch_stdout = p++;
+ watch_stdout->fd = STDOUT_FILENO;
+ watch_stdout->events = POLLOUT;
+ } else
+ watch_stdout = NULL;
+
+ if (pa_poll(pollfd, p-pollfd, -1) < 0) {
+
+ if (errno == EINTR)
+ continue;
+
+ pa_log(_("poll(): %s"), strerror(errno));
+ goto quit;
+ }
+
+ if (watch_stdin) {
+ if (watch_stdin->revents & POLLIN) {
+ ssize_t r;
+ pa_assert(ibuf_length <= 0);
+
+ if ((r = pa_read(STDIN_FILENO, ibuf, ibuf_size, &stdin_type)) <= 0) {
+ if (r < 0) {
+ pa_log(_("read(): %s"), strerror(errno));
+ goto quit;
+ }
+
+ ibuf_eof = true;
+ } else {
+ ibuf_length = (size_t) r;
+ ibuf_index = 0;
+ }
+ } else if (watch_stdin->revents & POLLHUP)
+ ibuf_eof = true;
+ }
+
+ if (watch_socket) {
+ if (watch_socket->revents & POLLIN) {
+ ssize_t r;
+ pa_assert(obuf_length <= 0);
+
+ if ((r = pa_read(fd, obuf, obuf_size, &fd_type)) <= 0) {
+ if (r < 0) {
+ pa_log(_("read(): %s"), strerror(errno));
+ goto quit;
+ }
+
+ obuf_eof = true;
+ } else {
+ obuf_length = (size_t) r;
+ obuf_index = 0;
+ }
+ } else if (watch_socket->revents & POLLHUP)
+ obuf_eof = true;
+ }
+
+ if (watch_stdout) {
+ if (watch_stdout->revents & POLLHUP) {
+ obuf_eof = true;
+ obuf_length = 0;
+ } else if (watch_stdout->revents & POLLOUT) {
+ ssize_t r;
+ pa_assert(obuf_length > 0);
+
+ if ((r = pa_write(STDOUT_FILENO, obuf + obuf_index, obuf_length, &stdout_type)) < 0) {
+ pa_log(_("write(): %s"), strerror(errno));
+ goto quit;
+ }
+
+ obuf_length -= (size_t) r;
+ obuf_index += obuf_index;
+ }
+ }
+
+ if (watch_socket) {
+ if (watch_socket->revents & POLLHUP) {
+ ibuf_eof = true;
+ ibuf_length = 0;
+ } else if (watch_socket->revents & POLLOUT) {
+ ssize_t r;
+ pa_assert(ibuf_length > 0);
+
+ if ((r = pa_write(fd, ibuf + ibuf_index, ibuf_length, &fd_type)) < 0) {
+ pa_log(_("write(): %s"), strerror(errno));
+ goto quit;
+ }
+
+ ibuf_length -= (size_t) r;
+ ibuf_index += obuf_index;
+ }
+ }
+ }
+
+ ret = 0;
+
+quit:
+ if (fd >= 0)
+ pa_close(fd);
+
+ pa_xfree(obuf);
+ pa_xfree(ibuf);
+
+ return ret;
+}
diff --git a/src/utils/pactl.c b/src/utils/pactl.c
new file mode 100644
index 0000000..9af1fc5
--- /dev/null
+++ b/src/utils/pactl.c
@@ -0,0 +1,2165 @@
+/***
+ This file is part of PulseAudio.
+
+ Copyright 2004-2006 Lennart Poettering
+
+ PulseAudio is free software; you can redistribute it and/or modify
+ it under the terms of the GNU Lesser General Public License as published
+ by the Free Software Foundation; either version 2.1 of the License,
+ or (at your option) any later version.
+
+ PulseAudio is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+***/
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <signal.h>
+#include <string.h>
+#include <errno.h>
+#include <unistd.h>
+#include <assert.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <getopt.h>
+#include <locale.h>
+#include <ctype.h>
+
+#include <sndfile.h>
+
+#include <pulse/pulseaudio.h>
+#include <pulse/ext-device-restore.h>
+
+#include <pulsecore/i18n.h>
+#include <pulsecore/macro.h>
+#include <pulsecore/core-util.h>
+#include <pulsecore/log.h>
+#include <pulsecore/sndfile-util.h>
+
+static pa_context *context = NULL;
+static pa_mainloop_api *mainloop_api = NULL;
+
+static char
+ *list_type = NULL,
+ *sample_name = NULL,
+ *sink_name = NULL,
+ *source_name = NULL,
+ *module_name = NULL,
+ *module_args = NULL,
+ *card_name = NULL,
+ *profile_name = NULL,
+ *port_name = NULL,
+ *formats = NULL;
+
+static uint32_t
+ sink_input_idx = PA_INVALID_INDEX,
+ source_output_idx = PA_INVALID_INDEX,
+ sink_idx = PA_INVALID_INDEX;
+
+static bool short_list_format = false;
+static uint32_t module_index;
+static int32_t latency_offset;
+static bool suspend;
+static pa_cvolume volume;
+static enum volume_flags {
+ VOL_UINT = 0,
+ VOL_PERCENT = 1,
+ VOL_LINEAR = 2,
+ VOL_DECIBEL = 3,
+ VOL_ABSOLUTE = 0 << 4,
+ VOL_RELATIVE = 1 << 4,
+} volume_flags;
+
+static enum mute_flags {
+ INVALID_MUTE = -1,
+ UNMUTE = 0,
+ MUTE = 1,
+ TOGGLE_MUTE = 2
+} mute = INVALID_MUTE;
+
+static pa_proplist *proplist = NULL;
+
+static SNDFILE *sndfile = NULL;
+static pa_stream *sample_stream = NULL;
+static pa_sample_spec sample_spec;
+static pa_channel_map channel_map;
+static size_t sample_length = 0;
+
+/* This variable tracks the number of ongoing asynchronous operations. When a
+ * new operation begins, this is incremented simply with actions++, and when
+ * an operation finishes, this is decremented with the complete_action()
+ * function, which shuts down the program if actions reaches zero. */
+static int actions = 0;
+
+static bool nl = false;
+
+static enum {
+ NONE,
+ EXIT,
+ STAT,
+ INFO,
+ UPLOAD_SAMPLE,
+ PLAY_SAMPLE,
+ REMOVE_SAMPLE,
+ LIST,
+ MOVE_SINK_INPUT,
+ MOVE_SOURCE_OUTPUT,
+ LOAD_MODULE,
+ UNLOAD_MODULE,
+ SUSPEND_SINK,
+ SUSPEND_SOURCE,
+ SET_CARD_PROFILE,
+ SET_SINK_PORT,
+ SET_DEFAULT_SINK,
+ SET_SOURCE_PORT,
+ SET_DEFAULT_SOURCE,
+ SET_SINK_VOLUME,
+ SET_SOURCE_VOLUME,
+ SET_SINK_INPUT_VOLUME,
+ SET_SOURCE_OUTPUT_VOLUME,
+ SET_SINK_MUTE,
+ SET_SOURCE_MUTE,
+ SET_SINK_INPUT_MUTE,
+ SET_SOURCE_OUTPUT_MUTE,
+ SET_SINK_FORMATS,
+ SET_PORT_LATENCY_OFFSET,
+ SUBSCRIBE
+} action = NONE;
+
+static void quit(int ret) {
+ pa_assert(mainloop_api);
+ mainloop_api->quit(mainloop_api, ret);
+}
+
+static void context_drain_complete(pa_context *c, void *userdata) {
+ pa_context_disconnect(c);
+}
+
+static void drain(void) {
+ pa_operation *o;
+
+ if (!(o = pa_context_drain(context, context_drain_complete, NULL)))
+ pa_context_disconnect(context);
+ else
+ pa_operation_unref(o);
+}
+
+static void complete_action(void) {
+ pa_assert(actions > 0);
+
+ if (!(--actions))
+ drain();
+}
+
+static void stat_callback(pa_context *c, const pa_stat_info *i, void *userdata) {
+ char s[PA_BYTES_SNPRINT_MAX];
+ if (!i) {
+ pa_log(_("Failed to get statistics: %s"), pa_strerror(pa_context_errno(c)));
+ quit(1);
+ return;
+ }
+
+ pa_bytes_snprint(s, sizeof(s), i->memblock_total_size);
+ printf(ngettext("Currently in use: %u block containing %s bytes total.\n",
+ "Currently in use: %u blocks containing %s bytes total.\n",
+ i->memblock_total),
+ i->memblock_total, s);
+
+ pa_bytes_snprint(s, sizeof(s), i->memblock_allocated_size);
+ printf(ngettext("Allocated during whole lifetime: %u block containing %s bytes total.\n",
+ "Allocated during whole lifetime: %u blocks containing %s bytes total.\n",
+ i->memblock_allocated),
+ i->memblock_allocated, s);
+
+ pa_bytes_snprint(s, sizeof(s), i->scache_size);
+ printf(_("Sample cache size: %s\n"), s);
+
+ complete_action();
+}
+
+static void get_server_info_callback(pa_context *c, const pa_server_info *i, void *useerdata) {
+ char ss[PA_SAMPLE_SPEC_SNPRINT_MAX], cm[PA_CHANNEL_MAP_SNPRINT_MAX];
+
+ if (!i) {
+ pa_log(_("Failed to get server information: %s"), pa_strerror(pa_context_errno(c)));
+ quit(1);
+ return;
+ }
+
+ printf(_("Server String: %s\n"
+ "Library Protocol Version: %u\n"
+ "Server Protocol Version: %u\n"
+ "Is Local: %s\n"
+ "Client Index: %u\n"
+ "Tile Size: %zu\n"),
+ pa_context_get_server(c),
+ pa_context_get_protocol_version(c),
+ pa_context_get_server_protocol_version(c),
+ pa_yes_no_localised(pa_context_is_local(c)),
+ pa_context_get_index(c),
+ pa_context_get_tile_size(c, NULL));
+
+ pa_sample_spec_snprint(ss, sizeof(ss), &i->sample_spec);
+ pa_channel_map_snprint(cm, sizeof(cm), &i->channel_map);
+
+ printf(_("User Name: %s\n"
+ "Host Name: %s\n"
+ "Server Name: %s\n"
+ "Server Version: %s\n"
+ "Default Sample Specification: %s\n"
+ "Default Channel Map: %s\n"
+ "Default Sink: %s\n"
+ "Default Source: %s\n"
+ "Cookie: %04x:%04x\n"),
+ i->user_name,
+ i->host_name,
+ i->server_name,
+ i->server_version,
+ ss,
+ cm,
+ i->default_sink_name,
+ i->default_source_name,
+ i->cookie >> 16,
+ i->cookie & 0xFFFFU);
+
+ complete_action();
+}
+
+static const char* get_available_str(int available) {
+ switch (available) {
+ case PA_PORT_AVAILABLE_UNKNOWN: return _("availability unknown");
+ case PA_PORT_AVAILABLE_YES: return _("available");
+ case PA_PORT_AVAILABLE_NO: return _("not available");
+ }
+
+ pa_assert_not_reached();
+}
+
+static const char* get_device_port_type(unsigned int type) {
+ static char buf[32];
+ switch (type) {
+ case PA_DEVICE_PORT_TYPE_UNKNOWN: return _("Unknown");
+ case PA_DEVICE_PORT_TYPE_AUX: return _("Aux");
+ case PA_DEVICE_PORT_TYPE_SPEAKER: return _("Speaker");
+ case PA_DEVICE_PORT_TYPE_HEADPHONES: return _("Headphones");
+ case PA_DEVICE_PORT_TYPE_LINE: return _("Line");
+ case PA_DEVICE_PORT_TYPE_MIC: return _("Mic");
+ case PA_DEVICE_PORT_TYPE_HEADSET: return _("Headset");
+ case PA_DEVICE_PORT_TYPE_HANDSET: return _("Handset");
+ case PA_DEVICE_PORT_TYPE_EARPIECE: return _("Earpiece");
+ case PA_DEVICE_PORT_TYPE_SPDIF: return _("SPDIF");
+ case PA_DEVICE_PORT_TYPE_HDMI: return _("HDMI");
+ case PA_DEVICE_PORT_TYPE_TV: return _("TV");
+ case PA_DEVICE_PORT_TYPE_RADIO: return _("Radio");
+ case PA_DEVICE_PORT_TYPE_VIDEO: return _("Video");
+ case PA_DEVICE_PORT_TYPE_USB: return _("USB");
+ case PA_DEVICE_PORT_TYPE_BLUETOOTH: return _("Bluetooth");
+ case PA_DEVICE_PORT_TYPE_PORTABLE: return _("Portable");
+ case PA_DEVICE_PORT_TYPE_HANDSFREE: return _("Handsfree");
+ case PA_DEVICE_PORT_TYPE_CAR: return _("Car");
+ case PA_DEVICE_PORT_TYPE_HIFI: return _("HiFi");
+ case PA_DEVICE_PORT_TYPE_PHONE: return _("Phone");
+ case PA_DEVICE_PORT_TYPE_NETWORK: return _("Network");
+ case PA_DEVICE_PORT_TYPE_ANALOG: return _("Analog");
+ }
+ snprintf(buf, sizeof(buf), "%s-%u", _("Unknown"), type);
+ return buf;
+}
+
+static void get_sink_info_callback(pa_context *c, const pa_sink_info *i, int is_last, void *userdata) {
+
+ static const char *state_table[] = {
+ [1+PA_SINK_INVALID_STATE] = "n/a",
+ [1+PA_SINK_RUNNING] = "RUNNING",
+ [1+PA_SINK_IDLE] = "IDLE",
+ [1+PA_SINK_SUSPENDED] = "SUSPENDED"
+ };
+
+ char
+ s[PA_SAMPLE_SPEC_SNPRINT_MAX],
+ cv[PA_CVOLUME_SNPRINT_VERBOSE_MAX],
+ v[PA_VOLUME_SNPRINT_VERBOSE_MAX],
+ cm[PA_CHANNEL_MAP_SNPRINT_MAX],
+ f[PA_FORMAT_INFO_SNPRINT_MAX];
+ char *pl;
+
+ if (is_last < 0) {
+ pa_log(_("Failed to get sink information: %s"), pa_strerror(pa_context_errno(c)));
+ quit(1);
+ return;
+ }
+
+ if (is_last) {
+ complete_action();
+ return;
+ }
+
+ pa_assert(i);
+
+ if (nl && !short_list_format)
+ printf("\n");
+ nl = true;
+
+ if (short_list_format) {
+ printf("%u\t%s\t%s\t%s\t%s\n",
+ i->index,
+ i->name,
+ pa_strnull(i->driver),
+ pa_sample_spec_snprint(s, sizeof(s), &i->sample_spec),
+ state_table[1+i->state]);
+ return;
+ }
+
+ printf(_("Sink #%u\n"
+ "\tState: %s\n"
+ "\tName: %s\n"
+ "\tDescription: %s\n"
+ "\tDriver: %s\n"
+ "\tSample Specification: %s\n"
+ "\tChannel Map: %s\n"
+ "\tOwner Module: %u\n"
+ "\tMute: %s\n"
+ "\tVolume: %s\n"
+ "\t balance %0.2f\n"
+ "\tBase Volume: %s\n"
+ "\tMonitor Source: %s\n"
+ "\tLatency: %0.0f usec, configured %0.0f usec\n"
+ "\tFlags: %s%s%s%s%s%s%s\n"
+ "\tProperties:\n\t\t%s\n"),
+ i->index,
+ state_table[1+i->state],
+ i->name,
+ pa_strnull(i->description),
+ pa_strnull(i->driver),
+ pa_sample_spec_snprint(s, sizeof(s), &i->sample_spec),
+ pa_channel_map_snprint(cm, sizeof(cm), &i->channel_map),
+ i->owner_module,
+ pa_yes_no_localised(i->mute),
+ pa_cvolume_snprint_verbose(cv, sizeof(cv), &i->volume, &i->channel_map, i->flags & PA_SINK_DECIBEL_VOLUME),
+ pa_cvolume_get_balance(&i->volume, &i->channel_map),
+ pa_volume_snprint_verbose(v, sizeof(v), i->base_volume, i->flags & PA_SINK_DECIBEL_VOLUME),
+ pa_strnull(i->monitor_source_name),
+ (double) i->latency, (double) i->configured_latency,
+ i->flags & PA_SINK_HARDWARE ? "HARDWARE " : "",
+ i->flags & PA_SINK_NETWORK ? "NETWORK " : "",
+ i->flags & PA_SINK_HW_MUTE_CTRL ? "HW_MUTE_CTRL " : "",
+ i->flags & PA_SINK_HW_VOLUME_CTRL ? "HW_VOLUME_CTRL " : "",
+ i->flags & PA_SINK_DECIBEL_VOLUME ? "DECIBEL_VOLUME " : "",
+ i->flags & PA_SINK_LATENCY ? "LATENCY " : "",
+ i->flags & PA_SINK_SET_FORMATS ? "SET_FORMATS " : "",
+ pl = pa_proplist_to_string_sep(i->proplist, "\n\t\t"));
+
+ pa_xfree(pl);
+
+ if (i->ports) {
+ pa_sink_port_info **p;
+
+ printf(_("\tPorts:\n"));
+ for (p = i->ports; *p; p++)
+ printf(_("\t\t%s: %s (type: %s, priority: %u%s%s, %s)\n"),
+ (*p)->name, (*p)->description, get_device_port_type((*p)->type),
+ (*p)->priority, (*p)->availability_group ? _(", availability group: ") : "",
+ (*p)->availability_group ?: "", get_available_str((*p)->available));
+ }
+
+ if (i->active_port)
+ printf(_("\tActive Port: %s\n"),
+ i->active_port->name);
+
+ if (i->formats) {
+ uint8_t j;
+
+ printf(_("\tFormats:\n"));
+ for (j = 0; j < i->n_formats; j++)
+ printf("\t\t%s\n", pa_format_info_snprint(f, sizeof(f), i->formats[j]));
+ }
+}
+
+static void get_source_info_callback(pa_context *c, const pa_source_info *i, int is_last, void *userdata) {
+
+ static const char *state_table[] = {
+ [1+PA_SOURCE_INVALID_STATE] = "n/a",
+ [1+PA_SOURCE_RUNNING] = "RUNNING",
+ [1+PA_SOURCE_IDLE] = "IDLE",
+ [1+PA_SOURCE_SUSPENDED] = "SUSPENDED"
+ };
+
+ char
+ s[PA_SAMPLE_SPEC_SNPRINT_MAX],
+ cv[PA_CVOLUME_SNPRINT_VERBOSE_MAX],
+ v[PA_VOLUME_SNPRINT_VERBOSE_MAX],
+ cm[PA_CHANNEL_MAP_SNPRINT_MAX],
+ f[PA_FORMAT_INFO_SNPRINT_MAX];
+ char *pl;
+
+ if (is_last < 0) {
+ pa_log(_("Failed to get source information: %s"), pa_strerror(pa_context_errno(c)));
+ quit(1);
+ return;
+ }
+
+ if (is_last) {
+ complete_action();
+ return;
+ }
+
+ pa_assert(i);
+
+ if (nl && !short_list_format)
+ printf("\n");
+ nl = true;
+
+ if (short_list_format) {
+ printf("%u\t%s\t%s\t%s\t%s\n",
+ i->index,
+ i->name,
+ pa_strnull(i->driver),
+ pa_sample_spec_snprint(s, sizeof(s), &i->sample_spec),
+ state_table[1+i->state]);
+ return;
+ }
+
+ printf(_("Source #%u\n"
+ "\tState: %s\n"
+ "\tName: %s\n"
+ "\tDescription: %s\n"
+ "\tDriver: %s\n"
+ "\tSample Specification: %s\n"
+ "\tChannel Map: %s\n"
+ "\tOwner Module: %u\n"
+ "\tMute: %s\n"
+ "\tVolume: %s\n"
+ "\t balance %0.2f\n"
+ "\tBase Volume: %s\n"
+ "\tMonitor of Sink: %s\n"
+ "\tLatency: %0.0f usec, configured %0.0f usec\n"
+ "\tFlags: %s%s%s%s%s%s\n"
+ "\tProperties:\n\t\t%s\n"),
+ i->index,
+ state_table[1+i->state],
+ i->name,
+ pa_strnull(i->description),
+ pa_strnull(i->driver),
+ pa_sample_spec_snprint(s, sizeof(s), &i->sample_spec),
+ pa_channel_map_snprint(cm, sizeof(cm), &i->channel_map),
+ i->owner_module,
+ pa_yes_no_localised(i->mute),
+ pa_cvolume_snprint_verbose(cv, sizeof(cv), &i->volume, &i->channel_map, i->flags & PA_SOURCE_DECIBEL_VOLUME),
+ pa_cvolume_get_balance(&i->volume, &i->channel_map),
+ pa_volume_snprint_verbose(v, sizeof(v), i->base_volume, i->flags & PA_SOURCE_DECIBEL_VOLUME),
+ i->monitor_of_sink_name ? i->monitor_of_sink_name : _("n/a"),
+ (double) i->latency, (double) i->configured_latency,
+ i->flags & PA_SOURCE_HARDWARE ? "HARDWARE " : "",
+ i->flags & PA_SOURCE_NETWORK ? "NETWORK " : "",
+ i->flags & PA_SOURCE_HW_MUTE_CTRL ? "HW_MUTE_CTRL " : "",
+ i->flags & PA_SOURCE_HW_VOLUME_CTRL ? "HW_VOLUME_CTRL " : "",
+ i->flags & PA_SOURCE_DECIBEL_VOLUME ? "DECIBEL_VOLUME " : "",
+ i->flags & PA_SOURCE_LATENCY ? "LATENCY " : "",
+ pl = pa_proplist_to_string_sep(i->proplist, "\n\t\t"));
+
+ pa_xfree(pl);
+
+ if (i->ports) {
+ pa_source_port_info **p;
+
+ printf(_("\tPorts:\n"));
+ for (p = i->ports; *p; p++)
+ printf(_("\t\t%s: %s (type: %s, priority: %u%s%s, %s)\n"),
+ (*p)->name, (*p)->description, get_device_port_type((*p)->type),
+ (*p)->priority, (*p)->availability_group ? _(", availability group: ") : "",
+ (*p)->availability_group ?: "", get_available_str((*p)->available));
+ }
+
+ if (i->active_port)
+ printf(_("\tActive Port: %s\n"),
+ i->active_port->name);
+
+ if (i->formats) {
+ uint8_t j;
+
+ printf(_("\tFormats:\n"));
+ for (j = 0; j < i->n_formats; j++)
+ printf("\t\t%s\n", pa_format_info_snprint(f, sizeof(f), i->formats[j]));
+ }
+}
+
+static void get_module_info_callback(pa_context *c, const pa_module_info *i, int is_last, void *userdata) {
+ char t[32];
+ char *pl;
+
+ if (is_last < 0) {
+ pa_log(_("Failed to get module information: %s"), pa_strerror(pa_context_errno(c)));
+ quit(1);
+ return;
+ }
+
+ if (is_last) {
+ complete_action();
+ return;
+ }
+
+ pa_assert(i);
+
+ if (nl && !short_list_format)
+ printf("\n");
+ nl = true;
+
+ pa_snprintf(t, sizeof(t), "%u", i->n_used);
+
+ if (short_list_format) {
+ printf("%u\t%s\t%s\t\n", i->index, i->name, i->argument ? i->argument : "");
+ return;
+ }
+
+ printf(_("Module #%u\n"
+ "\tName: %s\n"
+ "\tArgument: %s\n"
+ "\tUsage counter: %s\n"
+ "\tProperties:\n\t\t%s\n"),
+ i->index,
+ i->name,
+ i->argument ? i->argument : "",
+ i->n_used != PA_INVALID_INDEX ? t : _("n/a"),
+ pl = pa_proplist_to_string_sep(i->proplist, "\n\t\t"));
+
+ pa_xfree(pl);
+}
+
+static void get_client_info_callback(pa_context *c, const pa_client_info *i, int is_last, void *userdata) {
+ char t[32];
+ char *pl;
+
+ if (is_last < 0) {
+ pa_log(_("Failed to get client information: %s"), pa_strerror(pa_context_errno(c)));
+ quit(1);
+ return;
+ }
+
+ if (is_last) {
+ complete_action();
+ return;
+ }
+
+ pa_assert(i);
+
+ if (nl && !short_list_format)
+ printf("\n");
+ nl = true;
+
+ pa_snprintf(t, sizeof(t), "%u", i->owner_module);
+
+ if (short_list_format) {
+ printf("%u\t%s\t%s\n",
+ i->index,
+ pa_strnull(i->driver),
+ pa_strnull(pa_proplist_gets(i->proplist, PA_PROP_APPLICATION_PROCESS_BINARY)));
+ return;
+ }
+
+ printf(_("Client #%u\n"
+ "\tDriver: %s\n"
+ "\tOwner Module: %s\n"
+ "\tProperties:\n\t\t%s\n"),
+ i->index,
+ pa_strnull(i->driver),
+ i->owner_module != PA_INVALID_INDEX ? t : _("n/a"),
+ pl = pa_proplist_to_string_sep(i->proplist, "\n\t\t"));
+
+ pa_xfree(pl);
+}
+
+static void get_card_info_callback(pa_context *c, const pa_card_info *i, int is_last, void *userdata) {
+ char t[32];
+ char *pl;
+
+ if (is_last < 0) {
+ pa_log(_("Failed to get card information: %s"), pa_strerror(pa_context_errno(c)));
+ complete_action();
+ return;
+ }
+
+ if (is_last) {
+ complete_action();
+ return;
+ }
+
+ pa_assert(i);
+
+ if (nl && !short_list_format)
+ printf("\n");
+ nl = true;
+
+ pa_snprintf(t, sizeof(t), "%u", i->owner_module);
+
+ if (short_list_format) {
+ printf("%u\t%s\t%s\n", i->index, i->name, pa_strnull(i->driver));
+ return;
+ }
+
+ printf(_("Card #%u\n"
+ "\tName: %s\n"
+ "\tDriver: %s\n"
+ "\tOwner Module: %s\n"
+ "\tProperties:\n\t\t%s\n"),
+ i->index,
+ i->name,
+ pa_strnull(i->driver),
+ i->owner_module != PA_INVALID_INDEX ? t : _("n/a"),
+ pl = pa_proplist_to_string_sep(i->proplist, "\n\t\t"));
+
+ pa_xfree(pl);
+
+ if (i->n_profiles > 0) {
+ pa_card_profile_info2 **p;
+
+ printf(_("\tProfiles:\n"));
+ for (p = i->profiles2; *p; p++)
+ printf(_("\t\t%s: %s (sinks: %u, sources: %u, priority: %u, available: %s)\n"), (*p)->name,
+ (*p)->description, (*p)->n_sinks, (*p)->n_sources, (*p)->priority, pa_yes_no_localised((*p)->available));
+ }
+
+ if (i->active_profile)
+ printf(_("\tActive Profile: %s\n"),
+ i->active_profile->name);
+
+ if (i->ports) {
+ pa_card_port_info **p;
+
+ printf(_("\tPorts:\n"));
+ for (p = i->ports; *p; p++) {
+ pa_card_profile_info **pr = (*p)->profiles;
+ printf(_("\t\t%s: %s (type: %s, priority: %u, latency offset: %" PRId64 " usec%s%s, %s)\n"), (*p)->name,
+ (*p)->description, get_device_port_type((*p)->type), (*p)->priority, (*p)->latency_offset,
+ (*p)->availability_group ? _(", availability group: ") : "", (*p)->availability_group ?: "",
+ get_available_str((*p)->available));
+
+ if (!pa_proplist_isempty((*p)->proplist)) {
+ printf(_("\t\t\tProperties:\n\t\t\t\t%s\n"), pl = pa_proplist_to_string_sep((*p)->proplist, "\n\t\t\t\t"));
+ pa_xfree(pl);
+ }
+
+ if (pr) {
+ printf(_("\t\t\tPart of profile(s): %s"), pa_strnull((*pr)->name));
+ pr++;
+ while (*pr) {
+ printf(", %s", pa_strnull((*pr)->name));
+ pr++;
+ }
+ printf("\n");
+ }
+ }
+ }
+}
+
+static void get_sink_input_info_callback(pa_context *c, const pa_sink_input_info *i, int is_last, void *userdata) {
+ char t[32], k[32], s[PA_SAMPLE_SPEC_SNPRINT_MAX], cv[PA_CVOLUME_SNPRINT_VERBOSE_MAX], cm[PA_CHANNEL_MAP_SNPRINT_MAX], f[PA_FORMAT_INFO_SNPRINT_MAX];
+ char *pl;
+
+ if (is_last < 0) {
+ pa_log(_("Failed to get sink input information: %s"), pa_strerror(pa_context_errno(c)));
+ quit(1);
+ return;
+ }
+
+ if (is_last) {
+ complete_action();
+ return;
+ }
+
+ pa_assert(i);
+
+ if (nl && !short_list_format)
+ printf("\n");
+ nl = true;
+
+ pa_snprintf(t, sizeof(t), "%u", i->owner_module);
+ pa_snprintf(k, sizeof(k), "%u", i->client);
+
+ if (short_list_format) {
+ printf("%u\t%u\t%s\t%s\t%s\n",
+ i->index,
+ i->sink,
+ i->client != PA_INVALID_INDEX ? k : "-",
+ pa_strnull(i->driver),
+ pa_sample_spec_snprint(s, sizeof(s), &i->sample_spec));
+ return;
+ }
+
+ printf(_("Sink Input #%u\n"
+ "\tDriver: %s\n"
+ "\tOwner Module: %s\n"
+ "\tClient: %s\n"
+ "\tSink: %u\n"
+ "\tSample Specification: %s\n"
+ "\tChannel Map: %s\n"
+ "\tFormat: %s\n"
+ "\tCorked: %s\n"
+ "\tMute: %s\n"
+ "\tVolume: %s\n"
+ "\t balance %0.2f\n"
+ "\tBuffer Latency: %0.0f usec\n"
+ "\tSink Latency: %0.0f usec\n"
+ "\tResample method: %s\n"
+ "\tProperties:\n\t\t%s\n"),
+ i->index,
+ pa_strnull(i->driver),
+ i->owner_module != PA_INVALID_INDEX ? t : _("n/a"),
+ i->client != PA_INVALID_INDEX ? k : _("n/a"),
+ i->sink,
+ pa_sample_spec_snprint(s, sizeof(s), &i->sample_spec),
+ pa_channel_map_snprint(cm, sizeof(cm), &i->channel_map),
+ pa_format_info_snprint(f, sizeof(f), i->format),
+ pa_yes_no_localised(i->corked),
+ pa_yes_no_localised(i->mute),
+ pa_cvolume_snprint_verbose(cv, sizeof(cv), &i->volume, &i->channel_map, true),
+ pa_cvolume_get_balance(&i->volume, &i->channel_map),
+ (double) i->buffer_usec,
+ (double) i->sink_usec,
+ i->resample_method ? i->resample_method : _("n/a"),
+ pl = pa_proplist_to_string_sep(i->proplist, "\n\t\t"));
+
+ pa_xfree(pl);
+}
+
+static void get_source_output_info_callback(pa_context *c, const pa_source_output_info *i, int is_last, void *userdata) {
+ char t[32], k[32], s[PA_SAMPLE_SPEC_SNPRINT_MAX], cv[PA_CVOLUME_SNPRINT_VERBOSE_MAX], cm[PA_CHANNEL_MAP_SNPRINT_MAX], f[PA_FORMAT_INFO_SNPRINT_MAX];
+ char *pl;
+
+ if (is_last < 0) {
+ pa_log(_("Failed to get source output information: %s"), pa_strerror(pa_context_errno(c)));
+ quit(1);
+ return;
+ }
+
+ if (is_last) {
+ complete_action();
+ return;
+ }
+
+ pa_assert(i);
+
+ if (nl && !short_list_format)
+ printf("\n");
+ nl = true;
+
+ pa_snprintf(t, sizeof(t), "%u", i->owner_module);
+ pa_snprintf(k, sizeof(k), "%u", i->client);
+
+ if (short_list_format) {
+ printf("%u\t%u\t%s\t%s\t%s\n",
+ i->index,
+ i->source,
+ i->client != PA_INVALID_INDEX ? k : "-",
+ pa_strnull(i->driver),
+ pa_sample_spec_snprint(s, sizeof(s), &i->sample_spec));
+ return;
+ }
+
+ printf(_("Source Output #%u\n"
+ "\tDriver: %s\n"
+ "\tOwner Module: %s\n"
+ "\tClient: %s\n"
+ "\tSource: %u\n"
+ "\tSample Specification: %s\n"
+ "\tChannel Map: %s\n"
+ "\tFormat: %s\n"
+ "\tCorked: %s\n"
+ "\tMute: %s\n"
+ "\tVolume: %s\n"
+ "\t balance %0.2f\n"
+ "\tBuffer Latency: %0.0f usec\n"
+ "\tSource Latency: %0.0f usec\n"
+ "\tResample method: %s\n"
+ "\tProperties:\n\t\t%s\n"),
+ i->index,
+ pa_strnull(i->driver),
+ i->owner_module != PA_INVALID_INDEX ? t : _("n/a"),
+ i->client != PA_INVALID_INDEX ? k : _("n/a"),
+ i->source,
+ pa_sample_spec_snprint(s, sizeof(s), &i->sample_spec),
+ pa_channel_map_snprint(cm, sizeof(cm), &i->channel_map),
+ pa_format_info_snprint(f, sizeof(f), i->format),
+ pa_yes_no_localised(i->corked),
+ pa_yes_no_localised(i->mute),
+ pa_cvolume_snprint_verbose(cv, sizeof(cv), &i->volume, &i->channel_map, true),
+ pa_cvolume_get_balance(&i->volume, &i->channel_map),
+ (double) i->buffer_usec,
+ (double) i->source_usec,
+ i->resample_method ? i->resample_method : _("n/a"),
+ pl = pa_proplist_to_string_sep(i->proplist, "\n\t\t"));
+
+ pa_xfree(pl);
+}
+
+static void get_sample_info_callback(pa_context *c, const pa_sample_info *i, int is_last, void *userdata) {
+ char t[PA_BYTES_SNPRINT_MAX], s[PA_SAMPLE_SPEC_SNPRINT_MAX], cv[PA_CVOLUME_SNPRINT_VERBOSE_MAX], cm[PA_CHANNEL_MAP_SNPRINT_MAX];
+ char *pl;
+
+ if (is_last < 0) {
+ pa_log(_("Failed to get sample information: %s"), pa_strerror(pa_context_errno(c)));
+ quit(1);
+ return;
+ }
+
+ if (is_last) {
+ complete_action();
+ return;
+ }
+
+ pa_assert(i);
+
+ if (nl && !short_list_format)
+ printf("\n");
+ nl = true;
+
+ pa_bytes_snprint(t, sizeof(t), i->bytes);
+
+ if (short_list_format) {
+ printf("%u\t%s\t%s\t%0.3f\n",
+ i->index,
+ i->name,
+ pa_sample_spec_valid(&i->sample_spec) ? pa_sample_spec_snprint(s, sizeof(s), &i->sample_spec) : "-",
+ (double) i->duration/1000000.0);
+ return;
+ }
+
+ printf(_("Sample #%u\n"
+ "\tName: %s\n"
+ "\tSample Specification: %s\n"
+ "\tChannel Map: %s\n"
+ "\tVolume: %s\n"
+ "\t balance %0.2f\n"
+ "\tDuration: %0.1fs\n"
+ "\tSize: %s\n"
+ "\tLazy: %s\n"
+ "\tFilename: %s\n"
+ "\tProperties:\n\t\t%s\n"),
+ i->index,
+ i->name,
+ pa_sample_spec_valid(&i->sample_spec) ? pa_sample_spec_snprint(s, sizeof(s), &i->sample_spec) : _("n/a"),
+ pa_sample_spec_valid(&i->sample_spec) ? pa_channel_map_snprint(cm, sizeof(cm), &i->channel_map) : _("n/a"),
+ pa_cvolume_snprint_verbose(cv, sizeof(cv), &i->volume, &i->channel_map, true),
+ pa_cvolume_get_balance(&i->volume, &i->channel_map),
+ (double) i->duration/1000000.0,
+ t,
+ pa_yes_no_localised(i->lazy),
+ i->filename ? i->filename : _("n/a"),
+ pl = pa_proplist_to_string_sep(i->proplist, "\n\t\t"));
+
+ pa_xfree(pl);
+}
+
+static void simple_callback(pa_context *c, int success, void *userdata) {
+ if (!success) {
+ pa_log(_("Failure: %s"), pa_strerror(pa_context_errno(c)));
+ quit(1);
+ return;
+ }
+
+ complete_action();
+}
+
+static void index_callback(pa_context *c, uint32_t idx, void *userdata) {
+ if (idx == PA_INVALID_INDEX) {
+ pa_log(_("Failure: %s"), pa_strerror(pa_context_errno(c)));
+ quit(1);
+ return;
+ }
+
+ printf("%u\n", idx);
+
+ complete_action();
+}
+
+static void volume_relative_adjust(pa_cvolume *cv) {
+ pa_assert(volume_flags & VOL_RELATIVE);
+
+ /* Relative volume change is additive in case of UINT or PERCENT
+ * and multiplicative for LINEAR or DECIBEL */
+ if ((volume_flags & 0x0F) == VOL_UINT || (volume_flags & 0x0F) == VOL_PERCENT) {
+ unsigned i;
+ for (i = 0; i < cv->channels; i++) {
+ if (cv->values[i] + volume.values[i] < PA_VOLUME_NORM)
+ cv->values[i] = PA_VOLUME_MUTED;
+ else
+ cv->values[i] = cv->values[i] + volume.values[i] - PA_VOLUME_NORM;
+ }
+ }
+ if ((volume_flags & 0x0F) == VOL_LINEAR || (volume_flags & 0x0F) == VOL_DECIBEL)
+ pa_sw_cvolume_multiply(cv, cv, &volume);
+}
+
+static void unload_module_by_name_callback(pa_context *c, const pa_module_info *i, int is_last, void *userdata) {
+ static bool unloaded = false;
+
+ if (is_last < 0) {
+ pa_log(_("Failed to get module information: %s"), pa_strerror(pa_context_errno(c)));
+ quit(1);
+ return;
+ }
+
+ if (is_last) {
+ if (unloaded == false)
+ pa_log(_("Failed to unload module: Module %s not loaded"), module_name);
+ complete_action();
+ return;
+ }
+
+ pa_assert(i);
+
+ if (pa_streq(module_name, i->name)) {
+ unloaded = true;
+ actions++;
+ pa_operation_unref(pa_context_unload_module(c, i->index, simple_callback, NULL));
+ }
+}
+
+static void fill_volume(pa_cvolume *cv, unsigned supported) {
+ if (volume.channels == 1) {
+ pa_cvolume_set(&volume, supported, volume.values[0]);
+ } else if (volume.channels != supported) {
+ pa_log(ngettext("Failed to set volume: You tried to set volumes for %d channel, whereas channel(s) supported = %d\n",
+ "Failed to set volume: You tried to set volumes for %d channels, whereas channel(s) supported = %d\n",
+ volume.channels),
+ volume.channels, supported);
+ quit(1);
+ return;
+ }
+
+ if (volume_flags & VOL_RELATIVE)
+ volume_relative_adjust(cv);
+ else
+ *cv = volume;
+}
+
+static void get_sink_volume_callback(pa_context *c, const pa_sink_info *i, int is_last, void *userdata) {
+ pa_cvolume cv;
+
+ if (is_last < 0) {
+ pa_log(_("Failed to get sink information: %s"), pa_strerror(pa_context_errno(c)));
+ quit(1);
+ return;
+ }
+
+ if (is_last)
+ return;
+
+ pa_assert(i);
+
+ cv = i->volume;
+ fill_volume(&cv, i->channel_map.channels);
+
+ pa_operation_unref(pa_context_set_sink_volume_by_name(c, sink_name, &cv, simple_callback, NULL));
+}
+
+static void get_source_volume_callback(pa_context *c, const pa_source_info *i, int is_last, void *userdata) {
+ pa_cvolume cv;
+
+ if (is_last < 0) {
+ pa_log(_("Failed to get source information: %s"), pa_strerror(pa_context_errno(c)));
+ quit(1);
+ return;
+ }
+
+ if (is_last)
+ return;
+
+ pa_assert(i);
+
+ cv = i->volume;
+ fill_volume(&cv, i->channel_map.channels);
+
+ pa_operation_unref(pa_context_set_source_volume_by_name(c, source_name, &cv, simple_callback, NULL));
+}
+
+static void get_sink_input_volume_callback(pa_context *c, const pa_sink_input_info *i, int is_last, void *userdata) {
+ pa_cvolume cv;
+
+ if (is_last < 0) {
+ pa_log(_("Failed to get sink input information: %s"), pa_strerror(pa_context_errno(c)));
+ quit(1);
+ return;
+ }
+
+ if (is_last)
+ return;
+
+ pa_assert(i);
+
+ cv = i->volume;
+ fill_volume(&cv, i->channel_map.channels);
+
+ pa_operation_unref(pa_context_set_sink_input_volume(c, sink_input_idx, &cv, simple_callback, NULL));
+}
+
+static void get_source_output_volume_callback(pa_context *c, const pa_source_output_info *o, int is_last, void *userdata) {
+ pa_cvolume cv;
+
+ if (is_last < 0) {
+ pa_log(_("Failed to get source output information: %s"), pa_strerror(pa_context_errno(c)));
+ quit(1);
+ return;
+ }
+
+ if (is_last)
+ return;
+
+ pa_assert(o);
+
+ cv = o->volume;
+ fill_volume(&cv, o->channel_map.channels);
+
+ pa_operation_unref(pa_context_set_source_output_volume(c, source_output_idx, &cv, simple_callback, NULL));
+}
+
+static void sink_toggle_mute_callback(pa_context *c, const pa_sink_info *i, int is_last, void *userdata) {
+ if (is_last < 0) {
+ pa_log(_("Failed to get sink information: %s"), pa_strerror(pa_context_errno(c)));
+ quit(1);
+ return;
+ }
+
+ if (is_last)
+ return;
+
+ pa_assert(i);
+
+ pa_operation_unref(pa_context_set_sink_mute_by_name(c, i->name, !i->mute, simple_callback, NULL));
+}
+
+static void source_toggle_mute_callback(pa_context *c, const pa_source_info *o, int is_last, void *userdata) {
+ if (is_last < 0) {
+ pa_log(_("Failed to get source information: %s"), pa_strerror(pa_context_errno(c)));
+ quit(1);
+ return;
+ }
+
+ if (is_last)
+ return;
+
+ pa_assert(o);
+
+ pa_operation_unref(pa_context_set_source_mute_by_name(c, o->name, !o->mute, simple_callback, NULL));
+}
+
+static void sink_input_toggle_mute_callback(pa_context *c, const pa_sink_input_info *i, int is_last, void *userdata) {
+ if (is_last < 0) {
+ pa_log(_("Failed to get sink input information: %s"), pa_strerror(pa_context_errno(c)));
+ quit(1);
+ return;
+ }
+
+ if (is_last)
+ return;
+
+ pa_assert(i);
+
+ pa_operation_unref(pa_context_set_sink_input_mute(c, i->index, !i->mute, simple_callback, NULL));
+}
+
+static void source_output_toggle_mute_callback(pa_context *c, const pa_source_output_info *o, int is_last, void *userdata) {
+ if (is_last < 0) {
+ pa_log(_("Failed to get source output information: %s"), pa_strerror(pa_context_errno(c)));
+ quit(1);
+ return;
+ }
+
+ if (is_last)
+ return;
+
+ pa_assert(o);
+
+ pa_operation_unref(pa_context_set_source_output_mute(c, o->index, !o->mute, simple_callback, NULL));
+}
+
+/* PA_MAX_FORMATS is defined in internal.h so we just define a sane value here */
+#define MAX_FORMATS 256
+
+static void set_sink_formats(pa_context *c, uint32_t sink, const char *str) {
+ pa_format_info *f_arr[MAX_FORMATS] = { 0, };
+ char *format = NULL;
+ const char *state = NULL;
+ int i = 0;
+ pa_operation *o = NULL;
+
+ while ((format = pa_split(str, ";", &state))) {
+ pa_format_info *f = pa_format_info_from_string(pa_strip(format));
+
+ if (!f) {
+ pa_log(_("Failed to set format: invalid format string %s"), format);
+ goto error;
+ }
+
+ f_arr[i++] = f;
+ pa_xfree(format);
+ }
+
+ o = pa_ext_device_restore_save_formats(c, PA_DEVICE_TYPE_SINK, sink, i, f_arr, simple_callback, NULL);
+ if (o) {
+ pa_operation_unref(o);
+ actions++;
+ }
+
+done:
+ if (format)
+ pa_xfree(format);
+ while (f_arr[i] && i--)
+ pa_format_info_free(f_arr[i]);
+
+ return;
+
+error:
+ while (f_arr[i] && i--)
+ pa_format_info_free(f_arr[i]);
+ quit(1);
+ goto done;
+}
+
+static void stream_state_callback(pa_stream *s, void *userdata) {
+ pa_assert(s);
+
+ switch (pa_stream_get_state(s)) {
+ case PA_STREAM_CREATING:
+ case PA_STREAM_READY:
+ break;
+
+ case PA_STREAM_TERMINATED:
+ drain();
+ break;
+
+ case PA_STREAM_FAILED:
+ default:
+ pa_log(_("Failed to upload sample: %s"), pa_strerror(pa_context_errno(pa_stream_get_context(s))));
+ quit(1);
+ }
+}
+
+static void stream_write_callback(pa_stream *s, size_t length, void *userdata) {
+ sf_count_t l;
+ float *d;
+ pa_assert(s && length && sndfile);
+
+ d = pa_xmalloc(length);
+
+ pa_assert(sample_length >= length);
+ l = (sf_count_t) (length/pa_frame_size(&sample_spec));
+
+ if ((sf_readf_float(sndfile, d, l)) != l) {
+ pa_xfree(d);
+ pa_log(_("Premature end of file"));
+ quit(1);
+ return;
+ }
+
+ pa_stream_write(s, d, length, pa_xfree, 0, PA_SEEK_RELATIVE);
+
+ sample_length -= length;
+
+ if (sample_length <= 0) {
+ pa_stream_set_write_callback(sample_stream, NULL, NULL);
+ pa_stream_finish_upload(sample_stream);
+ }
+}
+
+static const char *subscription_event_type_to_string(pa_subscription_event_type_t t) {
+
+ switch (t & PA_SUBSCRIPTION_EVENT_TYPE_MASK) {
+
+ case PA_SUBSCRIPTION_EVENT_NEW:
+ return _("new");
+
+ case PA_SUBSCRIPTION_EVENT_CHANGE:
+ return _("change");
+
+ case PA_SUBSCRIPTION_EVENT_REMOVE:
+ return _("remove");
+ }
+
+ return _("unknown");
+}
+
+static const char *subscription_event_facility_to_string(pa_subscription_event_type_t t) {
+
+ switch (t & PA_SUBSCRIPTION_EVENT_FACILITY_MASK) {
+
+ case PA_SUBSCRIPTION_EVENT_SINK:
+ return _("sink");
+
+ case PA_SUBSCRIPTION_EVENT_SOURCE:
+ return _("source");
+
+ case PA_SUBSCRIPTION_EVENT_SINK_INPUT:
+ return _("sink-input");
+
+ case PA_SUBSCRIPTION_EVENT_SOURCE_OUTPUT:
+ return _("source-output");
+
+ case PA_SUBSCRIPTION_EVENT_MODULE:
+ return _("module");
+
+ case PA_SUBSCRIPTION_EVENT_CLIENT:
+ return _("client");
+
+ case PA_SUBSCRIPTION_EVENT_SAMPLE_CACHE:
+ return _("sample-cache");
+
+ case PA_SUBSCRIPTION_EVENT_SERVER:
+ return _("server");
+
+ case PA_SUBSCRIPTION_EVENT_CARD:
+ return _("card");
+ }
+
+ return _("unknown");
+}
+
+static void context_subscribe_callback(pa_context *c, pa_subscription_event_type_t t, uint32_t idx, void *userdata) {
+ pa_assert(c);
+
+ printf(_("Event '%s' on %s #%u\n"),
+ subscription_event_type_to_string(t),
+ subscription_event_facility_to_string(t),
+ idx);
+ fflush(stdout);
+}
+
+static void context_state_callback(pa_context *c, void *userdata) {
+ pa_operation *o = NULL;
+
+ pa_assert(c);
+
+ switch (pa_context_get_state(c)) {
+ case PA_CONTEXT_CONNECTING:
+ case PA_CONTEXT_AUTHORIZING:
+ case PA_CONTEXT_SETTING_NAME:
+ break;
+
+ case PA_CONTEXT_READY:
+ switch (action) {
+ case STAT:
+ o = pa_context_stat(c, stat_callback, NULL);
+ break;
+
+ case INFO:
+ o = pa_context_get_server_info(c, get_server_info_callback, NULL);
+ break;
+
+ case PLAY_SAMPLE:
+ o = pa_context_play_sample(c, sample_name, sink_name, PA_VOLUME_NORM, simple_callback, NULL);
+ break;
+
+ case REMOVE_SAMPLE:
+ o = pa_context_remove_sample(c, sample_name, simple_callback, NULL);
+ break;
+
+ case UPLOAD_SAMPLE:
+ sample_stream = pa_stream_new(c, sample_name, &sample_spec, NULL);
+ pa_assert(sample_stream);
+
+ pa_stream_set_state_callback(sample_stream, stream_state_callback, NULL);
+ pa_stream_set_write_callback(sample_stream, stream_write_callback, NULL);
+ pa_stream_connect_upload(sample_stream, sample_length);
+ actions++;
+ break;
+
+ case EXIT:
+ o = pa_context_exit_daemon(c, simple_callback, NULL);
+ break;
+
+ case LIST:
+ if (list_type) {
+ if (pa_streq(list_type, "modules"))
+ o = pa_context_get_module_info_list(c, get_module_info_callback, NULL);
+ else if (pa_streq(list_type, "sinks"))
+ o = pa_context_get_sink_info_list(c, get_sink_info_callback, NULL);
+ else if (pa_streq(list_type, "sources"))
+ o = pa_context_get_source_info_list(c, get_source_info_callback, NULL);
+ else if (pa_streq(list_type, "sink-inputs"))
+ o = pa_context_get_sink_input_info_list(c, get_sink_input_info_callback, NULL);
+ else if (pa_streq(list_type, "source-outputs"))
+ o = pa_context_get_source_output_info_list(c, get_source_output_info_callback, NULL);
+ else if (pa_streq(list_type, "clients"))
+ o = pa_context_get_client_info_list(c, get_client_info_callback, NULL);
+ else if (pa_streq(list_type, "samples"))
+ o = pa_context_get_sample_info_list(c, get_sample_info_callback, NULL);
+ else if (pa_streq(list_type, "cards"))
+ o = pa_context_get_card_info_list(c, get_card_info_callback, NULL);
+ else
+ pa_assert_not_reached();
+ } else {
+ o = pa_context_get_module_info_list(c, get_module_info_callback, NULL);
+ if (o) {
+ pa_operation_unref(o);
+ actions++;
+ }
+
+ o = pa_context_get_sink_info_list(c, get_sink_info_callback, NULL);
+ if (o) {
+ pa_operation_unref(o);
+ actions++;
+ }
+
+ o = pa_context_get_source_info_list(c, get_source_info_callback, NULL);
+ if (o) {
+ pa_operation_unref(o);
+ actions++;
+ }
+ o = pa_context_get_sink_input_info_list(c, get_sink_input_info_callback, NULL);
+ if (o) {
+ pa_operation_unref(o);
+ actions++;
+ }
+
+ o = pa_context_get_source_output_info_list(c, get_source_output_info_callback, NULL);
+ if (o) {
+ pa_operation_unref(o);
+ actions++;
+ }
+
+ o = pa_context_get_client_info_list(c, get_client_info_callback, NULL);
+ if (o) {
+ pa_operation_unref(o);
+ actions++;
+ }
+
+ o = pa_context_get_sample_info_list(c, get_sample_info_callback, NULL);
+ if (o) {
+ pa_operation_unref(o);
+ actions++;
+ }
+
+ o = pa_context_get_card_info_list(c, get_card_info_callback, NULL);
+ if (o) {
+ pa_operation_unref(o);
+ actions++;
+ }
+
+ o = NULL;
+ }
+ break;
+
+ case MOVE_SINK_INPUT:
+ o = pa_context_move_sink_input_by_name(c, sink_input_idx, sink_name, simple_callback, NULL);
+ break;
+
+ case MOVE_SOURCE_OUTPUT:
+ o = pa_context_move_source_output_by_name(c, source_output_idx, source_name, simple_callback, NULL);
+ break;
+
+ case LOAD_MODULE:
+ o = pa_context_load_module(c, module_name, module_args, index_callback, NULL);
+ break;
+
+ case UNLOAD_MODULE:
+ if (module_name)
+ o = pa_context_get_module_info_list(c, unload_module_by_name_callback, NULL);
+ else
+ o = pa_context_unload_module(c, module_index, simple_callback, NULL);
+ break;
+
+ case SUSPEND_SINK:
+ if (sink_name)
+ o = pa_context_suspend_sink_by_name(c, sink_name, suspend, simple_callback, NULL);
+ else
+ o = pa_context_suspend_sink_by_index(c, PA_INVALID_INDEX, suspend, simple_callback, NULL);
+ break;
+
+ case SUSPEND_SOURCE:
+ if (source_name)
+ o = pa_context_suspend_source_by_name(c, source_name, suspend, simple_callback, NULL);
+ else
+ o = pa_context_suspend_source_by_index(c, PA_INVALID_INDEX, suspend, simple_callback, NULL);
+ break;
+
+ case SET_CARD_PROFILE:
+ o = pa_context_set_card_profile_by_name(c, card_name, profile_name, simple_callback, NULL);
+ break;
+
+ case SET_SINK_PORT:
+ o = pa_context_set_sink_port_by_name(c, sink_name, port_name, simple_callback, NULL);
+ break;
+
+ case SET_DEFAULT_SINK:
+ o = pa_context_set_default_sink(c, sink_name, simple_callback, NULL);
+ break;
+
+ case SET_SOURCE_PORT:
+ o = pa_context_set_source_port_by_name(c, source_name, port_name, simple_callback, NULL);
+ break;
+
+ case SET_DEFAULT_SOURCE:
+ o = pa_context_set_default_source(c, source_name, simple_callback, NULL);
+ break;
+
+ case SET_SINK_MUTE:
+ if (mute == TOGGLE_MUTE)
+ o = pa_context_get_sink_info_by_name(c, sink_name, sink_toggle_mute_callback, NULL);
+ else
+ o = pa_context_set_sink_mute_by_name(c, sink_name, mute, simple_callback, NULL);
+ break;
+
+ case SET_SOURCE_MUTE:
+ if (mute == TOGGLE_MUTE)
+ o = pa_context_get_source_info_by_name(c, source_name, source_toggle_mute_callback, NULL);
+ else
+ o = pa_context_set_source_mute_by_name(c, source_name, mute, simple_callback, NULL);
+ break;
+
+ case SET_SINK_INPUT_MUTE:
+ if (mute == TOGGLE_MUTE)
+ o = pa_context_get_sink_input_info(c, sink_input_idx, sink_input_toggle_mute_callback, NULL);
+ else
+ o = pa_context_set_sink_input_mute(c, sink_input_idx, mute, simple_callback, NULL);
+ break;
+
+ case SET_SOURCE_OUTPUT_MUTE:
+ if (mute == TOGGLE_MUTE)
+ o = pa_context_get_source_output_info(c, source_output_idx, source_output_toggle_mute_callback, NULL);
+ else
+ o = pa_context_set_source_output_mute(c, source_output_idx, mute, simple_callback, NULL);
+ break;
+
+ case SET_SINK_VOLUME:
+ o = pa_context_get_sink_info_by_name(c, sink_name, get_sink_volume_callback, NULL);
+ break;
+
+ case SET_SOURCE_VOLUME:
+ o = pa_context_get_source_info_by_name(c, source_name, get_source_volume_callback, NULL);
+ break;
+
+ case SET_SINK_INPUT_VOLUME:
+ o = pa_context_get_sink_input_info(c, sink_input_idx, get_sink_input_volume_callback, NULL);
+ break;
+
+ case SET_SOURCE_OUTPUT_VOLUME:
+ o = pa_context_get_source_output_info(c, source_output_idx, get_source_output_volume_callback, NULL);
+ break;
+
+ case SET_SINK_FORMATS:
+ set_sink_formats(c, sink_idx, formats);
+ break;
+
+ case SET_PORT_LATENCY_OFFSET:
+ o = pa_context_set_port_latency_offset(c, card_name, port_name, latency_offset, simple_callback, NULL);
+ break;
+
+ case SUBSCRIBE:
+ pa_context_set_subscribe_callback(c, context_subscribe_callback, NULL);
+
+ o = pa_context_subscribe(c,
+ PA_SUBSCRIPTION_MASK_SINK|
+ PA_SUBSCRIPTION_MASK_SOURCE|
+ PA_SUBSCRIPTION_MASK_SINK_INPUT|
+ PA_SUBSCRIPTION_MASK_SOURCE_OUTPUT|
+ PA_SUBSCRIPTION_MASK_MODULE|
+ PA_SUBSCRIPTION_MASK_CLIENT|
+ PA_SUBSCRIPTION_MASK_SAMPLE_CACHE|
+ PA_SUBSCRIPTION_MASK_SERVER|
+ PA_SUBSCRIPTION_MASK_CARD,
+ NULL,
+ NULL);
+ break;
+
+ default:
+ pa_assert_not_reached();
+ }
+
+ if (o) {
+ pa_operation_unref(o);
+ actions++;
+ }
+
+ if (actions == 0) {
+ pa_log("Operation failed: %s", pa_strerror(pa_context_errno(c)));
+ quit(1);
+ }
+
+ break;
+
+ case PA_CONTEXT_TERMINATED:
+ quit(0);
+ break;
+
+ case PA_CONTEXT_FAILED:
+ default:
+ pa_log(_("Connection failure: %s"), pa_strerror(pa_context_errno(c)));
+ quit(1);
+ }
+}
+
+static void exit_signal_callback(pa_mainloop_api *m, pa_signal_event *e, int sig, void *userdata) {
+ pa_log(_("Got SIGINT, exiting."));
+ quit(0);
+}
+
+static int parse_volume(const char *vol_spec, pa_volume_t *vol, enum volume_flags *vol_flags) {
+ double v;
+ char *vs;
+ const char *atod_input;
+
+ pa_assert(vol_spec);
+ pa_assert(vol);
+ pa_assert(vol_flags);
+
+ vs = pa_xstrdup(vol_spec);
+
+ *vol_flags = (pa_startswith(vs, "+") || pa_startswith(vs, "-")) ? VOL_RELATIVE : VOL_ABSOLUTE;
+ if (strchr(vs, '.'))
+ *vol_flags |= VOL_LINEAR;
+ if (pa_endswith(vs, "%")) {
+ *vol_flags |= VOL_PERCENT;
+ vs[strlen(vs)-1] = 0;
+ }
+ if (pa_endswith(vs, "db") || pa_endswith(vs, "dB")) {
+ *vol_flags |= VOL_DECIBEL;
+ vs[strlen(vs)-2] = 0;
+ }
+
+ atod_input = vs;
+
+ if (atod_input[0] == '+')
+ atod_input++; /* pa_atod() doesn't accept leading '+', so skip it. */
+
+ if (pa_atod(atod_input, &v) < 0) {
+ pa_log(_("Invalid volume specification"));
+ pa_xfree(vs);
+ return -1;
+ }
+
+ pa_xfree(vs);
+
+ if (*vol_flags & VOL_RELATIVE) {
+ if ((*vol_flags & 0x0F) == VOL_UINT)
+ v += (double) PA_VOLUME_NORM;
+ if ((*vol_flags & 0x0F) == VOL_PERCENT)
+ v += 100.0;
+ if ((*vol_flags & 0x0F) == VOL_LINEAR)
+ v += 1.0;
+ }
+ if ((*vol_flags & 0x0F) == VOL_PERCENT)
+ v = v * (double) PA_VOLUME_NORM / 100;
+ if ((*vol_flags & 0x0F) == VOL_LINEAR)
+ v = pa_sw_volume_from_linear(v);
+ if ((*vol_flags & 0x0F) == VOL_DECIBEL)
+ v = pa_sw_volume_from_dB(v);
+
+ if (!PA_VOLUME_IS_VALID((pa_volume_t) v)) {
+ pa_log(_("Volume outside permissible range.\n"));
+ return -1;
+ }
+
+ *vol = (pa_volume_t) v;
+
+ return 0;
+}
+
+static int parse_volumes(char *args[], unsigned n) {
+ unsigned i;
+
+ if (n >= PA_CHANNELS_MAX) {
+ pa_log(_("Invalid number of volume specifications.\n"));
+ return -1;
+ }
+
+ volume.channels = n;
+ for (i = 0; i < volume.channels; i++) {
+ enum volume_flags flags;
+
+ if (parse_volume(args[i], &volume.values[i], &flags) < 0)
+ return -1;
+
+ if (i > 0 && flags != volume_flags) {
+ pa_log(_("Inconsistent volume specification.\n"));
+ return -1;
+ } else
+ volume_flags = flags;
+ }
+
+ return 0;
+}
+
+static enum mute_flags parse_mute(const char *mute_text) {
+ int b;
+
+ pa_assert(mute_text);
+
+ if (pa_streq("toggle", mute_text))
+ return TOGGLE_MUTE;
+
+ b = pa_parse_boolean(mute_text);
+ switch (b) {
+ case 0:
+ return UNMUTE;
+ case 1:
+ return MUTE;
+ default:
+ return INVALID_MUTE;
+ }
+}
+
+static void help(const char *argv0) {
+
+ printf("%s %s %s\n", argv0, _("[options]"), "stat");
+ printf("%s %s %s\n", argv0, _("[options]"), "info");
+ printf("%s %s %s %s\n", argv0, _("[options]"), "list [short]", _("[TYPE]"));
+ printf("%s %s %s\n", argv0, _("[options]"), "exit");
+ printf("%s %s %s %s\n", argv0, _("[options]"), "upload-sample", _("FILENAME [NAME]"));
+ printf("%s %s %s %s\n", argv0, _("[options]"), "play-sample ", _("NAME [SINK]"));
+ printf("%s %s %s %s\n", argv0, _("[options]"), "remove-sample ", _("NAME"));
+ printf("%s %s %s %s\n", argv0, _("[options]"), "load-module ", _("NAME [ARGS ...]"));
+ printf("%s %s %s %s\n", argv0, _("[options]"), "unload-module ", _("NAME|#N"));
+ printf("%s %s %s %s\n", argv0, _("[options]"), "move-(sink-input|source-output)", _("#N SINK|SOURCE"));
+ printf("%s %s %s %s\n", argv0, _("[options]"), "suspend-(sink|source)", _("NAME|#N 1|0"));
+ printf("%s %s %s %s\n", argv0, _("[options]"), "set-card-profile ", _("CARD PROFILE"));
+ printf("%s %s %s %s\n", argv0, _("[options]"), "set-default-(sink|source)", _("NAME"));
+ printf("%s %s %s %s\n", argv0, _("[options]"), "set-(sink|source)-port", _("NAME|#N PORT"));
+ printf("%s %s %s %s\n", argv0, _("[options]"), "set-(sink|source)-volume", _("NAME|#N VOLUME [VOLUME ...]"));
+ printf("%s %s %s %s\n", argv0, _("[options]"), "set-(sink-input|source-output)-volume", _("#N VOLUME [VOLUME ...]"));
+ printf("%s %s %s %s\n", argv0, _("[options]"), "set-(sink|source)-mute", _("NAME|#N 1|0|toggle"));
+ printf("%s %s %s %s\n", argv0, _("[options]"), "set-(sink-input|source-output)-mute", _("#N 1|0|toggle"));
+ printf("%s %s %s %s\n", argv0, _("[options]"), "set-sink-formats", _("#N FORMATS"));
+ printf("%s %s %s %s\n", argv0, _("[options]"), "set-port-latency-offset", _("CARD-NAME|CARD-#N PORT OFFSET"));
+ printf("%s %s %s\n", argv0, _("[options]"), "subscribe");
+ printf(_("\nThe special names @DEFAULT_SINK@, @DEFAULT_SOURCE@ and @DEFAULT_MONITOR@\n"
+ "can be used to specify the default sink, source and monitor.\n"));
+
+ printf(_("\n"
+ " -h, --help Show this help\n"
+ " --version Show version\n\n"
+ " -s, --server=SERVER The name of the server to connect to\n"
+ " -n, --client-name=NAME How to call this client on the server\n"));
+}
+
+enum {
+ ARG_VERSION = 256
+};
+
+int main(int argc, char *argv[]) {
+ pa_mainloop *m = NULL;
+ int ret = 1, c;
+ char *server = NULL, *bn;
+
+ static const struct option long_options[] = {
+ {"server", 1, NULL, 's'},
+ {"client-name", 1, NULL, 'n'},
+ {"version", 0, NULL, ARG_VERSION},
+ {"help", 0, NULL, 'h'},
+ {NULL, 0, NULL, 0}
+ };
+
+ setlocale(LC_ALL, "");
+#ifdef ENABLE_NLS
+ bindtextdomain(GETTEXT_PACKAGE, PULSE_LOCALEDIR);
+#endif
+
+ bn = pa_path_get_filename(argv[0]);
+
+ proplist = pa_proplist_new();
+
+ while ((c = getopt_long(argc, argv, "+s:n:h", long_options, NULL)) != -1) {
+ switch (c) {
+ case 'h' :
+ help(bn);
+ ret = 0;
+ goto quit;
+
+ case ARG_VERSION:
+ printf(_("pactl %s\n"
+ "Compiled with libpulse %s\n"
+ "Linked with libpulse %s\n"),
+ PACKAGE_VERSION,
+ pa_get_headers_version(),
+ pa_get_library_version());
+ ret = 0;
+ goto quit;
+
+ case 's':
+ pa_xfree(server);
+ server = pa_xstrdup(optarg);
+ break;
+
+ case 'n': {
+ char *t;
+
+ if (!(t = pa_locale_to_utf8(optarg)) ||
+ pa_proplist_sets(proplist, PA_PROP_APPLICATION_NAME, t) < 0) {
+
+ pa_log(_("Invalid client name '%s'"), t ? t : optarg);
+ pa_xfree(t);
+ goto quit;
+ }
+
+ pa_xfree(t);
+ break;
+ }
+
+ default:
+ goto quit;
+ }
+ }
+
+ if (optind < argc) {
+ if (pa_streq(argv[optind], "stat")) {
+ action = STAT;
+
+ } else if (pa_streq(argv[optind], "info"))
+ action = INFO;
+
+ else if (pa_streq(argv[optind], "exit"))
+ action = EXIT;
+
+ else if (pa_streq(argv[optind], "list")) {
+ action = LIST;
+
+ for (int i = optind+1; i < argc; i++) {
+ if (pa_streq(argv[i], "modules") || pa_streq(argv[i], "clients") ||
+ pa_streq(argv[i], "sinks") || pa_streq(argv[i], "sink-inputs") ||
+ pa_streq(argv[i], "sources") || pa_streq(argv[i], "source-outputs") ||
+ pa_streq(argv[i], "samples") || pa_streq(argv[i], "cards")) {
+ list_type = pa_xstrdup(argv[i]);
+ } else if (pa_streq(argv[i], "short")) {
+ short_list_format = true;
+ } else {
+ pa_log(_("Specify nothing, or one of: %s"), "modules, sinks, sources, sink-inputs, source-outputs, clients, samples, cards");
+ goto quit;
+ }
+ }
+
+ } else if (pa_streq(argv[optind], "upload-sample")) {
+ struct SF_INFO sfi;
+ action = UPLOAD_SAMPLE;
+
+ if (optind+1 >= argc) {
+ pa_log(_("Please specify a sample file to load"));
+ goto quit;
+ }
+
+ if (optind+2 < argc)
+ sample_name = pa_xstrdup(argv[optind+2]);
+ else {
+ char *f = pa_path_get_filename(argv[optind+1]);
+ sample_name = pa_xstrndup(f, strcspn(f, "."));
+ }
+
+ pa_zero(sfi);
+ if (!(sndfile = sf_open(argv[optind+1], SFM_READ, &sfi))) {
+ pa_log(_("Failed to open sound file."));
+ goto quit;
+ }
+
+ if (pa_sndfile_read_sample_spec(sndfile, &sample_spec) < 0) {
+ pa_log(_("Failed to determine sample specification from file."));
+ goto quit;
+ }
+ sample_spec.format = PA_SAMPLE_FLOAT32;
+
+ if (pa_sndfile_read_channel_map(sndfile, &channel_map) < 0) {
+ if (sample_spec.channels > 2)
+ pa_log(_("Warning: Failed to determine sample specification from file."));
+ pa_channel_map_init_extend(&channel_map, sample_spec.channels, PA_CHANNEL_MAP_DEFAULT);
+ }
+
+ pa_assert(pa_channel_map_compatible(&channel_map, &sample_spec));
+ sample_length = (size_t) sfi.frames*pa_frame_size(&sample_spec);
+
+ } else if (pa_streq(argv[optind], "play-sample")) {
+ action = PLAY_SAMPLE;
+ if (argc != optind+2 && argc != optind+3) {
+ pa_log(_("You have to specify a sample name to play"));
+ goto quit;
+ }
+
+ sample_name = pa_xstrdup(argv[optind+1]);
+
+ if (optind+2 < argc)
+ sink_name = pa_xstrdup(argv[optind+2]);
+
+ } else if (pa_streq(argv[optind], "remove-sample")) {
+ action = REMOVE_SAMPLE;
+ if (argc != optind+2) {
+ pa_log(_("You have to specify a sample name to remove"));
+ goto quit;
+ }
+
+ sample_name = pa_xstrdup(argv[optind+1]);
+
+ } else if (pa_streq(argv[optind], "move-sink-input")) {
+ action = MOVE_SINK_INPUT;
+ if (argc != optind+3) {
+ pa_log(_("You have to specify a sink input index and a sink"));
+ goto quit;
+ }
+
+ sink_input_idx = (uint32_t) atoi(argv[optind+1]);
+ sink_name = pa_xstrdup(argv[optind+2]);
+
+ } else if (pa_streq(argv[optind], "move-source-output")) {
+ action = MOVE_SOURCE_OUTPUT;
+ if (argc != optind+3) {
+ pa_log(_("You have to specify a source output index and a source"));
+ goto quit;
+ }
+
+ source_output_idx = (uint32_t) atoi(argv[optind+1]);
+ source_name = pa_xstrdup(argv[optind+2]);
+
+ } else if (pa_streq(argv[optind], "load-module")) {
+ int i;
+ size_t n = 0;
+ char *p;
+
+ action = LOAD_MODULE;
+
+ if (argc <= optind+1) {
+ pa_log(_("You have to specify a module name and arguments."));
+ goto quit;
+ }
+
+ module_name = argv[optind+1];
+
+ for (i = optind+2; i < argc; i++)
+ n += strlen(argv[i])+1;
+
+ if (n > 0) {
+ p = module_args = pa_xmalloc(n);
+
+ for (i = optind+2; i < argc; i++)
+ p += sprintf(p, "%s%s", p == module_args ? "" : " ", argv[i]);
+ }
+
+ } else if (pa_streq(argv[optind], "unload-module")) {
+ action = UNLOAD_MODULE;
+
+ if (argc != optind+2) {
+ pa_log(_("You have to specify a module index or name"));
+ goto quit;
+ }
+
+ if (pa_atou(argv[optind + 1], &module_index) < 0)
+ module_name = argv[optind + 1];
+
+ } else if (pa_streq(argv[optind], "suspend-sink")) {
+ int b;
+
+ action = SUSPEND_SINK;
+
+ if (argc > optind+3 || optind+1 >= argc) {
+ pa_log(_("You may not specify more than one sink. You have to specify a boolean value."));
+ goto quit;
+ }
+
+ if ((b = pa_parse_boolean(argv[argc-1])) < 0) {
+ pa_log(_("Invalid suspend specification."));
+ goto quit;
+ }
+
+ suspend = !!b;
+
+ if (argc > optind+2)
+ sink_name = pa_xstrdup(argv[optind+1]);
+
+ } else if (pa_streq(argv[optind], "suspend-source")) {
+ int b;
+
+ action = SUSPEND_SOURCE;
+
+ if (argc > optind+3 || optind+1 >= argc) {
+ pa_log(_("You may not specify more than one source. You have to specify a boolean value."));
+ goto quit;
+ }
+
+ if ((b = pa_parse_boolean(argv[argc-1])) < 0) {
+ pa_log(_("Invalid suspend specification."));
+ goto quit;
+ }
+
+ suspend = !!b;
+
+ if (argc > optind+2)
+ source_name = pa_xstrdup(argv[optind+1]);
+ } else if (pa_streq(argv[optind], "set-card-profile")) {
+ action = SET_CARD_PROFILE;
+
+ if (argc != optind+3) {
+ pa_log(_("You have to specify a card name/index and a profile name"));
+ goto quit;
+ }
+
+ card_name = pa_xstrdup(argv[optind+1]);
+ profile_name = pa_xstrdup(argv[optind+2]);
+
+ } else if (pa_streq(argv[optind], "set-sink-port")) {
+ action = SET_SINK_PORT;
+
+ if (argc != optind+3) {
+ pa_log(_("You have to specify a sink name/index and a port name"));
+ goto quit;
+ }
+
+ sink_name = pa_xstrdup(argv[optind+1]);
+ port_name = pa_xstrdup(argv[optind+2]);
+
+ } else if (pa_streq(argv[optind], "set-default-sink")) {
+ action = SET_DEFAULT_SINK;
+
+ if (argc != optind+2) {
+ pa_log(_("You have to specify a sink name"));
+ goto quit;
+ }
+
+ sink_name = pa_xstrdup(argv[optind+1]);
+
+ } else if (pa_streq(argv[optind], "set-source-port")) {
+ action = SET_SOURCE_PORT;
+
+ if (argc != optind+3) {
+ pa_log(_("You have to specify a source name/index and a port name"));
+ goto quit;
+ }
+
+ source_name = pa_xstrdup(argv[optind+1]);
+ port_name = pa_xstrdup(argv[optind+2]);
+
+ } else if (pa_streq(argv[optind], "set-default-source")) {
+ action = SET_DEFAULT_SOURCE;
+
+ if (argc != optind+2) {
+ pa_log(_("You have to specify a source name"));
+ goto quit;
+ }
+
+ source_name = pa_xstrdup(argv[optind+1]);
+
+ } else if (pa_streq(argv[optind], "set-sink-volume")) {
+ action = SET_SINK_VOLUME;
+
+ if (argc < optind+3) {
+ pa_log(_("You have to specify a sink name/index and a volume"));
+ goto quit;
+ }
+
+ sink_name = pa_xstrdup(argv[optind+1]);
+
+ if (parse_volumes(argv+optind+2, argc-(optind+2)) < 0)
+ goto quit;
+
+ } else if (pa_streq(argv[optind], "set-source-volume")) {
+ action = SET_SOURCE_VOLUME;
+
+ if (argc < optind+3) {
+ pa_log(_("You have to specify a source name/index and a volume"));
+ goto quit;
+ }
+
+ source_name = pa_xstrdup(argv[optind+1]);
+
+ if (parse_volumes(argv+optind+2, argc-(optind+2)) < 0)
+ goto quit;
+
+ } else if (pa_streq(argv[optind], "set-sink-input-volume")) {
+ action = SET_SINK_INPUT_VOLUME;
+
+ if (argc < optind+3) {
+ pa_log(_("You have to specify a sink input index and a volume"));
+ goto quit;
+ }
+
+ if (pa_atou(argv[optind+1], &sink_input_idx) < 0) {
+ pa_log(_("Invalid sink input index"));
+ goto quit;
+ }
+
+ if (parse_volumes(argv+optind+2, argc-(optind+2)) < 0)
+ goto quit;
+
+ } else if (pa_streq(argv[optind], "set-source-output-volume")) {
+ action = SET_SOURCE_OUTPUT_VOLUME;
+
+ if (argc < optind+3) {
+ pa_log(_("You have to specify a source output index and a volume"));
+ goto quit;
+ }
+
+ if (pa_atou(argv[optind+1], &source_output_idx) < 0) {
+ pa_log(_("Invalid source output index"));
+ goto quit;
+ }
+
+ if (parse_volumes(argv+optind+2, argc-(optind+2)) < 0)
+ goto quit;
+
+ } else if (pa_streq(argv[optind], "set-sink-mute")) {
+ action = SET_SINK_MUTE;
+
+ if (argc != optind+3) {
+ pa_log(_("You have to specify a sink name/index and a mute action (0, 1, or 'toggle')"));
+ goto quit;
+ }
+
+ if ((mute = parse_mute(argv[optind+2])) == INVALID_MUTE) {
+ pa_log(_("Invalid mute specification"));
+ goto quit;
+ }
+
+ sink_name = pa_xstrdup(argv[optind+1]);
+
+ } else if (pa_streq(argv[optind], "set-source-mute")) {
+ action = SET_SOURCE_MUTE;
+
+ if (argc != optind+3) {
+ pa_log(_("You have to specify a source name/index and a mute action (0, 1, or 'toggle')"));
+ goto quit;
+ }
+
+ if ((mute = parse_mute(argv[optind+2])) == INVALID_MUTE) {
+ pa_log(_("Invalid mute specification"));
+ goto quit;
+ }
+
+ source_name = pa_xstrdup(argv[optind+1]);
+
+ } else if (pa_streq(argv[optind], "set-sink-input-mute")) {
+ action = SET_SINK_INPUT_MUTE;
+
+ if (argc != optind+3) {
+ pa_log(_("You have to specify a sink input index and a mute action (0, 1, or 'toggle')"));
+ goto quit;
+ }
+
+ if (pa_atou(argv[optind+1], &sink_input_idx) < 0) {
+ pa_log(_("Invalid sink input index specification"));
+ goto quit;
+ }
+
+ if ((mute = parse_mute(argv[optind+2])) == INVALID_MUTE) {
+ pa_log(_("Invalid mute specification"));
+ goto quit;
+ }
+
+ } else if (pa_streq(argv[optind], "set-source-output-mute")) {
+ action = SET_SOURCE_OUTPUT_MUTE;
+
+ if (argc != optind+3) {
+ pa_log(_("You have to specify a source output index and a mute action (0, 1, or 'toggle')"));
+ goto quit;
+ }
+
+ if (pa_atou(argv[optind+1], &source_output_idx) < 0) {
+ pa_log(_("Invalid source output index specification"));
+ goto quit;
+ }
+
+ if ((mute = parse_mute(argv[optind+2])) == INVALID_MUTE) {
+ pa_log(_("Invalid mute specification"));
+ goto quit;
+ }
+
+ } else if (pa_streq(argv[optind], "subscribe"))
+
+ action = SUBSCRIBE;
+
+ else if (pa_streq(argv[optind], "set-sink-formats")) {
+ int32_t tmp;
+
+ if (argc != optind+3 || pa_atoi(argv[optind+1], &tmp) < 0) {
+ pa_log(_("You have to specify a sink index and a semicolon-separated list of supported formats"));
+ goto quit;
+ }
+
+ sink_idx = tmp;
+ action = SET_SINK_FORMATS;
+ formats = pa_xstrdup(argv[optind+2]);
+
+ } else if (pa_streq(argv[optind], "set-port-latency-offset")) {
+ action = SET_PORT_LATENCY_OFFSET;
+
+ if (argc != optind+4) {
+ pa_log(_("You have to specify a card name/index, a port name and a latency offset"));
+ goto quit;
+ }
+
+ card_name = pa_xstrdup(argv[optind+1]);
+ port_name = pa_xstrdup(argv[optind+2]);
+ if (pa_atoi(argv[optind + 3], &latency_offset) < 0) {
+ pa_log(_("Could not parse latency offset"));
+ goto quit;
+ }
+
+ } else if (pa_streq(argv[optind], "help")) {
+ help(bn);
+ ret = 0;
+ goto quit;
+ }
+ }
+
+ if (action == NONE) {
+ pa_log(_("No valid command specified."));
+ goto quit;
+ }
+
+ if (!(m = pa_mainloop_new())) {
+ pa_log(_("pa_mainloop_new() failed."));
+ goto quit;
+ }
+
+ mainloop_api = pa_mainloop_get_api(m);
+
+ pa_assert_se(pa_signal_init(mainloop_api) == 0);
+ pa_signal_new(SIGINT, exit_signal_callback, NULL);
+ pa_signal_new(SIGTERM, exit_signal_callback, NULL);
+ pa_disable_sigpipe();
+
+ if (!(context = pa_context_new_with_proplist(mainloop_api, NULL, proplist))) {
+ pa_log(_("pa_context_new() failed."));
+ goto quit;
+ }
+
+ pa_context_set_state_callback(context, context_state_callback, NULL);
+ if (pa_context_connect(context, server, 0, NULL) < 0) {
+ pa_log(_("pa_context_connect() failed: %s"), pa_strerror(pa_context_errno(context)));
+ goto quit;
+ }
+
+ if (pa_mainloop_run(m, &ret) < 0) {
+ pa_log(_("pa_mainloop_run() failed."));
+ goto quit;
+ }
+
+quit:
+ if (sample_stream)
+ pa_stream_unref(sample_stream);
+
+ if (context)
+ pa_context_unref(context);
+
+ if (m) {
+ pa_signal_done();
+ pa_mainloop_free(m);
+ }
+
+ pa_xfree(server);
+ pa_xfree(list_type);
+ pa_xfree(sample_name);
+ pa_xfree(sink_name);
+ pa_xfree(source_name);
+ pa_xfree(module_args);
+ pa_xfree(card_name);
+ pa_xfree(profile_name);
+ pa_xfree(port_name);
+ pa_xfree(formats);
+
+ if (sndfile)
+ sf_close(sndfile);
+
+ if (proplist)
+ pa_proplist_free(proplist);
+
+ return ret;
+}
diff --git a/src/utils/padsp.c b/src/utils/padsp.c
new file mode 100644
index 0000000..a53b161
--- /dev/null
+++ b/src/utils/padsp.c
@@ -0,0 +1,2747 @@
+/***
+ This file is part of PulseAudio.
+
+ Copyright 2006 Lennart Poettering
+ Copyright 2006-2007 Pierre Ossman <ossman@cendio.se> for Cendio AB
+
+ PulseAudio is free software; you can redistribute it and/or modify
+ it under the terms of the GNU Lesser General Public License as published
+ by the Free Software Foundation; either version 2.1 of the License,
+ or (at your option) any later version.
+
+ PulseAudio is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+***/
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#ifdef _FILE_OFFSET_BITS
+#undef _FILE_OFFSET_BITS
+#endif
+
+#ifndef _LARGEFILE64_SOURCE
+#define _LARGEFILE64_SOURCE 1
+#endif
+
+#include <sys/soundcard.h>
+#include <sys/ioctl.h>
+#include <pthread.h>
+#include <unistd.h>
+#include <sys/socket.h>
+#include <sys/stat.h>
+#include <dlfcn.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <string.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <signal.h>
+
+#ifdef __linux__
+#include <linux/sockios.h>
+#endif
+
+#include <pulse/pulseaudio.h>
+#include <pulse/gccmacro.h>
+#include <pulsecore/llist.h>
+#include <pulsecore/core-util.h>
+#include <pulsecore/sample-util.h>
+
+/* On some systems SIOCINQ isn't defined, but FIONREAD is just an alias */
+#if !defined(SIOCINQ) && defined(FIONREAD)
+# define SIOCINQ FIONREAD
+#endif
+
+/* make sure gcc doesn't redefine open and friends as macros */
+#undef open
+#undef open64
+
+typedef enum {
+ FD_INFO_MIXER,
+ FD_INFO_STREAM,
+} fd_info_type_t;
+
+typedef struct fd_info fd_info;
+
+struct fd_info {
+ pthread_mutex_t mutex;
+ int ref;
+ int unusable;
+
+ fd_info_type_t type;
+ int app_fd, thread_fd;
+
+ pa_sample_spec sample_spec;
+ size_t fragment_size;
+ unsigned n_fragments;
+
+ pa_threaded_mainloop *mainloop;
+ pa_context *context;
+ pa_stream *play_stream;
+ pa_stream *rec_stream;
+ int play_precork;
+ int rec_precork;
+
+ pa_io_event *io_event;
+ pa_io_event_flags_t io_flags;
+
+ void *buf;
+ size_t leftover;
+ size_t rec_offset;
+
+ int operation_success;
+
+ pa_cvolume sink_volume, source_volume;
+ uint32_t sink_index, source_index;
+ int volume_modify_count;
+
+ int optr_n_blocks;
+
+ PA_LLIST_FIELDS(fd_info);
+};
+
+static int dsp_drain(fd_info *i);
+static void fd_info_remove_from_list(fd_info *i);
+
+static pthread_mutex_t fd_infos_mutex = PTHREAD_MUTEX_INITIALIZER;
+static pthread_mutex_t func_mutex = PTHREAD_MUTEX_INITIALIZER;
+
+static PA_LLIST_HEAD(fd_info, fd_infos) = NULL;
+
+static int (*_ioctl)(int, int, void*) = NULL;
+static int (*_close)(int) = NULL;
+static int (*_open)(const char *, int, mode_t) = NULL;
+static int (*___open_2)(const char *, int) = NULL;
+static FILE* (*_fopen)(const char *path, const char *mode) = NULL;
+static int (*_stat)(const char *, struct stat *) = NULL;
+#ifdef _STAT_VER
+static int (*___xstat)(int, const char *, struct stat *) = NULL;
+#endif
+#ifdef HAVE_OPEN64
+static int (*_open64)(const char *, int, mode_t) = NULL;
+static int (*___open64_2)(const char *, int) = NULL;
+static FILE* (*_fopen64)(const char *path, const char *mode) = NULL;
+static int (*_stat64)(const char *, struct stat64 *) = NULL;
+#ifdef _STAT_VER
+static int (*___xstat64)(int, const char *, struct stat64 *) = NULL;
+#endif
+#endif
+static int (*_fclose)(FILE *f) = NULL;
+static int (*_access)(const char *, int) = NULL;
+
+/* dlsym() violates ISO C, so confide the breakage into this function to
+ * avoid warnings. */
+typedef void (*fnptr)(void);
+static inline fnptr dlsym_fn(void *handle, const char *symbol) {
+ return (fnptr) (long) dlsym(handle, symbol);
+}
+
+#define LOAD_IOCTL_FUNC() \
+do { \
+ pthread_mutex_lock(&func_mutex); \
+ if (!_ioctl) \
+ _ioctl = (int (*)(int, int, void*)) dlsym_fn(RTLD_NEXT, "ioctl"); \
+ pthread_mutex_unlock(&func_mutex); \
+} while(0)
+
+#define LOAD_OPEN_FUNC() \
+do { \
+ pthread_mutex_lock(&func_mutex); \
+ if (!_open) \
+ _open = (int (*)(const char *, int, mode_t)) dlsym_fn(RTLD_NEXT, "open"); \
+ pthread_mutex_unlock(&func_mutex); \
+} while(0)
+
+#define LOAD___OPEN_2_FUNC() \
+do { \
+ pthread_mutex_lock(&func_mutex); \
+ if (!___open_2) \
+ ___open_2 = (int (*)(const char *, int)) dlsym_fn(RTLD_NEXT, "__open_2"); \
+ pthread_mutex_unlock(&func_mutex); \
+} while(0)
+
+#define LOAD_OPEN64_FUNC() \
+do { \
+ pthread_mutex_lock(&func_mutex); \
+ if (!_open64) \
+ _open64 = (int (*)(const char *, int, mode_t)) dlsym_fn(RTLD_NEXT, "open64"); \
+ pthread_mutex_unlock(&func_mutex); \
+} while(0)
+
+#define LOAD___OPEN64_2_FUNC() \
+do { \
+ pthread_mutex_lock(&func_mutex); \
+ if (!___open64_2) \
+ ___open64_2 = (int (*)(const char *, int)) dlsym_fn(RTLD_NEXT, "__open64_2"); \
+ pthread_mutex_unlock(&func_mutex); \
+} while(0)
+
+#define LOAD_CLOSE_FUNC() \
+do { \
+ pthread_mutex_lock(&func_mutex); \
+ if (!_close) \
+ _close = (int (*)(int)) dlsym_fn(RTLD_NEXT, "close"); \
+ pthread_mutex_unlock(&func_mutex); \
+} while(0)
+
+#define LOAD_ACCESS_FUNC() \
+do { \
+ pthread_mutex_lock(&func_mutex); \
+ if (!_access) \
+ _access = (int (*)(const char*, int)) dlsym_fn(RTLD_NEXT, "access"); \
+ pthread_mutex_unlock(&func_mutex); \
+} while(0)
+
+#define LOAD_STAT_FUNC() \
+do { \
+ pthread_mutex_lock(&func_mutex); \
+ if (!_stat) \
+ _stat = (int (*)(const char *, struct stat *)) dlsym_fn(RTLD_NEXT, "stat"); \
+ pthread_mutex_unlock(&func_mutex); \
+} while(0)
+
+#define LOAD_STAT64_FUNC() \
+do { \
+ pthread_mutex_lock(&func_mutex); \
+ if (!_stat64) \
+ _stat64 = (int (*)(const char *, struct stat64 *)) dlsym_fn(RTLD_NEXT, "stat64"); \
+ pthread_mutex_unlock(&func_mutex); \
+} while(0)
+
+#define LOAD_XSTAT_FUNC() \
+do { \
+ pthread_mutex_lock(&func_mutex); \
+ if (!___xstat) \
+ ___xstat = (int (*)(int, const char *, struct stat *)) dlsym_fn(RTLD_NEXT, "__xstat"); \
+ pthread_mutex_unlock(&func_mutex); \
+} while(0)
+
+#define LOAD_XSTAT64_FUNC() \
+do { \
+ pthread_mutex_lock(&func_mutex); \
+ if (!___xstat64) \
+ ___xstat64 = (int (*)(int, const char *, struct stat64 *)) dlsym_fn(RTLD_NEXT, "__xstat64"); \
+ pthread_mutex_unlock(&func_mutex); \
+} while(0)
+
+#define LOAD_FOPEN_FUNC() \
+do { \
+ pthread_mutex_lock(&func_mutex); \
+ if (!_fopen) \
+ _fopen = (FILE* (*)(const char *, const char*)) dlsym_fn(RTLD_NEXT, "fopen"); \
+ pthread_mutex_unlock(&func_mutex); \
+} while(0)
+
+#define LOAD_FOPEN64_FUNC() \
+do { \
+ pthread_mutex_lock(&func_mutex); \
+ if (!_fopen64) \
+ _fopen64 = (FILE* (*)(const char *, const char*)) dlsym_fn(RTLD_NEXT, "fopen64"); \
+ pthread_mutex_unlock(&func_mutex); \
+} while(0)
+
+#define LOAD_FCLOSE_FUNC() \
+do { \
+ pthread_mutex_lock(&func_mutex); \
+ if (!_fclose) \
+ _fclose = (int (*)(FILE *)) dlsym_fn(RTLD_NEXT, "fclose"); \
+ pthread_mutex_unlock(&func_mutex); \
+} while(0)
+
+#define CONTEXT_CHECK_DEAD_GOTO(i, label) do { \
+if (!(i)->context || pa_context_get_state((i)->context) != PA_CONTEXT_READY) { \
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": Not connected: %s\n", (i)->context ? pa_strerror(pa_context_errno((i)->context)) : "NULL"); \
+ goto label; \
+} \
+} while(0)
+
+#define PLAYBACK_STREAM_CHECK_DEAD_GOTO(i, label) do { \
+if (!(i)->context || pa_context_get_state((i)->context) != PA_CONTEXT_READY || \
+ !(i)->play_stream || pa_stream_get_state((i)->play_stream) != PA_STREAM_READY) { \
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": Not connected: %s\n", (i)->context ? pa_strerror(pa_context_errno((i)->context)) : "NULL"); \
+ goto label; \
+} \
+} while(0)
+
+#define RECORD_STREAM_CHECK_DEAD_GOTO(i, label) do { \
+if (!(i)->context || pa_context_get_state((i)->context) != PA_CONTEXT_READY || \
+ !(i)->rec_stream || pa_stream_get_state((i)->rec_stream) != PA_STREAM_READY) { \
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": Not connected: %s\n", (i)->context ? pa_strerror(pa_context_errno((i)->context)) : "NULL"); \
+ goto label; \
+} \
+} while(0)
+
+static void debug(int level, const char *format, ...) PA_GCC_PRINTF_ATTR(2,3);
+
+#define DEBUG_LEVEL_ALWAYS 0
+#define DEBUG_LEVEL_NORMAL 1
+#define DEBUG_LEVEL_VERBOSE 2
+
+static void debug(int level, const char *format, ...) {
+ va_list ap;
+ const char *dlevel_s;
+ int dlevel;
+
+ dlevel_s = getenv("PADSP_DEBUG");
+ if (!dlevel_s)
+ return;
+
+ dlevel = atoi(dlevel_s);
+
+ if (dlevel < level)
+ return;
+
+ va_start(ap, format);
+ vfprintf(stderr, format, ap);
+ va_end(ap);
+}
+
+static int padsp_disabled(void) {
+ static int *sym;
+ static int sym_resolved = 0;
+
+ /* If the current process has a symbol __padsp_disabled__ we use
+ * it to detect whether we should enable our stuff or not. A
+ * program needs to be compiled with -rdynamic for this to work!
+ * The symbol must be an int containing a three bit bitmask: bit 1
+ * -> disable /dev/dsp emulation, bit 2 -> disable /dev/sndstat
+ * emulation, bit 3 -> disable /dev/mixer emulation. Hence a value
+ * of 7 disables padsp entirely. */
+
+ pthread_mutex_lock(&func_mutex);
+ if (!sym_resolved) {
+ sym = (int*) dlsym(RTLD_DEFAULT, "__padsp_disabled__");
+ sym_resolved = 1;
+ }
+ pthread_mutex_unlock(&func_mutex);
+
+ if (!sym)
+ return 0;
+
+ return *sym;
+}
+
+static int dsp_cloak_enable(void) {
+ if (padsp_disabled() & 1)
+ return 0;
+
+ if (getenv("PADSP_NO_DSP") || getenv("PULSE_INTERNAL"))
+ return 0;
+
+ return 1;
+}
+
+static int sndstat_cloak_enable(void) {
+ if (padsp_disabled() & 2)
+ return 0;
+
+ if (getenv("PADSP_NO_SNDSTAT") || getenv("PULSE_INTERNAL"))
+ return 0;
+
+ return 1;
+}
+
+static int mixer_cloak_enable(void) {
+ if (padsp_disabled() & 4)
+ return 0;
+
+ if (getenv("PADSP_NO_MIXER") || getenv("PULSE_INTERNAL"))
+ return 0;
+
+ return 1;
+}
+static pthread_key_t recursion_key;
+
+static void recursion_key_alloc(void) {
+ pthread_key_create(&recursion_key, NULL);
+}
+
+static int function_enter(void) {
+ /* Avoid recursive calls */
+ static pthread_once_t recursion_key_once = PTHREAD_ONCE_INIT;
+ pthread_once(&recursion_key_once, recursion_key_alloc);
+
+ if (pthread_getspecific(recursion_key))
+ return 0;
+
+ pthread_setspecific(recursion_key, (void*) 1);
+ return 1;
+}
+
+static void function_exit(void) {
+ pthread_setspecific(recursion_key, NULL);
+}
+
+static void fd_info_free(fd_info *i) {
+ assert(i);
+
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": freeing fd info (fd=%i)\n", i->app_fd);
+
+ dsp_drain(i);
+
+ if (i->mainloop)
+ pa_threaded_mainloop_stop(i->mainloop);
+
+ if (i->play_stream) {
+ pa_stream_disconnect(i->play_stream);
+ pa_stream_unref(i->play_stream);
+ }
+
+ if (i->rec_stream) {
+ pa_stream_disconnect(i->rec_stream);
+ pa_stream_unref(i->rec_stream);
+ }
+
+ if (i->context) {
+ pa_context_disconnect(i->context);
+ pa_context_unref(i->context);
+ }
+
+ if (i->mainloop)
+ pa_threaded_mainloop_free(i->mainloop);
+
+ if (i->app_fd >= 0) {
+ LOAD_CLOSE_FUNC();
+ _close(i->app_fd);
+ }
+
+ if (i->thread_fd >= 0) {
+ LOAD_CLOSE_FUNC();
+ _close(i->thread_fd);
+ }
+
+ free(i->buf);
+
+ pthread_mutex_destroy(&i->mutex);
+ free(i);
+}
+
+static fd_info *fd_info_ref(fd_info *i) {
+ assert(i);
+
+ pthread_mutex_lock(&i->mutex);
+ assert(i->ref >= 1);
+ i->ref++;
+
+ debug(DEBUG_LEVEL_VERBOSE, __FILE__": ref++, now %i\n", i->ref);
+ pthread_mutex_unlock(&i->mutex);
+
+ return i;
+}
+
+static void fd_info_unref(fd_info *i) {
+ int r;
+ pthread_mutex_lock(&i->mutex);
+ assert(i->ref >= 1);
+ r = --i->ref;
+ debug(DEBUG_LEVEL_VERBOSE, __FILE__": ref--, now %i\n", i->ref);
+ pthread_mutex_unlock(&i->mutex);
+
+ if (r <= 0)
+ fd_info_free(i);
+}
+
+static void context_state_cb(pa_context *c, void *userdata) {
+ fd_info *i = userdata;
+ assert(c);
+
+ switch (pa_context_get_state(c)) {
+ case PA_CONTEXT_READY:
+ case PA_CONTEXT_TERMINATED:
+ case PA_CONTEXT_FAILED:
+ pa_threaded_mainloop_signal(i->mainloop, 0);
+ break;
+
+ case PA_CONTEXT_UNCONNECTED:
+ case PA_CONTEXT_CONNECTING:
+ case PA_CONTEXT_AUTHORIZING:
+ case PA_CONTEXT_SETTING_NAME:
+ break;
+ }
+}
+
+static void reset_params(fd_info *i) {
+ assert(i);
+
+ i->sample_spec.format = PA_SAMPLE_U8;
+ i->sample_spec.channels = 1;
+ i->sample_spec.rate = 8000;
+ i->fragment_size = 0;
+ i->n_fragments = 0;
+}
+
+static const char *client_name(char *buf, size_t n) {
+ char *p;
+ const char *e;
+
+ if ((e = getenv("PADSP_CLIENT_NAME")))
+ return e;
+
+ if ((p = pa_get_binary_name_malloc())) {
+ snprintf(buf, n, "OSS Emulation[%s]", p);
+ pa_xfree(p);
+ } else
+ snprintf(buf, n, "OSS");
+
+ return buf;
+}
+
+static const char *stream_name(void) {
+ const char *e;
+
+ if ((e = getenv("PADSP_STREAM_NAME")))
+ return e;
+
+ return "Audio Stream";
+}
+
+static void atfork_prepare(void) {
+ fd_info *i;
+
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": atfork_prepare() enter\n");
+
+ function_enter();
+
+ pthread_mutex_lock(&fd_infos_mutex);
+
+ for (i = fd_infos; i; i = i->next) {
+ pthread_mutex_lock(&i->mutex);
+ pa_threaded_mainloop_lock(i->mainloop);
+ }
+
+ pthread_mutex_lock(&func_mutex);
+
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": atfork_prepare() exit\n");
+}
+
+static void atfork_parent(void) {
+ fd_info *i;
+
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": atfork_parent() enter\n");
+
+ pthread_mutex_unlock(&func_mutex);
+
+ for (i = fd_infos; i; i = i->next) {
+ pa_threaded_mainloop_unlock(i->mainloop);
+ pthread_mutex_unlock(&i->mutex);
+ }
+
+ pthread_mutex_unlock(&fd_infos_mutex);
+
+ function_exit();
+
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": atfork_parent() exit\n");
+}
+
+static void atfork_child(void) {
+ fd_info *i;
+
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": atfork_child() enter\n");
+
+ /* We do only the bare minimum to get all fds closed */
+ pthread_mutex_init(&func_mutex, NULL);
+ pthread_mutex_init(&fd_infos_mutex, NULL);
+
+ for (i = fd_infos; i; i = i->next) {
+ pthread_mutex_init(&i->mutex, NULL);
+
+ if (i->context) {
+ pa_context_disconnect(i->context);
+ pa_context_unref(i->context);
+ i->context = NULL;
+ }
+
+ if (i->play_stream) {
+ pa_stream_unref(i->play_stream);
+ i->play_stream = NULL;
+ }
+
+ if (i->rec_stream) {
+ pa_stream_unref(i->rec_stream);
+ i->rec_stream = NULL;
+ }
+
+ if (i->app_fd >= 0) {
+ LOAD_CLOSE_FUNC();
+ _close(i->app_fd);
+ i->app_fd = -1;
+ }
+
+ if (i->thread_fd >= 0) {
+ LOAD_CLOSE_FUNC();
+ _close(i->thread_fd);
+ i->thread_fd = -1;
+ }
+
+ i->unusable = 1;
+ }
+
+ function_exit();
+
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": atfork_child() exit\n");
+}
+
+static void install_atfork(void) {
+ pthread_atfork(atfork_prepare, atfork_parent, atfork_child);
+}
+
+static void stream_success_cb(pa_stream *s, int success, void *userdata) {
+ fd_info *i = userdata;
+
+ assert(s);
+ assert(i);
+
+ i->operation_success = success;
+ pa_threaded_mainloop_signal(i->mainloop, 0);
+}
+
+static void context_success_cb(pa_context *c, int success, void *userdata) {
+ fd_info *i = userdata;
+
+ assert(c);
+ assert(i);
+
+ i->operation_success = success;
+ pa_threaded_mainloop_signal(i->mainloop, 0);
+}
+
+static fd_info* fd_info_new(fd_info_type_t type, int *_errno) {
+ fd_info *i;
+ int sfds[2] = { -1, -1 };
+ char name[64];
+ static pthread_once_t install_atfork_once = PTHREAD_ONCE_INIT;
+
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": fd_info_new()\n");
+
+ signal(SIGPIPE, SIG_IGN); /* Yes, ugly as hell */
+
+ pthread_once(&install_atfork_once, install_atfork);
+
+ if (!(i = malloc(sizeof(fd_info)))) {
+ *_errno = ENOMEM;
+ goto fail;
+ }
+
+ i->app_fd = i->thread_fd = -1;
+ i->type = type;
+
+ i->mainloop = NULL;
+ i->context = NULL;
+ i->play_stream = NULL;
+ i->rec_stream = NULL;
+ i->play_precork = 0;
+ i->rec_precork = 0;
+ i->io_event = NULL;
+ i->io_flags = 0;
+ pthread_mutex_init(&i->mutex, NULL);
+ i->ref = 1;
+ i->buf = NULL;
+ i->leftover = 0;
+ i->rec_offset = 0;
+ i->unusable = 0;
+ pa_cvolume_reset(&i->sink_volume, 2);
+ pa_cvolume_reset(&i->source_volume, 2);
+ i->volume_modify_count = 0;
+ i->sink_index = (uint32_t) -1;
+ i->source_index = (uint32_t) -1;
+ i->optr_n_blocks = 0;
+ PA_LLIST_INIT(fd_info, i);
+
+ reset_params(i);
+
+ if (socketpair(AF_UNIX, SOCK_STREAM, 0, sfds) < 0) {
+ *_errno = errno;
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": socket() failed: %s\n", strerror(errno));
+ goto fail;
+ }
+
+ i->app_fd = sfds[0];
+ i->thread_fd = sfds[1];
+
+ if (!(i->mainloop = pa_threaded_mainloop_new())) {
+ *_errno = EIO;
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": pa_threaded_mainloop_new() failed\n");
+ goto fail;
+ }
+
+ if (!(i->context = pa_context_new(pa_threaded_mainloop_get_api(i->mainloop), client_name(name, sizeof(name))))) {
+ *_errno = EIO;
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": pa_context_new() failed\n");
+ goto fail;
+ }
+
+ pa_context_set_state_callback(i->context, context_state_cb, i);
+
+ if (pa_context_connect(i->context, NULL, 0, NULL) < 0) {
+ *_errno = ECONNREFUSED;
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": pa_context_connect() failed: %s\n", pa_strerror(pa_context_errno(i->context)));
+ goto fail;
+ }
+
+ pa_threaded_mainloop_lock(i->mainloop);
+
+ if (pa_threaded_mainloop_start(i->mainloop) < 0) {
+ *_errno = EIO;
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": pa_threaded_mainloop_start() failed\n");
+ goto unlock_and_fail;
+ }
+
+ /* Wait until the context is ready */
+ pa_threaded_mainloop_wait(i->mainloop);
+
+ if (pa_context_get_state(i->context) != PA_CONTEXT_READY) {
+ *_errno = ECONNREFUSED;
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": pa_context_connect() failed: %s\n", pa_strerror(pa_context_errno(i->context)));
+ goto unlock_and_fail;
+ }
+
+ pa_threaded_mainloop_unlock(i->mainloop);
+ return i;
+
+unlock_and_fail:
+
+ pa_threaded_mainloop_unlock(i->mainloop);
+
+fail:
+
+ if (i)
+ fd_info_unref(i);
+
+ return NULL;
+}
+
+static void fd_info_add_to_list(fd_info *i) {
+ assert(i);
+
+ pthread_mutex_lock(&fd_infos_mutex);
+ PA_LLIST_PREPEND(fd_info, fd_infos, i);
+ pthread_mutex_unlock(&fd_infos_mutex);
+
+ fd_info_ref(i);
+}
+
+static void fd_info_remove_from_list(fd_info *i) {
+ assert(i);
+
+ pthread_mutex_lock(&fd_infos_mutex);
+ PA_LLIST_REMOVE(fd_info, fd_infos, i);
+ pthread_mutex_unlock(&fd_infos_mutex);
+
+ fd_info_unref(i);
+}
+
+static fd_info* fd_info_find(int fd) {
+ fd_info *i;
+
+ pthread_mutex_lock(&fd_infos_mutex);
+
+ for (i = fd_infos; i; i = i->next)
+ if (i->app_fd == fd && !i->unusable) {
+ fd_info_ref(i);
+ break;
+ }
+
+ pthread_mutex_unlock(&fd_infos_mutex);
+
+ return i;
+}
+
+static void fix_metrics(fd_info *i) {
+ size_t fs;
+ char t[PA_SAMPLE_SPEC_SNPRINT_MAX];
+
+ fs = pa_frame_size(&i->sample_spec);
+
+ /* Don't fix things more than necessary */
+ if ((i->fragment_size % fs) == 0 &&
+ i->n_fragments >= 2 &&
+ i->fragment_size > 0)
+ return;
+
+ i->fragment_size = (i->fragment_size/fs)*fs;
+
+ /* Number of fragments set? */
+ if (i->n_fragments < 2) {
+ if (i->fragment_size > 0) {
+ i->n_fragments = (unsigned) (pa_bytes_per_second(&i->sample_spec) / 2 / i->fragment_size);
+ if (i->n_fragments < 2)
+ i->n_fragments = 2;
+ } else
+ i->n_fragments = 12;
+ }
+
+ /* Fragment size set? */
+ if (i->fragment_size <= 0) {
+ i->fragment_size = pa_bytes_per_second(&i->sample_spec) / 2 / i->n_fragments;
+ if (i->fragment_size < 1024)
+ i->fragment_size = 1024;
+ }
+
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": sample spec: %s\n", pa_sample_spec_snprint(t, sizeof(t), &i->sample_spec));
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": fixated metrics to %i fragments, %li bytes each.\n", i->n_fragments, (long)i->fragment_size);
+}
+
+static void stream_request_cb(pa_stream *s, size_t length, void *userdata) {
+ fd_info *i = userdata;
+ assert(s);
+
+ if (i->io_event) {
+ pa_mainloop_api *api;
+ size_t n;
+
+ api = pa_threaded_mainloop_get_api(i->mainloop);
+
+ if (s == i->play_stream) {
+ n = pa_stream_writable_size(i->play_stream);
+ if (n == (size_t)-1) {
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": pa_stream_writable_size(): %s\n",
+ pa_strerror(pa_context_errno(i->context)));
+ }
+
+ if (n >= i->fragment_size)
+ i->io_flags |= PA_IO_EVENT_INPUT;
+ else
+ i->io_flags &= ~PA_IO_EVENT_INPUT;
+ }
+
+ if (s == i->rec_stream) {
+ n = pa_stream_readable_size(i->rec_stream);
+ if (n == (size_t)-1) {
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": pa_stream_readable_size(): %s\n",
+ pa_strerror(pa_context_errno(i->context)));
+ }
+
+ if (n >= i->fragment_size)
+ i->io_flags |= PA_IO_EVENT_OUTPUT;
+ else
+ i->io_flags &= ~PA_IO_EVENT_OUTPUT;
+ }
+
+ api->io_enable(i->io_event, i->io_flags);
+ }
+}
+
+static void stream_latency_update_cb(pa_stream *s, void *userdata) {
+ fd_info *i = userdata;
+ assert(s);
+
+ pa_threaded_mainloop_signal(i->mainloop, 0);
+}
+
+static void fd_info_shutdown(fd_info *i) {
+ assert(i);
+
+ if (i->io_event) {
+ pa_mainloop_api *api;
+ api = pa_threaded_mainloop_get_api(i->mainloop);
+ api->io_free(i->io_event);
+ i->io_event = NULL;
+ i->io_flags = 0;
+ }
+
+ if (i->thread_fd >= 0) {
+ close(i->thread_fd);
+ i->thread_fd = -1;
+ }
+}
+
+static int fd_info_copy_data(fd_info *i, int force) {
+ size_t n;
+
+ if (!i->play_stream && !i->rec_stream)
+ return -1;
+
+ if ((i->play_stream) && (pa_stream_get_state(i->play_stream) == PA_STREAM_READY)) {
+ n = pa_stream_writable_size(i->play_stream);
+
+ if (n == (size_t)-1) {
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": pa_stream_writable_size(): %s\n",
+ pa_strerror(pa_context_errno(i->context)));
+ return -1;
+ }
+
+ while (n >= i->fragment_size || force) {
+ ssize_t r;
+ size_t to_write;
+
+ if (!i->buf) {
+ if (!(i->buf = malloc(i->fragment_size))) {
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": malloc() failed.\n");
+ return -1;
+ }
+
+ i->leftover = 0;
+ }
+
+ if ((r = read(i->thread_fd, ((uint8_t *) i->buf) + i->leftover, i->fragment_size - i->leftover)) <= 0) {
+
+ if (errno == EAGAIN)
+ break;
+
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": read(): %s\n", r == 0 ? "EOF" : strerror(errno));
+ return -1;
+ }
+
+ to_write = pa_frame_align(r + i->leftover, &i->sample_spec);
+
+ if (pa_stream_write(i->play_stream, i->buf, to_write, NULL, 0LL, PA_SEEK_RELATIVE) < 0) {
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": pa_stream_write(): %s\n", pa_strerror(pa_context_errno(i->context)));
+ return -1;
+ }
+
+ i->leftover += r - to_write;
+ if (i->leftover)
+ memmove(i->buf, ((uint8_t *) i->buf) + to_write, i->leftover);
+
+ assert(n >= (size_t) to_write);
+ n -= (size_t) to_write;
+ }
+
+ if (n >= i->fragment_size)
+ i->io_flags |= PA_IO_EVENT_INPUT;
+ else
+ i->io_flags &= ~PA_IO_EVENT_INPUT;
+ }
+
+ if ((i->rec_stream) && (pa_stream_get_state(i->rec_stream) == PA_STREAM_READY)) {
+ n = pa_stream_readable_size(i->rec_stream);
+
+ if (n == (size_t)-1) {
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": pa_stream_readable_size(): %s\n",
+ pa_strerror(pa_context_errno(i->context)));
+ return -1;
+ }
+
+ while (n >= i->fragment_size || force) {
+ ssize_t r;
+ const void *data;
+ const char *buf;
+ size_t len;
+
+ if (pa_stream_peek(i->rec_stream, &data, &len) < 0) {
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": pa_stream_peek(): %s\n", pa_strerror(pa_context_errno(i->context)));
+ return -1;
+ }
+
+ if (len <= 0)
+ break;
+
+ if (!data) {
+ /* Maybe we should generate silence here, but I'm lazy and
+ * I'll just skip any holes in the stream. */
+ if (pa_stream_drop(i->rec_stream) < 0) {
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": pa_stream_drop(): %s\n", pa_strerror(pa_context_errno(i->context)));
+ return -1;
+ }
+
+ assert(n >= len);
+ n -= len;
+ continue;
+ }
+
+ buf = (const char*)data + i->rec_offset;
+
+ if ((r = write(i->thread_fd, buf, len - i->rec_offset)) <= 0) {
+
+ if (errno == EAGAIN)
+ break;
+
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": write(): %s\n", strerror(errno));
+ return -1;
+ }
+
+ assert((size_t)r <= len - i->rec_offset);
+ i->rec_offset += (size_t) r;
+
+ if (i->rec_offset == len) {
+ if (pa_stream_drop(i->rec_stream) < 0) {
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": pa_stream_drop(): %s\n", pa_strerror(pa_context_errno(i->context)));
+ return -1;
+ }
+ i->rec_offset = 0;
+ }
+
+ assert(n >= (size_t) r);
+ n -= (size_t) r;
+ }
+
+ if (n >= i->fragment_size)
+ i->io_flags |= PA_IO_EVENT_OUTPUT;
+ else
+ i->io_flags &= ~PA_IO_EVENT_OUTPUT;
+ }
+
+ if (i->io_event) {
+ pa_mainloop_api *api;
+
+ api = pa_threaded_mainloop_get_api(i->mainloop);
+ api->io_enable(i->io_event, i->io_flags);
+ }
+
+ /* So, we emptied the socket now, let's tell dsp_empty_socket()
+ * about this */
+ pa_threaded_mainloop_signal(i->mainloop, 0);
+
+ return 0;
+}
+
+static void stream_state_cb(pa_stream *s, void * userdata) {
+ fd_info *i = userdata;
+ assert(s);
+
+ switch (pa_stream_get_state(s)) {
+
+ case PA_STREAM_READY:
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": stream established.\n");
+ break;
+
+ case PA_STREAM_FAILED:
+ if (s == i->play_stream) {
+ debug(DEBUG_LEVEL_NORMAL,
+ __FILE__": pa_stream_connect_playback() failed: %s\n",
+ pa_strerror(pa_context_errno(i->context)));
+ pa_stream_unref(i->play_stream);
+ i->play_stream = NULL;
+ } else if (s == i->rec_stream) {
+ debug(DEBUG_LEVEL_NORMAL,
+ __FILE__": pa_stream_connect_record() failed: %s\n",
+ pa_strerror(pa_context_errno(i->context)));
+ pa_stream_unref(i->rec_stream);
+ i->rec_stream = NULL;
+ }
+ fd_info_shutdown(i);
+ break;
+
+ case PA_STREAM_TERMINATED:
+ case PA_STREAM_UNCONNECTED:
+ case PA_STREAM_CREATING:
+ break;
+ }
+}
+
+static int create_playback_stream(fd_info *i) {
+ pa_buffer_attr attr;
+ int n, flags;
+
+ assert(i);
+
+ fix_metrics(i);
+
+ if (!(i->play_stream = pa_stream_new(i->context, stream_name(), &i->sample_spec, NULL))) {
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": pa_stream_new() failed: %s\n", pa_strerror(pa_context_errno(i->context)));
+ goto fail;
+ }
+
+ pa_stream_set_state_callback(i->play_stream, stream_state_cb, i);
+ pa_stream_set_write_callback(i->play_stream, stream_request_cb, i);
+ pa_stream_set_latency_update_callback(i->play_stream, stream_latency_update_cb, i);
+
+ memset(&attr, 0, sizeof(attr));
+ attr.maxlength = (uint32_t) (i->fragment_size * (i->n_fragments+1));
+ attr.tlength = (uint32_t) (i->fragment_size * i->n_fragments);
+ attr.prebuf = (uint32_t) i->fragment_size;
+ attr.minreq = (uint32_t) i->fragment_size;
+
+ flags = PA_STREAM_INTERPOLATE_TIMING|PA_STREAM_AUTO_TIMING_UPDATE|PA_STREAM_EARLY_REQUESTS;
+ if (i->play_precork) {
+ flags |= PA_STREAM_START_CORKED;
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": creating stream corked\n");
+ }
+ if (pa_stream_connect_playback(i->play_stream, NULL, &attr, flags, NULL, NULL) < 0) {
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": pa_stream_connect_playback() failed: %s\n", pa_strerror(pa_context_errno(i->context)));
+ goto fail;
+ }
+
+ n = (int) i->fragment_size;
+ setsockopt(i->app_fd, SOL_SOCKET, SO_SNDBUF, &n, sizeof(n));
+ n = (int) i->fragment_size;
+ setsockopt(i->thread_fd, SOL_SOCKET, SO_RCVBUF, &n, sizeof(n));
+
+ return 0;
+
+fail:
+ return -1;
+}
+
+static int create_record_stream(fd_info *i) {
+ pa_buffer_attr attr;
+ int n, flags;
+
+ assert(i);
+
+ fix_metrics(i);
+
+ if (!(i->rec_stream = pa_stream_new(i->context, stream_name(), &i->sample_spec, NULL))) {
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": pa_stream_new() failed: %s\n", pa_strerror(pa_context_errno(i->context)));
+ goto fail;
+ }
+
+ pa_stream_set_state_callback(i->rec_stream, stream_state_cb, i);
+ pa_stream_set_read_callback(i->rec_stream, stream_request_cb, i);
+ pa_stream_set_latency_update_callback(i->rec_stream, stream_latency_update_cb, i);
+
+ memset(&attr, 0, sizeof(attr));
+ attr.maxlength = (uint32_t) (i->fragment_size * (i->n_fragments+1));
+ attr.fragsize = (uint32_t) i->fragment_size;
+
+ flags = PA_STREAM_INTERPOLATE_TIMING|PA_STREAM_AUTO_TIMING_UPDATE;
+ if (i->rec_precork) {
+ flags |= PA_STREAM_START_CORKED;
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": creating stream corked\n");
+ }
+ if (pa_stream_connect_record(i->rec_stream, NULL, &attr, flags) < 0) {
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": pa_stream_connect_record() failed: %s\n", pa_strerror(pa_context_errno(i->context)));
+ goto fail;
+ }
+
+ n = (int) i->fragment_size;
+ setsockopt(i->app_fd, SOL_SOCKET, SO_RCVBUF, &n, sizeof(n));
+ n = (int) i->fragment_size;
+ setsockopt(i->thread_fd, SOL_SOCKET, SO_SNDBUF, &n, sizeof(n));
+
+ return 0;
+
+fail:
+ return -1;
+}
+
+static void free_streams(fd_info *i) {
+ assert(i);
+
+ if (i->play_stream) {
+ pa_stream_disconnect(i->play_stream);
+ pa_stream_unref(i->play_stream);
+ i->play_stream = NULL;
+ i->io_flags |= PA_IO_EVENT_INPUT;
+ }
+
+ if (i->rec_stream) {
+ pa_stream_disconnect(i->rec_stream);
+ pa_stream_unref(i->rec_stream);
+ i->rec_stream = NULL;
+ i->io_flags |= PA_IO_EVENT_OUTPUT;
+ }
+
+ if (i->io_event) {
+ pa_mainloop_api *api;
+
+ api = pa_threaded_mainloop_get_api(i->mainloop);
+ api->io_enable(i->io_event, i->io_flags);
+ }
+}
+
+static void io_event_cb(pa_mainloop_api *api, pa_io_event *e, int fd, pa_io_event_flags_t flags, void *userdata) {
+ fd_info *i = userdata;
+
+ pa_threaded_mainloop_signal(i->mainloop, 0);
+
+ if (flags & PA_IO_EVENT_INPUT) {
+
+ if (!i->play_stream) {
+ if (create_playback_stream(i) < 0)
+ goto fail;
+ } else {
+ if (fd_info_copy_data(i, 0) < 0)
+ goto fail;
+ }
+
+ } else if (flags & PA_IO_EVENT_OUTPUT) {
+
+ if (!i->rec_stream) {
+ if (create_record_stream(i) < 0)
+ goto fail;
+ } else {
+ if (fd_info_copy_data(i, 0) < 0)
+ goto fail;
+ }
+
+ } else if (flags & (PA_IO_EVENT_HANGUP|PA_IO_EVENT_ERROR))
+ goto fail;
+
+ return;
+
+fail:
+ /* We can't do anything better than removing the event source */
+ fd_info_shutdown(i);
+}
+
+static int dsp_open(int flags, int *_errno) {
+ fd_info *i;
+ pa_mainloop_api *api;
+ int ret;
+ int f;
+
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": dsp_open()\n");
+
+ if (!(i = fd_info_new(FD_INFO_STREAM, _errno)))
+ return -1;
+
+ if ((flags & O_NONBLOCK) == O_NONBLOCK) {
+ if ((f = fcntl(i->app_fd, F_GETFL)) >= 0)
+ fcntl(i->app_fd, F_SETFL, f|O_NONBLOCK);
+ }
+ if ((f = fcntl(i->thread_fd, F_GETFL)) >= 0)
+ fcntl(i->thread_fd, F_SETFL, f|O_NONBLOCK);
+
+ fcntl(i->app_fd, F_SETFD, FD_CLOEXEC);
+ fcntl(i->thread_fd, F_SETFD, FD_CLOEXEC);
+
+ pa_threaded_mainloop_lock(i->mainloop);
+ api = pa_threaded_mainloop_get_api(i->mainloop);
+
+ switch (flags & O_ACCMODE) {
+ case O_RDONLY:
+ i->io_flags = PA_IO_EVENT_OUTPUT;
+ shutdown(i->thread_fd, SHUT_RD);
+ shutdown(i->app_fd, SHUT_WR);
+ break;
+ case O_WRONLY:
+ i->io_flags = PA_IO_EVENT_INPUT;
+ shutdown(i->thread_fd, SHUT_WR);
+ shutdown(i->app_fd, SHUT_RD);
+ break;
+ case O_RDWR:
+ i->io_flags = PA_IO_EVENT_INPUT | PA_IO_EVENT_OUTPUT;
+ break;
+ default:
+ pa_threaded_mainloop_unlock(i->mainloop);
+ fd_info_unref(i);
+ *_errno = EIO;
+ return -1;
+ }
+
+ if (!(i->io_event = api->io_new(api, i->thread_fd, i->io_flags, io_event_cb, i)))
+ goto fail;
+
+ pa_threaded_mainloop_unlock(i->mainloop);
+
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": dsp_open() succeeded, fd=%i\n", i->app_fd);
+
+ fd_info_add_to_list(i);
+ ret = i->app_fd;
+ fd_info_unref(i);
+
+ return ret;
+
+fail:
+ pa_threaded_mainloop_unlock(i->mainloop);
+
+ if (i)
+ fd_info_unref(i);
+
+ *_errno = EIO;
+
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": dsp_open() failed\n");
+
+ return -1;
+}
+
+static void sink_info_cb(pa_context *context, const pa_sink_info *si, int eol, void *userdata) {
+ fd_info *i = userdata;
+
+ if (eol < 0) {
+ i->operation_success = 0;
+ pa_threaded_mainloop_signal(i->mainloop, 0);
+ return;
+ }
+
+ if (eol)
+ return;
+
+ if (!pa_cvolume_equal(&i->sink_volume, &si->volume))
+ i->volume_modify_count++;
+
+ i->sink_volume = si->volume;
+ i->sink_index = si->index;
+
+ i->operation_success = 1;
+ pa_threaded_mainloop_signal(i->mainloop, 0);
+}
+
+static void source_info_cb(pa_context *context, const pa_source_info *si, int eol, void *userdata) {
+ fd_info *i = userdata;
+
+ if (eol < 0) {
+ i->operation_success = 0;
+ pa_threaded_mainloop_signal(i->mainloop, 0);
+ return;
+ }
+
+ if (eol)
+ return;
+
+ if (!pa_cvolume_equal(&i->source_volume, &si->volume))
+ i->volume_modify_count++;
+
+ i->source_volume = si->volume;
+ i->source_index = si->index;
+
+ i->operation_success = 1;
+ pa_threaded_mainloop_signal(i->mainloop, 0);
+}
+
+static void subscribe_cb(pa_context *context, pa_subscription_event_type_t t, uint32_t idx, void *userdata) {
+ fd_info *i = userdata;
+ pa_operation *o = NULL;
+
+ if (i->sink_index != idx)
+ return;
+
+ if ((t & PA_SUBSCRIPTION_EVENT_TYPE_MASK) != PA_SUBSCRIPTION_EVENT_CHANGE)
+ return;
+
+ if (!(o = pa_context_get_sink_info_by_index(i->context, i->sink_index, sink_info_cb, i))) {
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": Failed to get sink info: %s", pa_strerror(pa_context_errno(i->context)));
+ return;
+ }
+
+ pa_operation_unref(o);
+}
+
+static int mixer_open(int flags, int *_errno) {
+ fd_info *i;
+ pa_operation *o = NULL;
+ int ret;
+
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": mixer_open()\n");
+
+ if (!(i = fd_info_new(FD_INFO_MIXER, _errno)))
+ return -1;
+
+ pa_threaded_mainloop_lock(i->mainloop);
+
+ pa_context_set_subscribe_callback(i->context, subscribe_cb, i);
+
+ if (!(o = pa_context_subscribe(i->context, PA_SUBSCRIPTION_MASK_SINK | PA_SUBSCRIPTION_MASK_SOURCE, context_success_cb, i))) {
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": Failed to subscribe to events: %s", pa_strerror(pa_context_errno(i->context)));
+ *_errno = EIO;
+ goto fail;
+ }
+
+ i->operation_success = 0;
+ while (pa_operation_get_state(o) != PA_OPERATION_DONE) {
+ pa_threaded_mainloop_wait(i->mainloop);
+ CONTEXT_CHECK_DEAD_GOTO(i, fail);
+ }
+
+ pa_operation_unref(o);
+ o = NULL;
+
+ if (!i->operation_success) {
+ debug(DEBUG_LEVEL_NORMAL, __FILE__":Failed to subscribe to events: %s", pa_strerror(pa_context_errno(i->context)));
+ *_errno = EIO;
+ goto fail;
+ }
+
+ /* Get sink info */
+
+ if (!(o = pa_context_get_sink_info_by_name(i->context, NULL, sink_info_cb, i))) {
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": Failed to get sink info: %s", pa_strerror(pa_context_errno(i->context)));
+ *_errno = EIO;
+ goto fail;
+ }
+
+ i->operation_success = 0;
+ while (pa_operation_get_state(o) != PA_OPERATION_DONE) {
+ pa_threaded_mainloop_wait(i->mainloop);
+ CONTEXT_CHECK_DEAD_GOTO(i, fail);
+ }
+
+ pa_operation_unref(o);
+ o = NULL;
+
+ if (!i->operation_success) {
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": Failed to get sink info: %s", pa_strerror(pa_context_errno(i->context)));
+ *_errno = EIO;
+ goto fail;
+ }
+
+ /* Get source info */
+
+ if (!(o = pa_context_get_source_info_by_name(i->context, NULL, source_info_cb, i))) {
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": Failed to get source info: %s", pa_strerror(pa_context_errno(i->context)));
+ *_errno = EIO;
+ goto fail;
+ }
+
+ i->operation_success = 0;
+ while (pa_operation_get_state(o) != PA_OPERATION_DONE) {
+ pa_threaded_mainloop_wait(i->mainloop);
+ CONTEXT_CHECK_DEAD_GOTO(i, fail);
+ }
+
+ pa_operation_unref(o);
+ o = NULL;
+
+ if (!i->operation_success) {
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": Failed to get source info: %s", pa_strerror(pa_context_errno(i->context)));
+ *_errno = EIO;
+ goto fail;
+ }
+
+ pa_threaded_mainloop_unlock(i->mainloop);
+
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": mixer_open() succeeded, fd=%i\n", i->app_fd);
+
+ fd_info_add_to_list(i);
+ ret = i->app_fd;
+ fd_info_unref(i);
+
+ return ret;
+
+fail:
+ if (o)
+ pa_operation_unref(o);
+
+ pa_threaded_mainloop_unlock(i->mainloop);
+
+ if (i)
+ fd_info_unref(i);
+
+ *_errno = EIO;
+
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": mixer_open() failed\n");
+
+ return -1;
+}
+
+static int sndstat_open(int flags, int *_errno) {
+ static const char sndstat[] =
+ "Sound Driver:3.8.1a-980706 (PulseAudio Virtual OSS)\n"
+ "Kernel: POSIX\n"
+ "Config options: 0\n"
+ "\n"
+ "Installed drivers:\n"
+ "Type 255: PulseAudio Virtual OSS\n"
+ "\n"
+ "Card config:\n"
+ "PulseAudio Virtual OSS\n"
+ "\n"
+ "Audio devices:\n"
+ "0: PulseAudio Virtual OSS\n"
+ "\n"
+ "Synth devices: NOT ENABLED IN CONFIG\n"
+ "\n"
+ "Midi devices:\n"
+ "\n"
+ "Timers:\n"
+ "\n"
+ "Mixers:\n"
+ "0: PulseAudio Virtual OSS\n";
+
+ char *fn;
+ mode_t u;
+ int fd = -1;
+ int e;
+
+ fn = pa_sprintf_malloc("%s" PA_PATH_SEP "padsp-sndstat-XXXXXX", pa_get_temp_dir());
+
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": sndstat_open()\n");
+
+ if (flags != O_RDONLY
+#ifdef O_LARGEFILE
+ && flags != (O_RDONLY|O_LARGEFILE)
+#endif
+ ) {
+ *_errno = EACCES;
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": bad access!\n");
+ goto fail;
+ }
+
+ u = umask(0077);
+ fd = mkstemp(fn);
+ e = errno;
+ umask(u);
+
+ if (fd < 0) {
+ *_errno = e;
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": mkstemp() failed: %s\n", strerror(errno));
+ goto fail;
+ }
+
+ unlink(fn);
+ pa_xfree(fn);
+ fn = NULL;
+
+ if (write(fd, sndstat, sizeof(sndstat) -1) != sizeof(sndstat)-1) {
+ *_errno = errno;
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": write() failed: %s\n", strerror(errno));
+ goto fail;
+ }
+
+ if (lseek(fd, SEEK_SET, 0) < 0) {
+ *_errno = errno;
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": lseek() failed: %s\n", strerror(errno));
+ goto fail;
+ }
+
+ return fd;
+
+fail:
+ pa_xfree(fn);
+ if (fd >= 0)
+ close(fd);
+ return -1;
+}
+
+static int real_open(const char *filename, int flags, mode_t mode) {
+ int r, _errno = 0;
+
+ debug(DEBUG_LEVEL_VERBOSE, __FILE__": open(%s)\n", filename?filename:"NULL");
+
+ if (!function_enter()) {
+ LOAD_OPEN_FUNC();
+ return _open(filename, flags, mode);
+ }
+
+ if (filename && dsp_cloak_enable() && (pa_streq(filename, "/dev/dsp") || pa_streq(filename, "/dev/adsp") || pa_streq(filename, "/dev/audio")))
+ r = dsp_open(flags, &_errno);
+ else if (filename && mixer_cloak_enable() && pa_streq(filename, "/dev/mixer"))
+ r = mixer_open(flags, &_errno);
+ else if (filename && sndstat_cloak_enable() && pa_streq(filename, "/dev/sndstat"))
+ r = sndstat_open(flags, &_errno);
+ else {
+ function_exit();
+ LOAD_OPEN_FUNC();
+ return _open(filename, flags, mode);
+ }
+
+ function_exit();
+
+ if (_errno)
+ errno = _errno;
+
+ return r;
+}
+
+int open(const char *filename, int flags, ...) {
+ va_list args;
+ mode_t mode = 0;
+
+ if (flags & O_CREAT) {
+ va_start(args, flags);
+ if (sizeof(mode_t) < sizeof(int))
+ mode = (mode_t) va_arg(args, int);
+ else
+ mode = va_arg(args, mode_t);
+ va_end(args);
+ }
+
+ return real_open(filename, flags, mode);
+}
+
+static bool is_audio_device_node(const char *path) {
+ return
+ pa_streq(path, "/dev/dsp") ||
+ pa_streq(path, "/dev/adsp") ||
+ pa_streq(path, "/dev/audio") ||
+ pa_streq(path, "/dev/sndstat") ||
+ pa_streq(path, "/dev/mixer");
+}
+
+int __open_2(const char *filename, int flags) {
+ debug(DEBUG_LEVEL_VERBOSE, __FILE__": __open_2(%s)\n", filename?filename:"NULL");
+
+ if ((flags & O_CREAT) ||
+ !filename ||
+ !is_audio_device_node(filename)) {
+ LOAD___OPEN_2_FUNC();
+ return ___open_2(filename, flags);
+ }
+ return real_open(filename, flags, 0);
+}
+
+static int mixer_ioctl(fd_info *i, unsigned long request, void*argp, int *_errno) {
+ int ret = -1;
+
+ switch (request) {
+ case SOUND_MIXER_READ_DEVMASK :
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": SOUND_MIXER_READ_DEVMASK\n");
+
+ *(int*) argp = SOUND_MASK_PCM | SOUND_MASK_IGAIN;
+ break;
+
+ case SOUND_MIXER_READ_RECMASK :
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": SOUND_MIXER_READ_RECMASK\n");
+
+ *(int*) argp = SOUND_MASK_IGAIN;
+ break;
+
+ case SOUND_MIXER_READ_STEREODEVS:
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": SOUND_MIXER_READ_STEREODEVS\n");
+
+ pa_threaded_mainloop_lock(i->mainloop);
+ *(int*) argp = 0;
+ if (i->sink_volume.channels > 1)
+ *(int*) argp |= SOUND_MASK_PCM;
+ if (i->source_volume.channels > 1)
+ *(int*) argp |= SOUND_MASK_IGAIN;
+ pa_threaded_mainloop_unlock(i->mainloop);
+
+ break;
+
+ case SOUND_MIXER_READ_RECSRC:
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": SOUND_MIXER_READ_RECSRC\n");
+
+ *(int*) argp = SOUND_MASK_IGAIN;
+ break;
+
+ case SOUND_MIXER_WRITE_RECSRC:
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": SOUND_MIXER_WRITE_RECSRC\n");
+ break;
+
+ case SOUND_MIXER_READ_CAPS:
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": SOUND_MIXER_READ_CAPS\n");
+
+ *(int*) argp = 0;
+ break;
+
+ case SOUND_MIXER_READ_PCM:
+ case SOUND_MIXER_READ_IGAIN: {
+ pa_cvolume *v;
+
+ if (request == SOUND_MIXER_READ_PCM)
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": SOUND_MIXER_READ_PCM\n");
+ else
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": SOUND_MIXER_READ_IGAIN\n");
+
+ pa_threaded_mainloop_lock(i->mainloop);
+
+ if (request == SOUND_MIXER_READ_PCM)
+ v = &i->sink_volume;
+ else
+ v = &i->source_volume;
+
+ *(int*) argp =
+ ((v->values[0]*100/PA_VOLUME_NORM)) |
+ ((v->values[v->channels > 1 ? 1 : 0]*100/PA_VOLUME_NORM) << 8);
+
+ pa_threaded_mainloop_unlock(i->mainloop);
+
+ break;
+ }
+
+ case SOUND_MIXER_WRITE_PCM:
+ case SOUND_MIXER_WRITE_IGAIN: {
+ pa_cvolume v, *pv;
+
+ if (request == SOUND_MIXER_WRITE_PCM)
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": SOUND_MIXER_WRITE_PCM\n");
+ else
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": SOUND_MIXER_WRITE_IGAIN\n");
+
+ pa_threaded_mainloop_lock(i->mainloop);
+
+ if (request == SOUND_MIXER_WRITE_PCM) {
+ v = i->sink_volume;
+ pv = &i->sink_volume;
+ } else {
+ v = i->source_volume;
+ pv = &i->source_volume;
+ }
+
+ pv->values[0] = ((*(int*) argp & 0xFF)*PA_VOLUME_NORM)/100;
+ pv->values[1] = ((*(int*) argp >> 8)*PA_VOLUME_NORM)/100;
+
+ if (!pa_cvolume_equal(pv, &v)) {
+ pa_operation *o;
+
+ if (request == SOUND_MIXER_WRITE_PCM)
+ o = pa_context_set_sink_volume_by_index(i->context, i->sink_index, pv, context_success_cb, i);
+ else
+ o = pa_context_set_source_volume_by_index(i->context, i->source_index, pv, context_success_cb, i);
+
+ if (!o)
+ debug(DEBUG_LEVEL_NORMAL, __FILE__":Failed set volume: %s", pa_strerror(pa_context_errno(i->context)));
+ else {
+
+ i->operation_success = 0;
+ while (pa_operation_get_state(o) != PA_OPERATION_DONE) {
+ CONTEXT_CHECK_DEAD_GOTO(i, exit_loop);
+
+ pa_threaded_mainloop_wait(i->mainloop);
+ }
+ exit_loop:
+
+ if (!i->operation_success)
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": Failed to set volume: %s\n", pa_strerror(pa_context_errno(i->context)));
+
+ pa_operation_unref(o);
+ }
+
+ /* We don't wait for completion here */
+ i->volume_modify_count++;
+ }
+
+ pa_threaded_mainloop_unlock(i->mainloop);
+
+ break;
+ }
+
+ case SOUND_MIXER_INFO: {
+ mixer_info *mi = argp;
+
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": SOUND_MIXER_INFO\n");
+
+ memset(mi, 0, sizeof(mixer_info));
+ strncpy(mi->id, "PULSEAUDIO", sizeof(mi->id));
+ strncpy(mi->name, "PulseAudio Virtual OSS", sizeof(mi->name));
+ pa_threaded_mainloop_lock(i->mainloop);
+ mi->modify_counter = i->volume_modify_count;
+ pa_threaded_mainloop_unlock(i->mainloop);
+ break;
+ }
+
+ default:
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": unknown ioctl 0x%08lx\n", request);
+
+ *_errno = EINVAL;
+ goto fail;
+ }
+
+ ret = 0;
+
+fail:
+
+ return ret;
+}
+
+static int map_format(int *fmt, pa_sample_spec *ss) {
+
+ switch (*fmt) {
+ case AFMT_MU_LAW:
+ ss->format = PA_SAMPLE_ULAW;
+ break;
+
+ case AFMT_A_LAW:
+ ss->format = PA_SAMPLE_ALAW;
+ break;
+
+ case AFMT_S8:
+ *fmt = AFMT_U8;
+ /* fall through */
+ case AFMT_U8:
+ ss->format = PA_SAMPLE_U8;
+ break;
+
+ case AFMT_U16_BE:
+ *fmt = AFMT_S16_BE;
+ /* fall through */
+ case AFMT_S16_BE:
+ ss->format = PA_SAMPLE_S16BE;
+ break;
+
+ case AFMT_U16_LE:
+ *fmt = AFMT_S16_LE;
+ /* fall through */
+ case AFMT_S16_LE:
+ ss->format = PA_SAMPLE_S16LE;
+ break;
+
+ default:
+ ss->format = PA_SAMPLE_S16NE;
+ *fmt = AFMT_S16_NE;
+ break;
+ }
+
+ return 0;
+}
+
+static int map_format_back(pa_sample_format_t format) {
+ switch (format) {
+ case PA_SAMPLE_S16LE: return AFMT_S16_LE;
+ case PA_SAMPLE_S16BE: return AFMT_S16_BE;
+ case PA_SAMPLE_ULAW: return AFMT_MU_LAW;
+ case PA_SAMPLE_ALAW: return AFMT_A_LAW;
+ case PA_SAMPLE_U8: return AFMT_U8;
+ default:
+ abort();
+ }
+}
+
+static int dsp_flush_fd(int fd) {
+#ifdef SIOCINQ
+ int l;
+
+ if (ioctl(fd, SIOCINQ, &l) < 0) {
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": SIOCINQ: %s\n", strerror(errno));
+ return -1;
+ }
+
+ while (l > 0) {
+ char buf[1024];
+ size_t k;
+ ssize_t r;
+
+ k = (size_t) l > sizeof(buf) ? sizeof(buf) : (size_t) l;
+ r = read(fd, buf, k);
+ if (r < 0) {
+ if (errno == EAGAIN)
+ break;
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": read(): %s\n", strerror(errno));
+ return -1;
+ } else if (r == 0)
+ break;
+ l -= r;
+ }
+
+ return 0;
+#else
+# warning "Your platform does not support SIOCINQ, something might not work as intended."
+ return 0;
+#endif
+}
+
+static int dsp_flush_socket(fd_info *i) {
+ int res = 0;
+
+ if ((i->thread_fd < 0) && (i->app_fd < 0))
+ return -1;
+
+ if (i->thread_fd >= 0)
+ res = dsp_flush_fd(i->thread_fd);
+
+ if (res < 0)
+ return res;
+
+ if (i->app_fd >= 0)
+ res = dsp_flush_fd(i->app_fd);
+
+ if (res < 0)
+ return res;
+
+ return 0;
+}
+
+static int dsp_empty_socket(fd_info *i) {
+#ifdef SIOCINQ
+ int ret = -1;
+
+ /* Empty the socket */
+ for (;;) {
+ int l;
+
+ if (i->thread_fd < 0)
+ break;
+
+ if (ioctl(i->thread_fd, SIOCINQ, &l) < 0) {
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": SIOCINQ: %s\n", strerror(errno));
+ break;
+ }
+
+ if (!l) {
+ ret = 0;
+ break;
+ }
+
+ pa_threaded_mainloop_wait(i->mainloop);
+ }
+
+ return ret;
+#else
+# warning "Your platform does not support SIOCINQ, something might not work as intended."
+ return 0;
+#endif
+}
+
+static int dsp_drain(fd_info *i) {
+ pa_operation *o = NULL;
+ int r = -1;
+
+ if (!i->mainloop)
+ return 0;
+
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": Draining.\n");
+
+ pa_threaded_mainloop_lock(i->mainloop);
+
+ if (dsp_empty_socket(i) < 0)
+ goto fail;
+
+ if (!i->play_stream)
+ goto fail;
+
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": Really draining.\n");
+
+ if (!(o = pa_stream_drain(i->play_stream, stream_success_cb, i))) {
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": pa_stream_drain(): %s\n", pa_strerror(pa_context_errno(i->context)));
+ goto fail;
+ }
+
+ i->operation_success = 0;
+ while (pa_operation_get_state(o) != PA_OPERATION_DONE) {
+ PLAYBACK_STREAM_CHECK_DEAD_GOTO(i, fail);
+
+ pa_threaded_mainloop_wait(i->mainloop);
+ }
+
+ if (!i->operation_success) {
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": pa_stream_drain() 2: %s\n", pa_strerror(pa_context_errno(i->context)));
+ goto fail;
+ }
+
+ r = 0;
+
+fail:
+
+ if (o)
+ pa_operation_unref(o);
+
+ pa_threaded_mainloop_unlock(i->mainloop);
+
+ return r;
+}
+
+static int dsp_trigger(fd_info *i) {
+ pa_operation *o = NULL;
+ int r = -1;
+
+ if (!i->play_stream)
+ return 0;
+
+ pa_threaded_mainloop_lock(i->mainloop);
+
+ if (dsp_empty_socket(i) < 0)
+ goto fail;
+
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": Triggering.\n");
+
+ if (!(o = pa_stream_trigger(i->play_stream, stream_success_cb, i))) {
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": pa_stream_trigger(): %s\n", pa_strerror(pa_context_errno(i->context)));
+ goto fail;
+ }
+
+ i->operation_success = 0;
+ while (pa_operation_get_state(o) != PA_OPERATION_DONE) {
+ PLAYBACK_STREAM_CHECK_DEAD_GOTO(i, fail);
+
+ pa_threaded_mainloop_wait(i->mainloop);
+ }
+
+ if (!i->operation_success) {
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": pa_stream_trigger(): %s\n", pa_strerror(pa_context_errno(i->context)));
+ goto fail;
+ }
+
+ r = 0;
+
+fail:
+
+ if (o)
+ pa_operation_unref(o);
+
+ pa_threaded_mainloop_unlock(i->mainloop);
+
+ return r;
+}
+
+static int dsp_cork(fd_info *i, pa_stream *s, int b) {
+ pa_operation *o = NULL;
+ int r = -1;
+
+ pa_threaded_mainloop_lock(i->mainloop);
+
+ if (!(o = pa_stream_cork(s, b, stream_success_cb, i))) {
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": pa_stream_cork(): %s\n", pa_strerror(pa_context_errno(i->context)));
+ goto fail;
+ }
+
+ i->operation_success = 0;
+ while (pa_operation_get_state(o) != PA_OPERATION_DONE) {
+ if (s == i->play_stream)
+ PLAYBACK_STREAM_CHECK_DEAD_GOTO(i, fail);
+ else if (s == i->rec_stream)
+ RECORD_STREAM_CHECK_DEAD_GOTO(i, fail);
+
+ pa_threaded_mainloop_wait(i->mainloop);
+ }
+
+ if (!i->operation_success) {
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": pa_stream_cork(): %s\n", pa_strerror(pa_context_errno(i->context)));
+ goto fail;
+ }
+
+ r = 0;
+
+fail:
+
+ if (o)
+ pa_operation_unref(o);
+
+ pa_threaded_mainloop_unlock(i->mainloop);
+
+ return r;
+}
+
+static int dsp_ioctl(fd_info *i, unsigned long request, void*argp, int *_errno) {
+ int ret = -1;
+
+ if (i->thread_fd == -1) {
+ /*
+ * We've encountered some fatal error and are just waiting
+ * for a close.
+ */
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": got ioctl 0x%08lx in fatal error state\n", request);
+ *_errno = EIO;
+ return -1;
+ }
+
+ switch (request) {
+ case SNDCTL_DSP_SETFMT: {
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": SNDCTL_DSP_SETFMT: %i\n", *(int*) argp);
+
+ pa_threaded_mainloop_lock(i->mainloop);
+
+ if (*(int*) argp == AFMT_QUERY)
+ *(int*) argp = map_format_back(i->sample_spec.format);
+ else {
+ map_format((int*) argp, &i->sample_spec);
+ free_streams(i);
+ }
+
+ pa_threaded_mainloop_unlock(i->mainloop);
+ break;
+ }
+
+ case SNDCTL_DSP_SPEED: {
+ pa_sample_spec ss;
+ int valid;
+ char t[256];
+
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": SNDCTL_DSP_SPEED: %i\n", *(int*) argp);
+
+ pa_threaded_mainloop_lock(i->mainloop);
+
+ ss = i->sample_spec;
+ ss.rate = *(int*) argp;
+
+ if ((valid = pa_sample_spec_valid(&ss))) {
+ i->sample_spec = ss;
+ free_streams(i);
+ }
+
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": ss: %s\n", pa_sample_spec_snprint(t, sizeof(t), &i->sample_spec));
+
+ pa_threaded_mainloop_unlock(i->mainloop);
+
+ if (!valid) {
+ *_errno = EINVAL;
+ goto fail;
+ }
+
+ break;
+ }
+
+ case SNDCTL_DSP_STEREO:
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": SNDCTL_DSP_STEREO: %i\n", *(int*) argp);
+
+ pa_threaded_mainloop_lock(i->mainloop);
+
+ i->sample_spec.channels = *(int*) argp ? 2 : 1;
+ free_streams(i);
+
+ pa_threaded_mainloop_unlock(i->mainloop);
+ return 0;
+
+ case SNDCTL_DSP_CHANNELS: {
+ pa_sample_spec ss;
+ int valid;
+
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": SNDCTL_DSP_CHANNELS: %i\n", *(int*) argp);
+
+ pa_threaded_mainloop_lock(i->mainloop);
+
+ ss = i->sample_spec;
+ ss.channels = *(int*) argp;
+
+ if ((valid = pa_sample_spec_valid(&ss))) {
+ i->sample_spec = ss;
+ free_streams(i);
+ }
+
+ pa_threaded_mainloop_unlock(i->mainloop);
+
+ if (!valid) {
+ *_errno = EINVAL;
+ goto fail;
+ }
+
+ break;
+ }
+
+ case SNDCTL_DSP_GETBLKSIZE:
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": SNDCTL_DSP_GETBLKSIZE\n");
+
+ pa_threaded_mainloop_lock(i->mainloop);
+
+ fix_metrics(i);
+ *(int*) argp = i->fragment_size;
+
+ pa_threaded_mainloop_unlock(i->mainloop);
+
+ break;
+
+ case SNDCTL_DSP_SETFRAGMENT:
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": SNDCTL_DSP_SETFRAGMENT: 0x%08x\n", *(int*) argp);
+
+ pa_threaded_mainloop_lock(i->mainloop);
+
+ i->fragment_size = 1 << ((*(int*) argp) & 31);
+ i->n_fragments = (*(int*) argp) >> 16;
+
+ /* 0x7FFF means that we can set whatever we like */
+ if (i->n_fragments == 0x7FFF)
+ i->n_fragments = 12;
+
+ free_streams(i);
+
+ pa_threaded_mainloop_unlock(i->mainloop);
+
+ break;
+
+ case SNDCTL_DSP_GETCAPS:
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": SNDCTL_DSP_CAPS\n");
+
+ *(int*) argp = DSP_CAP_DUPLEX | DSP_CAP_TRIGGER
+#ifdef DSP_CAP_MULTI
+ | DSP_CAP_MULTI
+#endif
+ ;
+ break;
+
+ case SNDCTL_DSP_GETODELAY: {
+ int l;
+
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": SNDCTL_DSP_GETODELAY\n");
+
+ pa_threaded_mainloop_lock(i->mainloop);
+
+ *(int*) argp = 0;
+
+ for (;;) {
+ pa_usec_t usec;
+
+ PLAYBACK_STREAM_CHECK_DEAD_GOTO(i, exit_loop);
+
+ if (pa_stream_get_latency(i->play_stream, &usec, NULL) >= 0) {
+ *(int*) argp = pa_usec_to_bytes(usec, &i->sample_spec);
+ break;
+ }
+
+ if (pa_context_errno(i->context) != PA_ERR_NODATA) {
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": pa_stream_get_latency(): %s\n", pa_strerror(pa_context_errno(i->context)));
+ break;
+ }
+
+ pa_threaded_mainloop_wait(i->mainloop);
+ }
+
+ exit_loop:
+
+#ifdef SIOCINQ
+ if (ioctl(i->thread_fd, SIOCINQ, &l) < 0)
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": SIOCINQ failed: %s\n", strerror(errno));
+ else
+ *(int*) argp += l;
+#else
+# warning "Your platform does not support SIOCINQ, something might not work as intended."
+#endif
+
+ pa_threaded_mainloop_unlock(i->mainloop);
+
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": ODELAY: %i\n", *(int*) argp);
+
+ break;
+ }
+
+ case SNDCTL_DSP_RESET: {
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": SNDCTL_DSP_RESET\n");
+
+ pa_threaded_mainloop_lock(i->mainloop);
+
+ free_streams(i);
+ dsp_flush_socket(i);
+
+ i->optr_n_blocks = 0;
+
+ pa_threaded_mainloop_unlock(i->mainloop);
+ break;
+ }
+
+ case SNDCTL_DSP_GETFMTS: {
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": SNDCTL_DSP_GETFMTS\n");
+
+ *(int*) argp = AFMT_MU_LAW|AFMT_A_LAW|AFMT_U8|AFMT_S16_LE|AFMT_S16_BE;
+ break;
+ }
+
+ case SNDCTL_DSP_POST:
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": SNDCTL_DSP_POST\n");
+
+ if (dsp_trigger(i) < 0)
+ *_errno = EIO;
+ break;
+
+ case SNDCTL_DSP_GETTRIGGER:
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": SNDCTL_DSP_GETTRIGGER\n");
+
+ *(int*) argp = 0;
+ if (!i->play_precork)
+ *(int*) argp |= PCM_ENABLE_OUTPUT;
+ if (!i->rec_precork)
+ *(int*) argp |= PCM_ENABLE_INPUT;
+
+ break;
+
+ case SNDCTL_DSP_SETTRIGGER:
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": SNDCTL_DSP_SETTRIGGER: 0x%08x\n", *(int*) argp);
+
+ if (!i->io_event) {
+ *_errno = EIO;
+ break;
+ }
+
+ i->play_precork = !((*(int*) argp) & PCM_ENABLE_OUTPUT);
+
+ if (i->play_stream) {
+ if (dsp_cork(i, i->play_stream, !((*(int*) argp) & PCM_ENABLE_OUTPUT)) < 0)
+ *_errno = EIO;
+ if (dsp_trigger(i) < 0)
+ *_errno = EIO;
+ }
+
+ i->rec_precork = !((*(int*) argp) & PCM_ENABLE_INPUT);
+
+ if (i->rec_stream) {
+ if (dsp_cork(i, i->rec_stream, !((*(int*) argp) & PCM_ENABLE_INPUT)) < 0)
+ *_errno = EIO;
+ }
+
+ break;
+
+ case SNDCTL_DSP_SYNC:
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": SNDCTL_DSP_SYNC\n");
+
+ if (dsp_drain(i) < 0)
+ *_errno = EIO;
+
+ break;
+
+ case SNDCTL_DSP_GETOSPACE:
+ case SNDCTL_DSP_GETISPACE: {
+ audio_buf_info *bi = (audio_buf_info*) argp;
+ int l = 0;
+ size_t k = 0;
+
+ if (request == SNDCTL_DSP_GETOSPACE)
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": SNDCTL_DSP_GETOSPACE\n");
+ else
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": SNDCTL_DSP_GETISPACE\n");
+
+ pa_threaded_mainloop_lock(i->mainloop);
+
+ fix_metrics(i);
+
+ if (request == SNDCTL_DSP_GETOSPACE) {
+ if (i->play_stream) {
+ if ((k = pa_stream_writable_size(i->play_stream)) == (size_t) -1)
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": pa_stream_writable_size(): %s\n", pa_strerror(pa_context_errno(i->context)));
+ } else
+ k = i->fragment_size * i->n_fragments;
+
+#ifdef SIOCINQ
+ if (ioctl(i->thread_fd, SIOCINQ, &l) < 0) {
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": SIOCINQ failed: %s\n", strerror(errno));
+ l = 0;
+ }
+#else
+# warning "Your platform does not dsp_flush_fd, something might not work as intended."
+#endif
+
+ bi->bytes = k > (size_t) l ? k - l : 0;
+ } else {
+ if (i->rec_stream) {
+ if ((k = pa_stream_readable_size(i->rec_stream)) == (size_t) -1)
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": pa_stream_readable_size(): %s\n", pa_strerror(pa_context_errno(i->context)));
+ } else
+ k = 0;
+
+#ifdef SIOCINQ
+ if (ioctl(i->app_fd, SIOCINQ, &l) < 0) {
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": SIOCINQ failed: %s\n", strerror(errno));
+ l = 0;
+ }
+#else
+# warning "Your platform does not dsp_flush_fd, something might not work as intended."
+#endif
+ bi->bytes = k + l;
+ }
+
+ bi->fragsize = i->fragment_size;
+ bi->fragstotal = i->n_fragments;
+ bi->fragments = bi->bytes / bi->fragsize;
+
+ pa_threaded_mainloop_unlock(i->mainloop);
+
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": fragsize=%i, fragstotal=%i, bytes=%i, fragments=%i\n", bi->fragsize, bi->fragstotal, bi->bytes, bi->fragments);
+
+ break;
+ }
+
+#ifdef HAVE_DECL_SOUND_PCM_READ_RATE
+ case SOUND_PCM_READ_RATE:
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": SOUND_PCM_READ_RATE\n");
+
+ pa_threaded_mainloop_lock(i->mainloop);
+ *(int*) argp = i->sample_spec.rate;
+ pa_threaded_mainloop_unlock(i->mainloop);
+ break;
+#endif
+
+#ifdef HAVE_DECL_SOUND_PCM_READ_CHANNELS
+ case SOUND_PCM_READ_CHANNELS:
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": SOUND_PCM_READ_CHANNELS\n");
+
+ pa_threaded_mainloop_lock(i->mainloop);
+ *(int*) argp = i->sample_spec.channels;
+ pa_threaded_mainloop_unlock(i->mainloop);
+ break;
+#endif
+
+#ifdef HAVE_DECL_SOUND_PCM_READ_BITS
+ case SOUND_PCM_READ_BITS:
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": SOUND_PCM_READ_BITS\n");
+
+ pa_threaded_mainloop_lock(i->mainloop);
+ *(int*) argp = pa_sample_size(&i->sample_spec)*8;
+ pa_threaded_mainloop_unlock(i->mainloop);
+ break;
+#endif
+
+ case SNDCTL_DSP_GETOPTR: {
+ count_info *info;
+
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": SNDCTL_DSP_GETOPTR\n");
+
+ info = (count_info*) argp;
+ memset(info, 0, sizeof(*info));
+
+ pa_threaded_mainloop_lock(i->mainloop);
+
+ for (;;) {
+ pa_usec_t usec;
+
+ PLAYBACK_STREAM_CHECK_DEAD_GOTO(i, exit_loop2);
+
+ if (pa_stream_get_time(i->play_stream, &usec) >= 0) {
+ size_t k = pa_usec_to_bytes(usec, &i->sample_spec);
+ int m;
+
+ info->bytes = (int) k;
+ m = k / i->fragment_size;
+ info->blocks = m - i->optr_n_blocks;
+ i->optr_n_blocks = m;
+
+ break;
+ }
+
+ if (pa_context_errno(i->context) != PA_ERR_NODATA) {
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": pa_stream_get_latency(): %s\n", pa_strerror(pa_context_errno(i->context)));
+ break;
+ }
+
+ pa_threaded_mainloop_wait(i->mainloop);
+ }
+
+ exit_loop2:
+
+ pa_threaded_mainloop_unlock(i->mainloop);
+
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": GETOPTR bytes=%i, blocks=%i, ptr=%i\n", info->bytes, info->blocks, info->ptr);
+
+ break;
+ }
+
+ case SNDCTL_DSP_GETIPTR:
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": invalid ioctl SNDCTL_DSP_GETIPTR\n");
+ goto inval;
+
+ case SNDCTL_DSP_SETDUPLEX:
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": SNDCTL_DSP_SETDUPLEX\n");
+ /* this is a no-op */
+ break;
+
+ default:
+ /* Mixer ioctls are valid on /dev/dsp as well */
+ return mixer_ioctl(i, request, argp, _errno);
+
+inval:
+ *_errno = EINVAL;
+ goto fail;
+ }
+
+ ret = 0;
+
+fail:
+
+ return ret;
+}
+
+#ifndef __GLIBC__
+int ioctl(int fd, int request, ...) {
+#else
+int ioctl(int fd, unsigned long request, ...) {
+#endif
+ fd_info *i;
+ va_list args;
+ void *argp;
+ int r, _errno = 0;
+
+ debug(DEBUG_LEVEL_VERBOSE, __FILE__": ioctl()\n");
+
+ va_start(args, request);
+ argp = va_arg(args, void *);
+ va_end(args);
+
+ if (!function_enter()) {
+ LOAD_IOCTL_FUNC();
+ return _ioctl(fd, request, argp);
+ }
+
+ if (!(i = fd_info_find(fd))) {
+ function_exit();
+ LOAD_IOCTL_FUNC();
+ return _ioctl(fd, request, argp);
+ }
+
+ if (i->type == FD_INFO_MIXER)
+ r = mixer_ioctl(i, request, argp, &_errno);
+ else
+ r = dsp_ioctl(i, request, argp, &_errno);
+
+ fd_info_unref(i);
+
+ if (_errno)
+ errno = _errno;
+
+ function_exit();
+
+ return r;
+}
+
+int close(int fd) {
+ fd_info *i;
+
+ debug(DEBUG_LEVEL_VERBOSE, __FILE__": close()\n");
+
+ if (!function_enter()) {
+ LOAD_CLOSE_FUNC();
+ return _close(fd);
+ }
+
+ if (!(i = fd_info_find(fd))) {
+ function_exit();
+ LOAD_CLOSE_FUNC();
+ return _close(fd);
+ }
+
+ fd_info_remove_from_list(i);
+ fd_info_unref(i);
+
+ function_exit();
+
+ return 0;
+}
+
+int access(const char *pathname, int mode) {
+
+ debug(DEBUG_LEVEL_VERBOSE, __FILE__": access(%s)\n", pathname?pathname:"NULL");
+
+ if (!pathname ||
+ !is_audio_device_node(pathname)) {
+ LOAD_ACCESS_FUNC();
+ return _access(pathname, mode);
+ }
+
+ if (mode & X_OK) {
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": access(%s, %x) = EACCESS\n", pathname, mode);
+ errno = EACCES;
+ return -1;
+ }
+
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": access(%s, %x) = OK\n", pathname, mode);
+
+ return 0;
+}
+
+int stat(const char *pathname, struct stat *buf) {
+#ifdef HAVE_OPEN64
+ struct stat64 parent;
+#else
+ struct stat parent;
+#endif
+ int ret;
+
+ if (!pathname ||
+ !buf ||
+ !is_audio_device_node(pathname)) {
+ debug(DEBUG_LEVEL_VERBOSE, __FILE__": stat(%s)\n", pathname?pathname:"NULL");
+ LOAD_STAT_FUNC();
+ return _stat(pathname, buf);
+ }
+
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": stat(%s)\n", pathname);
+
+#ifdef _STAT_VER
+#ifdef HAVE_OPEN64
+ ret = __xstat64(_STAT_VER, "/dev", &parent);
+#else
+ ret = __xstat(_STAT_VER, "/dev", &parent);
+#endif
+#else
+#ifdef HAVE_OPEN64
+ ret = stat64("/dev", &parent);
+#else
+ ret = stat("/dev", &parent);
+#endif
+#endif
+
+ if (ret) {
+ debug(DEBUG_LEVEL_NORMAL, __FILE__": unable to stat \"/dev\"\n");
+ return -1;
+ }
+
+ buf->st_dev = parent.st_dev;
+ buf->st_ino = 0xDEADBEEF; /* FIXME: Can we do this in a safe way? */
+ buf->st_mode = S_IFCHR | S_IRUSR | S_IWUSR;
+ buf->st_nlink = 1;
+ buf->st_uid = getuid();
+ buf->st_gid = getgid();
+ buf->st_rdev = 0x0E03; /* FIXME: Linux specific */
+ buf->st_size = 0;
+ buf->st_atime = 1181557705;
+ buf->st_mtime = 1181557705;
+ buf->st_ctime = 1181557705;
+ buf->st_blksize = 1;
+ buf->st_blocks = 0;
+
+ return 0;
+}
+#ifdef HAVE_OPEN64
+#undef stat64
+#ifdef __GLIBC__
+int stat64(const char *pathname, struct stat64 *buf) {
+#else
+int stat64(const char *pathname, struct stat *buf) {
+#endif
+ struct stat oldbuf;
+ int ret;
+
+ debug(DEBUG_LEVEL_VERBOSE, __FILE__": stat64(%s)\n", pathname?pathname:"NULL");
+
+ if (!pathname ||
+ !buf ||
+ !is_audio_device_node(pathname)) {
+ LOAD_STAT64_FUNC();
+ return _stat64(pathname, buf);
+ }
+
+ ret = stat(pathname, &oldbuf);
+ if (ret)
+ return ret;
+
+ buf->st_dev = oldbuf.st_dev;
+ buf->st_ino = oldbuf.st_ino;
+ buf->st_mode = oldbuf.st_mode;
+ buf->st_nlink = oldbuf.st_nlink;
+ buf->st_uid = oldbuf.st_uid;
+ buf->st_gid = oldbuf.st_gid;
+ buf->st_rdev = oldbuf.st_rdev;
+ buf->st_size = oldbuf.st_size;
+ buf->st_atime = oldbuf.st_atime;
+ buf->st_mtime = oldbuf.st_mtime;
+ buf->st_ctime = oldbuf.st_ctime;
+ buf->st_blksize = oldbuf.st_blksize;
+ buf->st_blocks = oldbuf.st_blocks;
+
+ return 0;
+}
+#undef open64
+int open64(const char *filename, int flags, ...) {
+ va_list args;
+ mode_t mode = 0;
+
+ debug(DEBUG_LEVEL_VERBOSE, __FILE__": open64(%s)\n", filename?filename:"NULL");
+
+ if (flags & O_CREAT) {
+ va_start(args, flags);
+ if (sizeof(mode_t) < sizeof(int))
+ mode = va_arg(args, int);
+ else
+ mode = va_arg(args, mode_t);
+ va_end(args);
+ }
+
+ if (!filename ||
+ !is_audio_device_node(filename)) {
+ LOAD_OPEN64_FUNC();
+ return _open64(filename, flags, mode);
+ }
+
+ return real_open(filename, flags, mode);
+}
+
+int __open64_2(const char *filename, int flags) {
+ debug(DEBUG_LEVEL_VERBOSE, __FILE__": __open64_2(%s)\n", filename?filename:"NULL");
+
+ if ((flags & O_CREAT) ||
+ !filename ||
+ !is_audio_device_node(filename)) {
+ LOAD___OPEN64_2_FUNC();
+ return ___open64_2(filename, flags);
+ }
+
+ return real_open(filename, flags, 0);
+}
+
+#endif
+
+#ifdef _STAT_VER
+
+int __xstat(int ver, const char *pathname, struct stat *buf) {
+ debug(DEBUG_LEVEL_VERBOSE, __FILE__": __xstat(%s)\n", pathname?pathname:"NULL");
+
+ if (!pathname ||
+ !buf ||
+ !is_audio_device_node(pathname)) {
+ LOAD_XSTAT_FUNC();
+ return ___xstat(ver, pathname, buf);
+ }
+
+ if (ver != _STAT_VER) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ return stat(pathname, buf);
+}
+
+#ifdef HAVE_OPEN64
+
+int __xstat64(int ver, const char *pathname, struct stat64 *buf) {
+ debug(DEBUG_LEVEL_VERBOSE, __FILE__": __xstat64(%s)\n", pathname?pathname:"NULL");
+
+ if (!pathname ||
+ !buf ||
+ !is_audio_device_node(pathname)) {
+ LOAD_XSTAT64_FUNC();
+ return ___xstat64(ver, pathname, buf);
+ }
+
+ if (ver != _STAT_VER) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ return stat64(pathname, buf);
+}
+
+#endif
+
+#endif
+
+FILE* fopen(const char *filename, const char *mode) {
+ FILE *f = NULL;
+ int fd;
+ mode_t m;
+
+ debug(DEBUG_LEVEL_VERBOSE, __FILE__": fopen(%s)\n", filename?filename:"NULL");
+
+ if (!filename ||
+ !mode ||
+ !is_audio_device_node(filename)) {
+ LOAD_FOPEN_FUNC();
+ return _fopen(filename, mode);
+ }
+
+ switch (mode[0]) {
+ case 'r':
+ m = O_RDONLY;
+ break;
+ case 'w':
+ case 'a':
+ m = O_WRONLY;
+ break;
+ default:
+ errno = EINVAL;
+ return NULL;
+ }
+
+ if ((((mode[1] == 'b') || (mode[1] == 't')) && (mode[2] == '+')) || (mode[1] == '+'))
+ m = O_RDWR;
+
+ if ((fd = real_open(filename, m, 0)) < 0)
+ return NULL;
+
+ if (!(f = fdopen(fd, mode))) {
+ close(fd);
+ return NULL;
+ }
+
+ return f;
+}
+
+#ifdef HAVE_OPEN64
+#undef fopen64
+FILE *fopen64(const char *__restrict filename, const char *__restrict mode) {
+
+ debug(DEBUG_LEVEL_VERBOSE, __FILE__": fopen64(%s)\n", filename?filename:"NULL");
+
+ if (!filename ||
+ !mode ||
+ !is_audio_device_node(filename)) {
+ LOAD_FOPEN64_FUNC();
+ return _fopen64(filename, mode);
+ }
+
+ return fopen(filename, mode);
+}
+
+#endif
+
+int fclose(FILE *f) {
+ fd_info *i;
+
+ debug(DEBUG_LEVEL_VERBOSE, __FILE__": fclose()\n");
+
+ if (!function_enter()) {
+ LOAD_FCLOSE_FUNC();
+ return _fclose(f);
+ }
+
+ if (!(i = fd_info_find(fileno(f)))) {
+ function_exit();
+ LOAD_FCLOSE_FUNC();
+ return _fclose(f);
+ }
+
+ fd_info_remove_from_list(i);
+
+ /* Dirty trick to avoid that the fd is not freed twice, once by us
+ * and once by the real fclose() */
+ i->app_fd = -1;
+
+ fd_info_unref(i);
+
+ function_exit();
+
+ LOAD_FCLOSE_FUNC();
+ return _fclose(f);
+}
diff --git a/src/utils/padsp.in b/src/utils/padsp.in
new file mode 100755
index 0000000..fea00d2
--- /dev/null
+++ b/src/utils/padsp.in
@@ -0,0 +1,84 @@
+#!/bin/sh
+
+# This file is part of PulseAudio.
+#
+# Copyright 2006 Lennart Poettering
+# Copyright 2006 Pierre Ossman <ossman@cendio.se> for Cendio AB
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+while getopts 'hs:n:m:MSDd' param ; do
+ case $param in
+ s)
+ PULSE_SERVER="$OPTARG"
+ export PULSE_SERVER
+ ;;
+ n)
+ PADSP_CLIENT_NAME="$OPTARG"
+ export PADSP_CLIENT_NAME
+ ;;
+ m)
+ PADSP_STREAM_NAME="$OPTARG"
+ export PADSP_STREAM_NAME
+ ;;
+ M)
+ PADSP_NO_MIXER=1
+ export PADSP_NO_MIXER
+ ;;
+ S)
+ PADSP_NO_SNDSTAT=1
+ export PADSP_NO_SNDSTAT
+ ;;
+ D)
+ PADSP_NO_DSP=1
+ export PADSP_NO_DSP
+ ;;
+ d)
+ if [ x"$PADSP_DEBUG" = x ]; then
+ PADSP_DEBUG=1
+ else
+ PADSP_DEBUG=$(( $PADSP_DEBUG + 1 ))
+ fi
+ export PADSP_DEBUG
+ ;;
+ *)
+ echo "$0 - redirect OSS audio devices to PulseAudio"
+ echo " "
+ echo "$0 [options] application [arguments]"
+ echo " "
+ echo "options:"
+ echo " -h show brief help"
+ echo " -s <host>[:<port>] contact a specific PulseAudio server"
+ echo " -n <name> client name to report to the server"
+ echo " -m <name> stream name to report to the server"
+ echo " -M disable /dev/mixer emulation"
+ echo " -S disable /dev/sndstat emulation"
+ echo " -D disable /dev/dsp emulation"
+ echo " -d enable debug output"
+ exit 0
+ ;;
+ esac
+done
+
+shift $(( $OPTIND - 1 ))
+
+if [ x"$LD_PRELOAD" = x ] ; then
+ LD_PRELOAD="@PULSEDSP_LOCATION@/libpulsedsp.so"
+else
+ LD_PRELOAD="$LD_PRELOAD @PULSEDSP_LOCATION@/libpulsedsp.so"
+fi
+
+export LD_PRELOAD
+
+exec "$@"
diff --git a/src/utils/pasuspender.c b/src/utils/pasuspender.c
new file mode 100644
index 0000000..1f0c987
--- /dev/null
+++ b/src/utils/pasuspender.c
@@ -0,0 +1,343 @@
+/***
+ This file is part of PulseAudio.
+
+ Copyright 2004-2006 Lennart Poettering
+
+ PulseAudio is free software; you can redistribute it and/or modify
+ it under the terms of the GNU Lesser General Public License as published
+ by the Free Software Foundation; either version 2.1 of the License,
+ or (at your option) any later version.
+
+ PulseAudio is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+***/
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <sys/types.h>
+#include <sys/wait.h>
+
+#include <signal.h>
+#include <string.h>
+#include <errno.h>
+#include <unistd.h>
+#include <assert.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <getopt.h>
+#include <locale.h>
+
+#ifdef __linux__
+#include <sys/prctl.h>
+#endif
+
+#include <pulse/pulseaudio.h>
+
+#include <pulsecore/i18n.h>
+#include <pulsecore/macro.h>
+
+static pa_context *context = NULL;
+static pa_mainloop_api *mainloop_api = NULL;
+static char **child_argv = NULL;
+static int child_argc = 0;
+static pid_t child_pid = (pid_t) -1;
+static int child_ret = 0;
+static int dead = 1;
+static int fork_failed = 0;
+
+static void quit(int ret) {
+ pa_assert(mainloop_api);
+ mainloop_api->quit(mainloop_api, ret);
+}
+
+static void context_drain_complete(pa_context *c, void *userdata) {
+ pa_context_disconnect(c);
+}
+
+static void drain(void) {
+ pa_operation *o;
+
+ if (context) {
+ if (!(o = pa_context_drain(context, context_drain_complete, NULL)))
+ pa_context_disconnect(context);
+ else
+ pa_operation_unref(o);
+ } else
+ quit(0);
+}
+
+static int start_child(void) {
+
+ if ((child_pid = fork()) < 0) {
+ fprintf(stderr, _("fork(): %s\n"), strerror(errno));
+ fork_failed = 1;
+
+ return -1;
+
+ } else if (child_pid == 0) {
+ /* Child */
+
+#ifdef __linux__
+ prctl(PR_SET_PDEATHSIG, SIGTERM, 0, 0, 0);
+#endif
+
+ if (execvp(child_argv[0], child_argv) < 0)
+ fprintf(stderr, _("execvp(): %s\n"), strerror(errno));
+
+ _exit(1);
+
+ } else {
+
+ /* parent */
+ dead = 0;
+ }
+
+ return 0;
+}
+
+static void resume_complete(pa_context *c, int success, void *userdata) {
+ static int n = 0;
+
+ n++;
+
+ if (!success) {
+ fprintf(stderr, _("Failure to resume: %s\n"), pa_strerror(pa_context_errno(c)));
+ quit(1);
+ return;
+ }
+
+ if (n >= 2)
+ drain(); /* drain and quit */
+}
+
+static void resume(void) {
+ static int n = 0;
+
+ n++;
+
+ if (n > 1)
+ return;
+
+ if (context) {
+ if (pa_context_is_local(context)) {
+ pa_operation_unref(pa_context_suspend_sink_by_index(context, PA_INVALID_INDEX, 0, resume_complete, NULL));
+ pa_operation_unref(pa_context_suspend_source_by_index(context, PA_INVALID_INDEX, 0, resume_complete, NULL));
+ } else
+ drain();
+ } else {
+ quit(0);
+ }
+}
+
+static void suspend_complete(pa_context *c, int success, void *userdata) {
+ static int n = 0;
+
+ n++;
+
+ if (!success) {
+ fprintf(stderr, _("Failure to suspend: %s\n"), pa_strerror(pa_context_errno(c)));
+ quit(1);
+ return;
+ }
+
+ if (n >= 2) {
+ if (start_child() < 0)
+ resume();
+ }
+}
+
+static void context_state_callback(pa_context *c, void *userdata) {
+ pa_assert(c);
+
+ switch (pa_context_get_state(c)) {
+ case PA_CONTEXT_CONNECTING:
+ case PA_CONTEXT_AUTHORIZING:
+ case PA_CONTEXT_SETTING_NAME:
+ break;
+
+ case PA_CONTEXT_READY:
+ if (pa_context_is_local(c)) {
+ pa_operation_unref(pa_context_suspend_sink_by_index(c, PA_INVALID_INDEX, 1, suspend_complete, NULL));
+ pa_operation_unref(pa_context_suspend_source_by_index(c, PA_INVALID_INDEX, 1, suspend_complete, NULL));
+ } else {
+ fprintf(stderr, _("WARNING: Sound server is not local, not suspending.\n"));
+ if (start_child() < 0)
+ drain();
+ }
+
+ break;
+
+ case PA_CONTEXT_TERMINATED:
+ quit(0);
+ break;
+
+ case PA_CONTEXT_FAILED:
+ default:
+ fprintf(stderr, _("Connection failure: %s\n"), pa_strerror(pa_context_errno(c)));
+
+ pa_context_unref(context);
+ context = NULL;
+
+ if (child_pid == (pid_t) -1) {
+ /* not started yet, then we do it now */
+ if (start_child() < 0)
+ quit(1);
+ } else if (dead)
+ /* already started, and dead, so let's quit */
+ quit(1);
+
+ break;
+ }
+}
+
+static void sigint_callback(pa_mainloop_api *m, pa_signal_event *e, int sig, void *userdata) {
+ fprintf(stderr, _("Got SIGINT, exiting.\n"));
+ resume();
+}
+
+static void sigchld_callback(pa_mainloop_api *m, pa_signal_event *e, int sig, void *userdata) {
+ int status = 0;
+ pid_t p;
+
+ p = waitpid(-1, &status, WNOHANG);
+
+ if (p != child_pid)
+ return;
+
+ dead = 1;
+
+ if (WIFEXITED(status))
+ child_ret = WEXITSTATUS(status);
+ else if (WIFSIGNALED(status)) {
+ fprintf(stderr, _("WARNING: Child process terminated by signal %u\n"), WTERMSIG(status));
+ child_ret = 1;
+ }
+
+ resume();
+}
+
+static void help(const char *argv0) {
+
+ printf(_("%s [options] -- PROGRAM [ARGUMENTS ...]\n\n"
+ "Temporarily suspend PulseAudio while PROGRAM runs.\n\n"
+ " -h, --help Show this help\n"
+ " --version Show version\n"
+ " -s, --server=SERVER The name of the server to connect to\n\n"),
+ argv0);
+}
+
+enum {
+ ARG_VERSION = 256
+};
+
+int main(int argc, char *argv[]) {
+ pa_mainloop* m = NULL;
+ int c, ret = 1;
+ char *server = NULL, *bn;
+
+ static const struct option long_options[] = {
+ {"server", 1, NULL, 's'},
+ {"version", 0, NULL, ARG_VERSION},
+ {"help", 0, NULL, 'h'},
+ {NULL, 0, NULL, 0}
+ };
+
+ setlocale(LC_ALL, "");
+#ifdef ENABLE_NLS
+ bindtextdomain(GETTEXT_PACKAGE, PULSE_LOCALEDIR);
+#endif
+
+ bn = pa_path_get_filename(argv[0]);
+
+ while ((c = getopt_long(argc, argv, "s:h", long_options, NULL)) != -1) {
+ switch (c) {
+ case 'h' :
+ help(bn);
+ ret = 0;
+ goto quit;
+
+ case ARG_VERSION:
+ printf(_("pasuspender %s\n"
+ "Compiled with libpulse %s\n"
+ "Linked with libpulse %s\n"),
+ PACKAGE_VERSION,
+ pa_get_headers_version(),
+ pa_get_library_version());
+ ret = 0;
+ goto quit;
+
+ case 's':
+ pa_xfree(server);
+ server = pa_xstrdup(optarg);
+ break;
+
+ default:
+ goto quit;
+ }
+ }
+
+ child_argv = argv + optind;
+ child_argc = argc - optind;
+
+ if (child_argc <= 0) {
+ help(bn);
+ ret = 0;
+ goto quit;
+ }
+
+ if (!(m = pa_mainloop_new())) {
+ fprintf(stderr, _("pa_mainloop_new() failed.\n"));
+ goto quit;
+ }
+
+ pa_assert_se(mainloop_api = pa_mainloop_get_api(m));
+ pa_assert_se(pa_signal_init(mainloop_api) == 0);
+ pa_signal_new(SIGINT, sigint_callback, NULL);
+ pa_signal_new(SIGCHLD, sigchld_callback, NULL);
+#ifdef SIGPIPE
+ signal(SIGPIPE, SIG_IGN);
+#endif
+
+ if (!(context = pa_context_new(mainloop_api, bn))) {
+ fprintf(stderr, _("pa_context_new() failed.\n"));
+ goto quit;
+ }
+
+ pa_context_set_state_callback(context, context_state_callback, NULL);
+
+ if (pa_context_connect(context, server, PA_CONTEXT_NOAUTOSPAWN, NULL) < 0) {
+ fprintf(stderr, "pa_context_connect() failed: %s\n", pa_strerror(pa_context_errno(context)));
+ goto quit;
+ }
+
+ if (pa_mainloop_run(m, &ret) < 0) {
+ fprintf(stderr, _("pa_mainloop_run() failed.\n"));
+ goto quit;
+ }
+
+ if (ret == 0 && fork_failed)
+ ret = 1;
+
+quit:
+ if (context)
+ pa_context_unref(context);
+
+ if (m) {
+ pa_signal_done();
+ pa_mainloop_free(m);
+ }
+
+ pa_xfree(server);
+
+ if (!dead)
+ kill(child_pid, SIGTERM);
+
+ return ret == 0 ? child_ret : ret;
+}
diff --git a/src/utils/pax11publish.c b/src/utils/pax11publish.c
new file mode 100644
index 0000000..a91dbf7
--- /dev/null
+++ b/src/utils/pax11publish.c
@@ -0,0 +1,220 @@
+/***
+ This file is part of PulseAudio.
+
+ Copyright 2004-2006 Lennart Poettering
+
+ PulseAudio is free software; you can redistribute it and/or modify
+ it under the terms of the GNU Lesser General Public License as published
+ by the Free Software Foundation; either version 2.1 of the License,
+ or (at your option) any later version.
+
+ PulseAudio is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+***/
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <stdio.h>
+#include <getopt.h>
+#include <assert.h>
+#include <locale.h>
+
+#include <xcb/xcb.h>
+
+#include <pulse/util.h>
+#include <pulse/client-conf.h>
+
+#include <pulsecore/core-util.h>
+#include <pulsecore/i18n.h>
+#include <pulsecore/log.h>
+#include <pulsecore/authkey.h>
+#include <pulsecore/native-common.h>
+#include <pulsecore/x11prop.h>
+
+int main(int argc, char *argv[]) {
+ const char *dname = NULL, *sink = NULL, *source = NULL, *server = NULL, *cookie_file = PA_NATIVE_COOKIE_FILE;
+ int c, ret = 1, screen = 0;
+ xcb_connection_t *xcb = NULL;
+ enum { DUMP, EXPORT, IMPORT, REMOVE } mode = DUMP;
+
+ setlocale(LC_ALL, "");
+#ifdef ENABLE_NLS
+ bindtextdomain(GETTEXT_PACKAGE, PULSE_LOCALEDIR);
+#endif
+
+ while ((c = getopt(argc, argv, "deiD:S:O:I:c:hr")) != -1) {
+ switch (c) {
+ case 'D' :
+ dname = optarg;
+ break;
+ case 'h':
+ printf(_("%s [-D display] [-S server] [-O sink] [-I source] [-c file] [-d|-e|-i|-r]\n\n"
+ " -d Show current PulseAudio data attached to X11 display (default)\n"
+ " -e Export local PulseAudio data to X11 display\n"
+ " -i Import PulseAudio data from X11 display to local environment variables and cookie file.\n"
+ " -r Remove PulseAudio data from X11 display\n"),
+ pa_path_get_filename(argv[0]));
+ ret = 0;
+ goto finish;
+ case 'd':
+ mode = DUMP;
+ break;
+ case 'e':
+ mode = EXPORT;
+ break;
+ case 'i':
+ mode = IMPORT;
+ break;
+ case 'r':
+ mode = REMOVE;
+ break;
+ case 'c':
+ cookie_file = optarg;
+ break;
+ case 'I':
+ source = optarg;
+ break;
+ case 'O':
+ sink = optarg;
+ break;
+ case 'S':
+ server = optarg;
+ break;
+ default:
+ fprintf(stderr, _("Failed to parse command line.\n"));
+ goto finish;
+ }
+ }
+
+ if (!(xcb = xcb_connect(dname, &screen))) {
+ pa_log(_("xcb_connect() failed"));
+ goto finish;
+ }
+
+ if (xcb_connection_has_error(xcb)) {
+ pa_log(_("xcb_connection_has_error() returned true"));
+ goto finish;
+ }
+
+ switch (mode) {
+ case DUMP: {
+ char t[1024];
+ if (pa_x11_get_prop(xcb, screen, "PULSE_SERVER", t, sizeof(t)))
+ printf(_("Server: %s\n"), t);
+ if (pa_x11_get_prop(xcb, screen, "PULSE_SOURCE", t, sizeof(t)))
+ printf(_("Source: %s\n"), t);
+ if (pa_x11_get_prop(xcb, screen, "PULSE_SINK", t, sizeof(t)))
+ printf(_("Sink: %s\n"), t);
+ if (pa_x11_get_prop(xcb, screen, "PULSE_COOKIE", t, sizeof(t)))
+ printf(_("Cookie: %s\n"), t);
+
+ break;
+ }
+
+ case IMPORT: {
+ char t[1024];
+ if (pa_x11_get_prop(xcb, screen, "PULSE_SERVER", t, sizeof(t)))
+ printf("PULSE_SERVER='%s'\nexport PULSE_SERVER\n", t);
+ if (pa_x11_get_prop(xcb, screen, "PULSE_SOURCE", t, sizeof(t)))
+ printf("PULSE_SOURCE='%s'\nexport PULSE_SOURCE\n", t);
+ if (pa_x11_get_prop(xcb, screen, "PULSE_SINK", t, sizeof(t)))
+ printf("PULSE_SINK='%s'\nexport PULSE_SINK\n", t);
+
+ if (pa_x11_get_prop(xcb, screen, "PULSE_COOKIE", t, sizeof(t))) {
+ uint8_t cookie[PA_NATIVE_COOKIE_LENGTH];
+ size_t l;
+ if ((l = pa_parsehex(t, cookie, sizeof(cookie))) != sizeof(cookie)) {
+ fprintf(stderr, _("Failed to parse cookie data\n"));
+ goto finish;
+ }
+
+ if (pa_authkey_save(cookie_file, cookie, l) < 0) {
+ fprintf(stderr, _("Failed to save cookie data\n"));
+ goto finish;
+ }
+ }
+
+ break;
+ }
+
+ case EXPORT: {
+ pa_client_conf *conf = pa_client_conf_new();
+ uint8_t cookie[PA_NATIVE_COOKIE_LENGTH];
+ char hx[PA_NATIVE_COOKIE_LENGTH*2+1];
+ assert(conf);
+
+ pa_client_conf_load(conf, false, true);
+
+ pa_x11_del_prop(xcb, screen, "PULSE_SERVER");
+ pa_x11_del_prop(xcb, screen, "PULSE_SINK");
+ pa_x11_del_prop(xcb, screen, "PULSE_SOURCE");
+ pa_x11_del_prop(xcb, screen, "PULSE_ID");
+ pa_x11_del_prop(xcb, screen, "PULSE_COOKIE");
+
+ if (server)
+ pa_x11_set_prop(xcb, screen, "PULSE_SERVER", server);
+ else if (conf->default_server)
+ pa_x11_set_prop(xcb, screen, "PULSE_SERVER", conf->default_server);
+ else {
+ char hn[256];
+ if (!pa_get_fqdn(hn, sizeof(hn))) {
+ fprintf(stderr, _("Failed to get FQDN.\n"));
+ goto finish;
+ }
+
+ pa_x11_set_prop(xcb, screen, "PULSE_SERVER", hn);
+ }
+
+ if (sink)
+ pa_x11_set_prop(xcb, screen, "PULSE_SINK", sink);
+ else if (conf->default_sink)
+ pa_x11_set_prop(xcb, screen, "PULSE_SINK", conf->default_sink);
+
+ if (source)
+ pa_x11_set_prop(xcb, screen, "PULSE_SOURCE", source);
+ if (conf->default_source)
+ pa_x11_set_prop(xcb, screen, "PULSE_SOURCE", conf->default_source);
+
+ pa_client_conf_free(conf);
+
+ if (pa_authkey_load(cookie_file, true, cookie, sizeof(cookie)) < 0) {
+ fprintf(stderr, _("Failed to load cookie data\n"));
+ goto finish;
+ }
+
+ pa_x11_set_prop(xcb, screen, "PULSE_COOKIE", pa_hexstr(cookie, sizeof(cookie), hx, sizeof(hx)));
+ break;
+ }
+
+ case REMOVE:
+ pa_x11_del_prop(xcb, screen, "PULSE_SERVER");
+ pa_x11_del_prop(xcb, screen, "PULSE_SINK");
+ pa_x11_del_prop(xcb, screen, "PULSE_SOURCE");
+ pa_x11_del_prop(xcb, screen, "PULSE_ID");
+ pa_x11_del_prop(xcb, screen, "PULSE_COOKIE");
+ pa_x11_del_prop(xcb, screen, "PULSE_SESSION_ID");
+ break;
+
+ default:
+ fprintf(stderr, _("Not yet implemented.\n"));
+ goto finish;
+ }
+
+ ret = 0;
+
+finish:
+
+ if (xcb) {
+ xcb_flush(xcb);
+ xcb_disconnect(xcb);
+ }
+
+ return ret;
+}
diff --git a/src/utils/qpaeq b/src/utils/qpaeq
new file mode 100755
index 0000000..7e01d87
--- /dev/null
+++ b/src/utils/qpaeq
@@ -0,0 +1,574 @@
+#!/usr/bin/env python3
+# qpaeq is a equalizer interface for pulseaudio's equalizer sinks
+# Copyright (C) 2009 Jason Newton <nevion@gmail.com
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation, either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+
+import os,math,sys
+try:
+ from PyQt5 import QtWidgets,QtCore
+ import dbus.mainloop.pyqt5
+ import dbus
+except ImportError as e:
+ sys.stderr.write('There was an error importing needed libraries\n'
+ 'Make sure you have qt5 and dbus-python installed\n'
+ 'The error that occurred was:\n'
+ '\t%s\n' % (str(e)))
+ sys.exit(-1)
+
+from functools import partial
+
+import signal
+signal.signal(signal.SIGINT, signal.SIG_DFL)
+SYNC_TIMEOUT = 4*1000
+
+CORE_PATH = "/org/pulseaudio/core1"
+CORE_IFACE = "org.PulseAudio.Core1"
+def connect():
+ try:
+ if 'PULSE_DBUS_SERVER' in os.environ:
+ address = os.environ['PULSE_DBUS_SERVER']
+ else:
+ bus = dbus.SessionBus() # Should be UserBus, but D-Bus doesn't implement that yet.
+ server_lookup = bus.get_object('org.PulseAudio1', '/org/pulseaudio/server_lookup1')
+ address = server_lookup.Get('org.PulseAudio.ServerLookup1', 'Address', dbus_interface='org.freedesktop.DBus.Properties')
+ return dbus.connection.Connection(address)
+ except Exception as e:
+ sys.stderr.write('There was an error connecting to pulseaudio, '
+ 'please make sure you have the pulseaudio dbus '
+ 'module loaded, exiting...\n')
+ sys.exit(-1)
+
+
+#TODO: signals: sink Filter changed, sink reconfigured (window size) (sink iface)
+#TODO: manager signals: new sink, removed sink, new profile, removed profile
+#TODO: add support for changing of window_size 1000-fft_size (adv option)
+#TODO: reconnect support loop 1 second trying to reconnect
+#TODO: just resample the filters for profiles when loading to different sizes
+#TODO: add preamp
+prop_iface='org.freedesktop.DBus.Properties'
+eq_iface='org.PulseAudio.Ext.Equalizing1.Equalizer'
+device_iface='org.PulseAudio.Core1.Device'
+class QPaeq(QtWidgets.QWidget):
+ manager_path='/org/pulseaudio/equalizing1'
+ manager_iface='org.PulseAudio.Ext.Equalizing1.Manager'
+ core_iface='org.PulseAudio.Core1'
+ core_path='/org/pulseaudio/core1'
+ module_name='module-equalizer-sink'
+
+ def __init__(self):
+ QtWidgets.QWidget.__init__(self)
+ self.setWindowTitle('qpaeq')
+ self.slider_widget=None
+ self.sink_name=None
+ self.filter_state=None
+
+ self.create_layout()
+
+ self.set_connection()
+ self.connect_to_sink(self.sinks[0])
+ self.set_callbacks()
+ self.setMinimumSize(self.sizeHint())
+
+ def create_layout(self):
+ self.main_layout=QtWidgets.QVBoxLayout()
+ self.setLayout(self.main_layout)
+ toprow_layout=QtWidgets.QHBoxLayout()
+ sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed)
+ sizePolicy.setHorizontalStretch(0)
+ sizePolicy.setVerticalStretch(0)
+ #sizePolicy.setHeightForWidth(self.profile_box.sizePolicy().hasHeightForWidth())
+
+ toprow_layout.addWidget(QtWidgets.QLabel('Sink'))
+ self.sink_box = QtWidgets.QComboBox()
+ self.sink_box.setSizePolicy(sizePolicy)
+ self.sink_box.setDuplicatesEnabled(False)
+ self.sink_box.setInsertPolicy(QtWidgets.QComboBox.InsertAlphabetically)
+ #self.sink_box.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToContents)
+ toprow_layout.addWidget(self.sink_box)
+
+ toprow_layout.addWidget(QtWidgets.QLabel('Channel'))
+ self.channel_box = QtWidgets.QComboBox()
+ self.channel_box.setSizePolicy(sizePolicy)
+ toprow_layout.addWidget(self.channel_box)
+
+ toprow_layout.addWidget(QtWidgets.QLabel('Preset'))
+ self.profile_box = QtWidgets.QComboBox()
+ self.profile_box.setSizePolicy(sizePolicy)
+ self.profile_box.setInsertPolicy(QtWidgets.QComboBox.InsertAlphabetically)
+ #self.profile_box.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToContents)
+ toprow_layout.addWidget(self.profile_box)
+
+ large_icon_size=self.style().pixelMetric(QtWidgets.QStyle.PM_LargeIconSize)
+ large_icon_size=QtCore.QSize(large_icon_size,large_icon_size)
+ save_profile=QtWidgets.QToolButton()
+ save_profile.setIcon(self.style().standardIcon(QtWidgets.QStyle.SP_DriveFDIcon))
+ save_profile.setIconSize(large_icon_size)
+ save_profile.setToolButtonStyle(QtCore.Qt.ToolButtonIconOnly)
+ save_profile.clicked.connect(self.save_profile)
+ remove_profile=QtWidgets.QToolButton()
+ remove_profile.setIcon(self.style().standardIcon(QtWidgets.QStyle.SP_TrashIcon))
+ remove_profile.setIconSize(large_icon_size)
+ remove_profile.setToolButtonStyle(QtCore.Qt.ToolButtonIconOnly)
+ remove_profile.clicked.connect(self.remove_profile)
+ toprow_layout.addWidget(save_profile)
+ toprow_layout.addWidget(remove_profile)
+
+ reset_button = QtWidgets.QPushButton('Reset')
+ reset_button.clicked.connect(self.reset)
+ toprow_layout.addStretch()
+ toprow_layout.addWidget(reset_button)
+ self.layout().addLayout(toprow_layout)
+
+ self.profile_box.activated.connect(self.load_profile)
+ self.channel_box.activated.connect(self.select_channel)
+ def connect_to_sink(self,name):
+ #TODO: clear slots for profile buttons
+
+ #flush any pending saves for other sinks
+ if self.filter_state is not None:
+ self.filter_state.flush_state()
+ sink=self.connection.get_object(object_path=name)
+ self.sink_props=dbus.Interface(sink,dbus_interface=prop_iface)
+ self.sink=dbus.Interface(sink,dbus_interface=eq_iface)
+ self.filter_state=FilterState(sink)
+ #sample_rate,filter_rate,channels,channel)
+
+ self.channel_box.clear()
+ self.channel_box.addItem('All',self.filter_state.channels)
+ for i in range(self.filter_state.channels):
+ self.channel_box.addItem('%d' %(i+1,),i)
+ self.setMinimumSize(self.sizeHint())
+
+ self.set_slider_widget(SliderArray(self.filter_state))
+
+ self.sink_name=name
+ #set the signal listener for this sink
+ core=self._get_core()
+ #temporary hack until signal filtering works properly
+ core.ListenForSignal('',[dbus.ObjectPath(self.sink_name),dbus.ObjectPath(self.manager_path)])
+ #for x in ['FilterChanged']:
+ # core.ListenForSignal("%s.%s" %(self.eq_iface,x),[dbus.ObjectPath(self.sink_name)])
+ #core.ListenForSignal(self.eq_iface,[dbus.ObjectPath(self.sink_name)])
+ self.sink.connect_to_signal('FilterChanged',self.read_filter)
+
+ def set_slider_widget(self,widget):
+ layout=self.layout()
+ if self.slider_widget is not None:
+ i=layout.indexOf(self.slider_widget)
+ layout.removeWidget(self.slider_widget)
+ self.slider_widget.deleteLater()
+ layout.insertWidget(i,self.slider_widget)
+ else:
+ layout.addWidget(widget)
+ self.slider_widget=widget
+ self.read_filter()
+ def _get_core(self):
+ core_obj=self.connection.get_object(object_path=self.core_path)
+ core=dbus.Interface(core_obj,dbus_interface=self.core_iface)
+ return core
+ def sink_added(self,sink):
+ #TODO: preserve selected sink
+ self.update_sinks()
+ def sink_removed(self,sink):
+ #TODO: preserve selected sink, try connecting to backup otherwise
+ if sink==self.sink_name:
+ #connect to new sink?
+ pass
+ self.update_sinks()
+ def save_profile(self):
+ #popup dialog box for name
+ current=self.profile_box.currentIndex()
+ profile,ok=QtWidgets.QInputDialog.getItem(self,'Preset Name','Preset',self.profiles,current)
+ if not ok or profile=='':
+ return
+ if profile in self.profiles:
+ mbox=QtWidgets.QMessageBox(self)
+ mbox.setText('%s preset already exists'%(profile,))
+ mbox.setInformativeText('Do you want to save over it?')
+ mbox.setStandardButtons(mbox.Save|mbox.Discard|mbox.Cancel)
+ mbox.setDefaultButton(mbox.Save)
+ ret=mbox.exec_()
+ if ret!=mbox.Save:
+ return
+ self.sink.SaveProfile(self.filter_state.channel,dbus.String(profile))
+ if self.filter_state.channel==self.filter_state.channels:
+ for x in range(1,self.filter_state.channels):
+ self.sink.LoadProfile(x,dbus.String(profile))
+ def remove_profile(self):
+ #find active profile name, remove it
+ profile=self.profile_box.currentText()
+ manager=dbus.Interface(self.manager_obj,dbus_interface=self.manager_iface)
+ manager.RemoveProfile(dbus.String(profile))
+ def load_profile(self,x):
+ profile=self.profile_box.itemText(x)
+ self.filter_state.load_profile(profile)
+ def select_channel(self,x):
+ self.filter_state.channel = self.channel_box.itemData(x)
+ self._set_profile_name()
+ self.filter_state.readback()
+
+ #TODO: add back in preamp!
+ #print(frequencies)
+ #main_layout.addLayout(self.create_slider(partial(self.update_coefficient,0),
+ # 'Preamp')[0]
+ #)
+ def set_connection(self):
+ self.connection=connect()
+
+ self.manager_obj=self.connection.get_object(object_path=self.manager_path)
+ manager_props=dbus.Interface(self.manager_obj,dbus_interface=prop_iface)
+ try:
+ self.sinks=manager_props.Get(self.manager_iface,'EqualizedSinks')
+ except dbus.exceptions.DBusException:
+ # probably module not yet loaded, try to load it:
+ try:
+ core=self.connection.get_object(object_path=self.core_path)
+ core.LoadModule(self.module_name,{},dbus_interface=self.core_iface)
+ # yup, we don't need to re-create manager_obj and manager_props,
+ # these are late-bound
+ self.sinks=manager_props.Get(self.manager_iface,'EqualizedSinks')
+ except dbus.exceptions.DBusException:
+ sys.stderr.write('It seems that running pulseaudio does not support '
+ 'equalizer features and loading %s module failed.\n'
+ 'Exiting...\n' % self.module_name)
+ sys.exit(-1)
+
+ def set_callbacks(self):
+ manager=dbus.Interface(self.manager_obj,dbus_interface=self.manager_iface)
+ manager.connect_to_signal('ProfilesChanged',self.update_profiles)
+ manager.connect_to_signal('SinkAdded',self.sink_added)
+ manager.connect_to_signal('SinkRemoved',self.sink_removed)
+ #self._get_core().ListenForSignal(self.manager_iface,[])
+ #self._get_core().ListenForSignal(self.manager_iface,[dbus.ObjectPath(self.manager_path)])
+ #core=self._get_core()
+ #for x in ['ProfilesChanged','SinkAdded','SinkRemoved']:
+ # core.ListenForSignal("%s.%s" %(self.manager_iface,x),[dbus.ObjectPath(self.manager_path)])
+ self.update_profiles()
+ self.update_sinks()
+ def update_profiles(self):
+ #print('update profiles called!')
+ manager_props=dbus.Interface(self.manager_obj,dbus_interface=prop_iface)
+ self.profiles=manager_props.Get(self.manager_iface,'Profiles')
+ self.profile_box.blockSignals(True)
+ self.profile_box.clear()
+ self.profile_box.addItems(self.profiles)
+ self.profile_box.blockSignals(False)
+ self._set_profile_name()
+ def update_sinks(self):
+ self.sink_box.blockSignals(True)
+ self.sink_box.clear()
+ for x in self.sinks:
+ sink=self.connection.get_object(object_path=x)
+ sink_props=dbus.Interface(sink,dbus_interface=prop_iface)
+ simple_name=sink_props.Get(device_iface,'Name')
+ self.sink_box.addItem(simple_name,x)
+ self.sink_box.blockSignals(False)
+ self.sink_box.setMinimumSize(self.sink_box.sizeHint())
+ def read_filter(self):
+ #print(self.filter_frequencies)
+ self.filter_state.readback()
+ def reset(self):
+ coefs=dbus.Array([1/math.sqrt(2.0)]*(self.filter_state.filter_rate//2+1))
+ preamp=1.0
+ self.filter_state.set_filter(preamp,coefs)
+ def _set_profile_name(self):
+ self.profile_box.blockSignals(True)
+ profile_name=self.sink.BaseProfile(self.filter_state.channel)
+ if profile_name is not None:
+ i=self.profile_box.findText(profile_name)
+ if i>=0:
+ self.profile_box.setCurrentIndex(i)
+ self.profile_box.blockSignals(False)
+
+
+class SliderArray(QtWidgets.QWidget):
+ def __init__(self,filter_state,parent=None):
+ super(SliderArray,self).__init__(parent)
+ #self.setStyleSheet('padding: 0px; border-width: 0px; margin: 0px;')
+ #self.setStyleSheet('font-family: monospace;'+outline%('blue'))
+ self.filter_state=filter_state
+ self.setLayout(QtWidgets.QHBoxLayout())
+ self.sub_array=None
+ self.set_sub_array(SliderArraySub(self.filter_state))
+ self.inhibit_resize=0
+ def set_sub_array(self,widget):
+ if self.sub_array is not None:
+ self.layout().removeWidget(self.sub_array)
+ self.sub_array.disconnect_signals()
+ self.sub_array.deleteLater()
+ self.sub_array=widget
+ self.layout().addWidget(self.sub_array)
+ self.sub_array.connect_signals()
+ self.filter_state.readback()
+ def resizeEvent(self,event):
+ super(SliderArray,self).resizeEvent(event)
+ if self.inhibit_resize==0:
+ self.inhibit_resize+=1
+ #self.add_sliders_to_fit()
+ t=QtCore.QTimer(self)
+ t.setSingleShot(True)
+ t.setInterval(0)
+ t.timeout.connect(partial(self.add_sliders_to_fit,event))
+ t.start()
+ def add_sliders_to_fit(self,event):
+ if event.oldSize().width()>0 and event.size().width()>0:
+ i=len(self.filter_state.frequencies)*int(round(float(event.size().width())/event.oldSize().width()))
+ else:
+ i=len(self.filter_state.frequencies)
+
+ t_w=self.size().width()
+ def evaluate(filter_state, target, variable):
+ base_freqs=self.filter_state.freq_proper(self.filter_state.DEFAULT_FREQUENCIES)
+ filter_state._set_frequency_values(subdivide(base_freqs,variable))
+ new_widget=SliderArraySub(filter_state)
+ w=new_widget.sizeHint().width()
+ return w-target
+ def searcher(initial,evaluator):
+ i=initial
+ def d(e): return 1 if e>=0 else -1
+ error=evaluator(i)
+ old_direction=d(error)
+ i-=old_direction
+ while True:
+ error=evaluator(i)
+ direction=d(error)
+ if direction!=old_direction:
+ k=i-1
+ #while direction<0 and error!=0:
+ # k-=1
+ # error=evaluator(i)
+ # direction=d(error)
+ return k, evaluator(k)
+ i-=direction
+ old_direction=direction
+ searcher(i,partial(evaluate,self.filter_state,t_w))
+ self.set_sub_array(SliderArraySub(self.filter_state))
+ self.inhibit_resize-=1
+
+class SliderArraySub(QtWidgets.QWidget):
+ def __init__(self,filter_state,parent=None):
+ super(SliderArraySub,self).__init__(parent)
+ self.filter_state=filter_state
+ self.setLayout(QtWidgets.QGridLayout())
+ self.slider=[None]*len(self.filter_state.frequencies)
+ self.label=[None]*len(self.slider)
+ #self.setStyleSheet('padding: 0px; border-width: 0px; margin: 0px;')
+ #self.setStyleSheet('font-family: monospace;'+outline%('blue'))
+ qt=QtCore.Qt
+ #self.layout().setHorizontalSpacing(1)
+ def add_slider(slider,label, c):
+ self.layout().addWidget(slider,0,c,qt.AlignHCenter)
+ self.layout().addWidget(label,1,c,qt.AlignHCenter)
+ self.layout().setColumnMinimumWidth(c,max(label.sizeHint().width(),slider.sizeHint().width()))
+ def create_slider(slider_label):
+ slider=QtWidgets.QSlider(QtCore.Qt.Vertical,self)
+ label=SliderLabel(slider_label,filter_state,self)
+ slider.setRange(-1000,2000)
+ slider.setSingleStep(1)
+ return (slider,label)
+ self.preamp_slider,self.preamp_label=create_slider('Preamp')
+ add_slider(self.preamp_slider,self.preamp_label,0)
+ for i,hz in enumerate(self.filter_state.frequencies):
+ slider,label=create_slider(self.hz2label(hz))
+ self.slider[i]=slider
+ #slider.setStyleSheet('font-family: monospace;'+outline%('red',))
+ self.label[i]=label
+ c=i+1
+ add_slider(slider,label,i+1)
+ def hz2label(self, hz):
+ if hz==0:
+ label_text='DC'
+ elif hz==self.filter_state.sample_rate//2:
+ label_text='Coda'
+ else:
+ label_text=hz2str(hz)
+ return label_text
+
+ def connect_signals(self):
+ def connect(writer,reader,slider,label):
+ slider.valueChanged.connect(writer)
+ self.filter_state.readFilter.connect(reader)
+ label_cb=partial(slider.setValue,0)
+ label.clicked.connect(label_cb)
+ return label_cb
+
+ self.preamp_writer_cb=self.write_preamp
+ self.preamp_reader_cb=self.sync_preamp
+ self.preamp_label_cb=connect(self.preamp_writer_cb,
+ self.preamp_reader_cb,
+ self.preamp_slider,
+ self.preamp_label)
+ self.writer_callbacks=[None]*len(self.slider)
+ self.reader_callbacks=[None]*len(self.slider)
+ self.label_callbacks=[None]*len(self.label)
+ for i in range(len(self.slider)):
+ self.writer_callbacks[i]=partial(self.write_coefficient,i)
+ self.reader_callbacks[i]=partial(self.sync_coefficient,i)
+ self.label_callbacks[i]=connect(self.writer_callbacks[i],
+ self.reader_callbacks[i],
+ self.slider[i],
+ self.label[i])
+ def disconnect_signals(self):
+ def disconnect(writer,reader,label_cb,slider,label):
+ slider.valueChanged.disconnect(writer)
+ self.filter_state.readFilter.disconnect(reader)
+ label.clicked.disconnect(label_cb)
+ disconnect(self.preamp_writer_cb, self.preamp_reader_cb,
+ self.preamp_label_cb, self.preamp_slider, self.preamp_label)
+ for i in range(len(self.slider)):
+ disconnect(self.writer_callbacks[i],
+ self.reader_callbacks[i],
+ self.label_callbacks[i],
+ self.slider[i],
+ self.label[i])
+
+ def write_preamp(self, v):
+ self.filter_state.preamp=self.slider2coef(v)
+ self.filter_state.seed()
+ def sync_preamp(self):
+ self.preamp_slider.blockSignals(True)
+ self.preamp_slider.setValue(self.coef2slider(self.filter_state.preamp))
+ self.preamp_slider.blockSignals(False)
+
+
+ def write_coefficient(self,i,v):
+ self.filter_state.coefficients[i]=self.slider2coef(v)/math.sqrt(2.0)
+ self.filter_state.seed()
+ def sync_coefficient(self,i):
+ slider=self.slider[i]
+ slider.blockSignals(True)
+ slider.setValue(self.coef2slider(math.sqrt(2.0)*self.filter_state.coefficients[i]))
+ slider.blockSignals(False)
+ @staticmethod
+ def slider2coef(x):
+ return (1.0+(x/1000.0))
+ @staticmethod
+ def coef2slider(x):
+ return int((x-1.0)*1000)
+outline='border-width: 1px; border-style: solid; border-color: %s;'
+
+class SliderLabel(QtWidgets.QLabel):
+ clicked=QtCore.pyqtSignal()
+ def __init__(self,label_text,filter_state,parent=None):
+ super(SliderLabel,self).__init__(parent)
+ self.setStyleSheet('font-family: monospace;')
+ self.setText(label_text)
+ self.setMinimumSize(self.sizeHint())
+ def mouseDoubleClickEvent(self, event):
+ self.clicked.emit()
+ super(SliderLabel,self).mouseDoubleClickEvent(event)
+
+#until there are server side state savings, do it in the client but try and avoid
+#simulaneous broadcasting situations
+class FilterState(QtCore.QObject):
+ #DEFAULT_FREQUENCIES=map(float,[25,50,75,100,150,200,300,400,500,800,1e3,1.5e3,3e3,5e3,7e3,10e3,15e3,20e3])
+ DEFAULT_FREQUENCIES=[31.75,63.5,125,250,500,1e3,2e3,4e3,8e3,16e3]
+ readFilter=QtCore.pyqtSignal()
+ def __init__(self,sink):
+ super(FilterState,self).__init__()
+ self.sink_props=dbus.Interface(sink,dbus_interface=prop_iface)
+ self.sink=dbus.Interface(sink,dbus_interface=eq_iface)
+ self.sample_rate=self.get_eq_attr('SampleRate')
+ self.filter_rate=self.get_eq_attr('FilterSampleRate')
+ self.channels=self.get_eq_attr('NChannels')
+ self.channel=self.channels
+ self.set_frequency_values(self.DEFAULT_FREQUENCIES)
+ self.sync_timer=QtCore.QTimer()
+ self.sync_timer.setSingleShot(True)
+ self.sync_timer.timeout.connect(self.save_state)
+
+ def get_eq_attr(self,attr):
+ return self.sink_props.Get(eq_iface,attr)
+ def freq_proper(self,xs):
+ return [0]+xs+[self.sample_rate//2]
+ def _set_frequency_values(self,freqs):
+ self.frequencies=freqs
+ #print('base',self.frequencies)
+ self.filter_frequencies=[int(round(x)) for x in self.translate_rates(self.filter_rate,self.sample_rate,
+ self.frequencies)]
+ self.coefficients=[0.0]*len(self.frequencies)
+ self.preamp=1.0
+ def set_frequency_values(self,freqs):
+ self._set_frequency_values(self.freq_proper(freqs))
+ @staticmethod
+ def translate_rates(dst,src,rates):
+ return list([x*dst/src for x in rates])
+ def seed(self):
+ self.sink.SeedFilter(self.channel,self.filter_frequencies,self.coefficients,self.preamp)
+ self.sync_timer.start(SYNC_TIMEOUT)
+ def readback(self):
+ coefs,preamp=self.sink.FilterAtPoints(self.channel,self.filter_frequencies)
+ self.coefficients=coefs
+ self.preamp=preamp
+ self.readFilter.emit()
+ def set_filter(self,preamp,coefs):
+ self.sink.SetFilter(self.channel,dbus.Array(coefs),self.preamp)
+ self.sync_timer.start(SYNC_TIMEOUT)
+ def save_state(self):
+ print('saving state')
+ self.sink.SaveState()
+ def load_profile(self,profile):
+ self.sink.LoadProfile(self.channel,dbus.String(profile))
+ self.sync_timer.start(SYNC_TIMEOUT)
+ def flush_state(self):
+ if self.sync_timer.isActive():
+ self.sync_timer.stop()
+ self.save_state()
+
+
+def safe_log(k,b):
+ i=0
+ while k//b!=0:
+ i+=1
+ k=k//b
+ return i
+def hz2str(hz):
+ p=safe_log(hz,10.0)
+ if p<3:
+ return '%dHz' %(hz,)
+ elif hz%1000==0:
+ return '%dKHz' %(hz/(10.0**3),)
+ else:
+ return '%.1fKHz' %(hz/(10.0**3),)
+
+def subdivide(xs, t_points):
+ while len(xs)<t_points:
+ m=[0]*(2*len(xs)-1)
+ m[0:len(m):2]=xs
+ for i in range(1,len(m),2):
+ m[i]=(m[i-1]+m[i+1])//2
+ xs=m
+ p_drop=len(xs)-t_points
+ p_drop_left=p_drop//2
+ p_drop_right=p_drop-p_drop_left
+ #print('xs',xs)
+ #print('dropping %d, %d left, %d right' %(p_drop,p_drop_left,p_drop_right))
+ c=len(xs)//2
+ left=xs[0:p_drop_left*2:2]+xs[p_drop_left*2:c]
+ right=list(reversed(xs[c:]))
+ right=right[0:p_drop_right*2:2]+right[p_drop_right*2:]
+ right=list(reversed(right))
+ return left+right
+
+def main():
+ dbus.mainloop.pyqt5.DBusQtMainLoop(set_as_default=True)
+ app=QtWidgets.QApplication(sys.argv)
+ qpaeq_main=QPaeq()
+ qpaeq_main.show()
+ sys.exit(app.exec_())
+
+if __name__=='__main__':
+ main()