Files
bananarchy/src/dwm-plugins/sxmo_vibrate.c
T

1017 lines
29 KiB
C
Raw Normal View History

#include <alsa/asoundlib.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <glob.h>
#include <grp.h>
#include <linux/input.h>
#include <math.h>
#include <pulse/pulseaudio.h>
#include <signal.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
#define HAPTIC_REF_RX3_VOL 84L
#define HAPTIC_REF_AMP_L1 1950.0
#define HAPTIC_REF_AMP_L2 2550.0
#define HAPTIC_REF_AMP_L3 3300.0
static volatile sig_atomic_t g_stop = 0;
static void handle_signal(int sig) {
(void)sig;
g_stop = 1;
}
static void get_sxmo_config_dir(char* out, size_t out_sz) {
const char* cfg = getenv("XDG_CONFIG_HOME");
const char* home = getenv("HOME");
if (cfg && *cfg) {
snprintf(out, out_sz, "%s/sxmo", cfg);
} else if (home && *home) {
snprintf(out, out_sz, "%s/.config/sxmo", home);
} else {
snprintf(out, out_sz, "/home/user/.config/sxmo");
}
}
static int is_vibrate_muted(void) {
const char* force = getenv("SXMO_VIBRATE_FORCE");
if (force && *force == '1') {
return 0;
}
char dir[448];
char path[512];
get_sxmo_config_dir(dir, sizeof(dir));
snprintf(path, sizeof(path), "%s/.novibrate", dir);
return access(path, F_OK) == 0;
}
static int read_configured_level(void) {
char dir[448];
char path[512];
get_sxmo_config_dir(dir, sizeof(dir));
snprintf(path, sizeof(path), "%s/ringsettings", dir);
FILE* fp = fopen(path, "r");
if (!fp) return 0;
int level = 0;
char line[256];
while (fgets(line, sizeof(line), fp)) {
char* p = line;
while (*p == ' ' || *p == '\t') ++p;
if (strncmp(p, "SXMO_VIBRATE_STRENGTH=", 22) == 0) {
int v = atoi(p + 22);
if (v >= 1 && v <= 3) level = v;
else if (v > 3 && v <= 16000) level = 1;
else if (v > 16000 && v <= 45000) level = 2;
else if (v > 45000) level = 3;
}
}
fclose(fp);
return level;
}
static int resolve_level_and_magnitude(int raw_arg, int has_arg, int* level_out) {
int val = raw_arg;
const char* env_str = getenv("SXMO_VIBRATE_STRENGTH");
if (!has_arg || (val == 1 && (!env_str || !*env_str))) {
int cfg = read_configured_level();
if (cfg >= 1 && cfg <= 3) {
val = cfg;
} else if (env_str && *env_str) {
int ev = atoi(env_str);
if (ev >= 1) val = ev;
} else if (!has_arg) {
val = 2;
}
}
int level = 2;
int mag = 32000;
if (val <= 1 || (val >= 256 && val <= 16000)) {
level = 1;
mag = 14000;
} else if (val == 2 || (val > 16000 && val <= 45000)) {
level = 2;
mag = 32000;
} else {
level = 3;
mag = 65535;
}
if (level_out) *level_out = level;
return mag;
}
static int open_vibrator_device(void) {
const char* env_dev = getenv("SXMO_VIBRATE_DEV");
if (env_dev && *env_dev) {
int fd = open(env_dev, O_RDWR | O_CLOEXEC);
if (fd >= 0) return fd;
}
int fd = open("/dev/input/by-path/platform-vibrator-event", O_RDWR | O_CLOEXEC);
if (fd >= 0) return fd;
glob_t g;
memset(&g, 0, sizeof(g));
if (glob("/dev/input/by-path/*vibrator*-event", 0, NULL, &g) == 0) {
for (size_t i = 0; i < g.gl_pathc; ++i) {
fd = open(g.gl_pathv[i], O_RDWR | O_CLOEXEC);
if (fd >= 0) {
globfree(&g);
return fd;
}
}
globfree(&g);
}
return -1;
}
static void sleep_ms_interruptible(long ms) {
if (ms <= 0 || g_stop) return;
struct timespec req;
req.tv_sec = ms / 1000;
req.tv_nsec = (ms % 1000) * 1000000L;
while (!g_stop && nanosleep(&req, &req) == -1 && errno == EINTR) {
}
}
static int contains_icase(const char* hay, const char* needle) {
if (!hay || !needle || !*needle) return 0;
size_t nlen = strlen(needle);
for (const char* p = hay; *p; ++p) {
size_t i = 0;
while (i < nlen && p[i] &&
tolower((unsigned char)p[i]) == tolower((unsigned char)needle[i])) {
++i;
}
if (i == nlen) return 1;
}
return 0;
}
static int is_haptic_audio_device(void) {
const char* env_ha = getenv("SXMO_VIBRATE_HAPTIC_AUDIO");
if (env_ha && *env_ha == '1') return 1;
if (env_ha && *env_ha == '0') return 0;
int fd = open("/sys/firmware/devicetree/base/compatible", O_RDONLY | O_CLOEXEC);
if (fd < 0) return 0;
char buf[256];
ssize_t n = read(fd, buf, sizeof(buf) - 1);
close(fd);
if (n <= 0) return 0;
buf[n] = '\0';
const char* p = buf;
const char* end = buf + n;
while (p < end && *p) {
if (strcmp(p, "nokia,sparkler") == 0 || strcmp(p, "nokia,leo") == 0) {
return 1;
}
p += strlen(p) + 1;
}
return 0;
}
static int is_non_speaker_name(const char* s) {
return contains_icase(s, "Headphone") ||
contains_icase(s, "Headset") ||
contains_icase(s, "Earpiece") ||
contains_icase(s, "Bluetooth") ||
contains_icase(s, "bluez");
}
static int is_non_speaker_audio_route(void) {
FILE* sco_fp = fopen("/tmp/sxmo_bt_sco_mm_active", "r");
if (sco_fp) {
int ch = fgetc(sco_fp);
fclose(sco_fp);
if (ch == '1') {
return 1;
}
}
char buf[128];
const char* paths[2];
char cfg_dir[448];
char cfg_path[512];
get_sxmo_config_dir(cfg_dir, sizeof(cfg_dir));
snprintf(cfg_path, sizeof(cfg_path), "%s/audio_out_device", cfg_dir);
paths[0] = "/tmp/sxmo_audio_out_device";
paths[1] = cfg_path;
for (int i = 0; i < 2; ++i) {
FILE* fp = fopen(paths[i], "r");
if (!fp) continue;
if (fgets(buf, sizeof(buf), fp)) {
fclose(fp);
return is_non_speaker_name(buf);
}
fclose(fp);
}
return 0;
}
static int is_pw_sink_muted(void) {
FILE* fp = fopen("/tmp/sxmo_pw_sink_muted", "r");
if (!fp) return 0;
int ch = fgetc(fp);
fclose(fp);
return ch == '1';
}
static double read_haptic_scale_env(void) {
const char* env_sc = getenv("SXMO_VIBRATE_HAPTIC_SCALE");
if (!env_sc || !*env_sc) return 1.0;
char* endp = NULL;
errno = 0;
double v = strtod(env_sc, &endp);
if (errno != 0 || !endp || *endp != '\0' || !isfinite(v)) return 1.0;
if (v < 0.05) v = 0.05;
if (v > 4.0) v = 4.0;
return v;
}
static long monotonic_ms(void) {
struct timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) return 0;
return (long)ts.tv_sec * 1000L + ts.tv_nsec / 1000000L;
}
#define HAPTIC_PW_MAX_INPUTS 32
struct haptic_pw_input {
uint32_t index;
int muted;
};
struct haptic_pw_state {
pa_mainloop* ml;
pa_context* ctx;
int connected;
int sink_found;
int non_speaker;
uint32_t sink_index;
int sink_muted;
pa_cvolume sink_vol;
double linear_gain;
int n_inputs;
struct haptic_pw_input inputs[HAPTIC_PW_MAX_INPUTS];
int n_saved_muted_inputs;
uint32_t saved_muted_inputs[HAPTIC_PW_MAX_INPUTS];
int modified_sink_vol;
int modified_sink_mute;
pa_cvolume orig_sink_vol;
int orig_sink_mute;
};
struct pw_query_wait {
struct haptic_pw_state* pw;
int ctx_ready;
int ctx_failed;
int sink_done;
int inputs_done;
int op_done;
};
static void pw_context_state_cb(pa_context* c, void* userdata) {
struct pw_query_wait* q = (struct pw_query_wait*)userdata;
pa_context_state_t st = pa_context_get_state(c);
if (st == PA_CONTEXT_READY) {
q->ctx_ready = 1;
} else if (st == PA_CONTEXT_FAILED || st == PA_CONTEXT_TERMINATED) {
q->ctx_failed = 1;
}
}
static void pw_sink_info_cb(pa_context* c, const pa_sink_info* i, int eol,
void* userdata) {
(void)c;
struct pw_query_wait* q = (struct pw_query_wait*)userdata;
struct haptic_pw_state* pw = q->pw;
if (eol > 0) {
q->sink_done = 1;
return;
}
if (!i || pw->sink_found) return;
pw->sink_found = 1;
pw->sink_index = i->index;
pw->sink_muted = i->mute ? 1 : 0;
pw->sink_vol = i->volume;
pw->orig_sink_vol = i->volume;
pw->orig_sink_mute = i->mute ? 1 : 0;
pw->linear_gain = pa_sw_volume_to_linear(pa_cvolume_max(&i->volume));
if (is_non_speaker_name(i->name) || is_non_speaker_name(i->description)) {
pw->non_speaker = 1;
} else if (i->active_port &&
(is_non_speaker_name(i->active_port->name) ||
is_non_speaker_name(i->active_port->description))) {
pw->non_speaker = 1;
}
}
static void pw_sink_input_info_cb(pa_context* c, const pa_sink_input_info* i,
int eol, void* userdata) {
(void)c;
struct pw_query_wait* q = (struct pw_query_wait*)userdata;
struct haptic_pw_state* pw = q->pw;
if (eol > 0) {
q->inputs_done = 1;
return;
}
if (!i || !pw->sink_found || i->sink != pw->sink_index || i->corked) return;
if (pw->n_inputs < HAPTIC_PW_MAX_INPUTS) {
pw->inputs[pw->n_inputs].index = i->index;
pw->inputs[pw->n_inputs].muted = i->mute ? 1 : 0;
pw->n_inputs++;
}
}
static void pw_success_cb(pa_context* c, int success, void* userdata) {
(void)c;
(void)success;
struct pw_query_wait* q = (struct pw_query_wait*)userdata;
q->op_done = 1;
}
static void pw_wait_until(pa_mainloop* ml, const int* done_flag,
const int* fail_flag, long timeout_ms,
int honor_stop) {
long start = monotonic_ms();
while (!*done_flag && (!fail_flag || !*fail_flag)) {
if (honor_stop && g_stop) break;
if (monotonic_ms() - start >= timeout_ms) break;
if (pa_mainloop_prepare(ml, 10000) < 0) break;
int prc = pa_mainloop_poll(ml);
if (prc < 0 && errno != EINTR) break;
if (pa_mainloop_dispatch(ml) < 0) break;
}
}
static void haptic_pw_run_op(struct haptic_pw_state* pw, pa_operation* op,
struct pw_query_wait* q, int* flag,
long timeout_ms, int honor_stop) {
if (!op) return;
pw_wait_until(pw->ml, flag, &q->ctx_failed, timeout_ms, honor_stop);
if (pa_operation_get_state(op) == PA_OPERATION_RUNNING) {
pa_operation_cancel(op);
}
pa_operation_unref(op);
}
static void haptic_pw_connect_and_query(struct haptic_pw_state* pw) {
memset(pw, 0, sizeof(*pw));
pw->ml = pa_mainloop_new();
if (!pw->ml) return;
pa_mainloop_api* api = pa_mainloop_get_api(pw->ml);
pw->ctx = pa_context_new(api, "sxmo_vibrate");
if (!pw->ctx) {
pa_mainloop_free(pw->ml);
pw->ml = NULL;
return;
}
struct pw_query_wait q;
memset(&q, 0, sizeof(q));
q.pw = pw;
pa_context_set_state_callback(pw->ctx, pw_context_state_cb, &q);
if (pa_context_connect(pw->ctx, NULL, PA_CONTEXT_NOAUTOSPAWN, NULL) < 0) {
pa_context_unref(pw->ctx);
pw->ctx = NULL;
pa_mainloop_free(pw->ml);
pw->ml = NULL;
return;
}
pw_wait_until(pw->ml, &q.ctx_ready, &q.ctx_failed, 150, 1);
if (!q.ctx_ready || q.ctx_failed) {
pa_context_disconnect(pw->ctx);
pa_context_unref(pw->ctx);
pw->ctx = NULL;
pa_mainloop_free(pw->ml);
pw->ml = NULL;
return;
}
pw->connected = 1;
pa_operation* op = pa_context_get_sink_info_by_name(
pw->ctx, "@DEFAULT_SINK@", pw_sink_info_cb, &q);
haptic_pw_run_op(pw, op, &q, &q.sink_done, 150, 1);
if (pw->sink_found && !pw->non_speaker && !g_stop) {
op = pa_context_get_sink_input_info_list(pw->ctx, pw_sink_input_info_cb, &q);
haptic_pw_run_op(pw, op, &q, &q.inputs_done, 150, 1);
}
}
static int haptic_pw_prepare_muted_bypass(struct haptic_pw_state* pw) {
if (!pw || !pw->connected || !pw->sink_found) return -1;
if (!PA_CONTEXT_IS_GOOD(pa_context_get_state(pw->ctx))) return -1;
struct pw_query_wait q;
memset(&q, 0, sizeof(q));
q.pw = pw;
/* Silence active inputs before temporarily unmuting the muted sink. */
for (int i = 0; i < pw->n_inputs; ++i) {
if (!pw->inputs[i].muted &&
pw->n_saved_muted_inputs < HAPTIC_PW_MAX_INPUTS) {
q.op_done = 0;
pa_operation* op = pa_context_set_sink_input_mute(
pw->ctx, pw->inputs[i].index, 1, pw_success_cb, &q);
haptic_pw_run_op(pw, op, &q, &q.op_done, 100, 1);
pw->saved_muted_inputs[pw->n_saved_muted_inputs++] = pw->inputs[i].index;
}
}
pa_cvolume unity_vol;
uint8_t ch = pw->orig_sink_vol.channels;
if (ch < 1 || ch > PA_CHANNELS_MAX) ch = 2;
pa_cvolume_set(&unity_vol, ch, PA_VOLUME_NORM);
q.op_done = 0;
pa_operation* vop = pa_context_set_sink_volume_by_index(
pw->ctx, pw->sink_index, &unity_vol, pw_success_cb, &q);
haptic_pw_run_op(pw, vop, &q, &q.op_done, 100, 1);
pw->modified_sink_vol = 1;
q.op_done = 0;
pa_operation* mop = pa_context_set_sink_mute_by_index(
pw->ctx, pw->sink_index, 0, pw_success_cb, &q);
haptic_pw_run_op(pw, mop, &q, &q.op_done, 100, 1);
pw->modified_sink_mute = 1;
return g_stop ? -1 : 0;
}
static void haptic_pw_restore_and_close(struct haptic_pw_state* pw) {
if (!pw) return;
if (pw->ctx) {
if (pw->connected && pw->sink_found &&
PA_CONTEXT_IS_GOOD(pa_context_get_state(pw->ctx))) {
struct pw_query_wait q;
memset(&q, 0, sizeof(q));
q.pw = pw;
if (pw->modified_sink_mute) {
q.op_done = 0;
pa_operation* mop = pa_context_set_sink_mute_by_index(
pw->ctx, pw->sink_index, pw->orig_sink_mute, pw_success_cb, &q);
haptic_pw_run_op(pw, mop, &q, &q.op_done, 100, 0);
}
if (pw->modified_sink_vol) {
q.op_done = 0;
pa_operation* vop = pa_context_set_sink_volume_by_index(
pw->ctx, pw->sink_index, &pw->orig_sink_vol, pw_success_cb, &q);
haptic_pw_run_op(pw, vop, &q, &q.op_done, 100, 0);
}
for (int i = 0; i < pw->n_saved_muted_inputs; ++i) {
q.op_done = 0;
pa_operation* iop = pa_context_set_sink_input_mute(
pw->ctx, pw->saved_muted_inputs[i], 0, pw_success_cb, &q);
haptic_pw_run_op(pw, iop, &q, &q.op_done, 100, 0);
}
}
pa_context_disconnect(pw->ctx);
pa_context_unref(pw->ctx);
pw->ctx = NULL;
}
if (pw->ml) {
pa_mainloop_free(pw->ml);
pw->ml = NULL;
}
}
struct haptic_ctl_state {
snd_ctl_t* ctl;
int has_spk_sw;
long saved_spk_sw;
int changed_spk_sw;
int has_pri_mm1;
long saved_pri_mm1;
int changed_pri_mm1;
int has_rx3_mux;
unsigned int saved_rx3_mux;
int changed_rx3_mux;
int has_rx3_vol;
long saved_rx3_vol;
long active_rx3_vol;
long min_rx3_vol;
long max_rx3_vol;
int changed_rx3_vol;
};
static int ctl_read_elem(snd_ctl_t* ctl, const char* name,
snd_ctl_elem_info_t* info,
snd_ctl_elem_value_t* val) {
snd_ctl_elem_info_clear(info);
snd_ctl_elem_info_set_interface(info, SND_CTL_ELEM_IFACE_MIXER);
snd_ctl_elem_info_set_name(info, name);
if (snd_ctl_elem_info(ctl, info) < 0) return -1;
snd_ctl_elem_value_clear(val);
snd_ctl_elem_value_set_interface(val, SND_CTL_ELEM_IFACE_MIXER);
snd_ctl_elem_value_set_name(val, name);
if (snd_ctl_elem_read(ctl, val) < 0) return -1;
return 0;
}
static void haptic_ctl_open(struct haptic_ctl_state* st) {
memset(st, 0, sizeof(*st));
if (snd_ctl_open(&st->ctl, "hw:0", 0) < 0) {
st->ctl = NULL;
return;
}
snd_ctl_elem_info_t* info = NULL;
snd_ctl_elem_value_t* val = NULL;
snd_ctl_elem_info_alloca(&info);
snd_ctl_elem_value_alloca(&val);
if (ctl_read_elem(st->ctl, "PRI_MI2S_RX Audio Mixer MultiMedia1",
info, val) == 0) {
st->has_pri_mm1 = 1;
st->saved_pri_mm1 = snd_ctl_elem_value_get_boolean(val, 0);
}
if (ctl_read_elem(st->ctl, "RX3 MIX1 INP1", info, val) == 0) {
st->has_rx3_mux = 1;
st->saved_rx3_mux = snd_ctl_elem_value_get_enumerated(val, 0);
}
if (ctl_read_elem(st->ctl, "SPK DAC Switch", info, val) == 0) {
st->has_spk_sw = 1;
st->saved_spk_sw = snd_ctl_elem_value_get_boolean(val, 0);
}
if (ctl_read_elem(st->ctl, "RX3 Digital Volume", info, val) == 0) {
st->has_rx3_vol = 1;
st->saved_rx3_vol = snd_ctl_elem_value_get_integer(val, 0);
st->active_rx3_vol = st->saved_rx3_vol;
st->min_rx3_vol = snd_ctl_elem_info_get_min(info);
st->max_rx3_vol = snd_ctl_elem_info_get_max(info);
}
}
static void haptic_ensure_speaker_ctl(struct haptic_ctl_state* st,
long target_rx3_vol) {
if (!st || !st->ctl) return;
snd_ctl_elem_info_t* info = NULL;
snd_ctl_elem_value_t* val = NULL;
snd_ctl_elem_info_alloca(&info);
snd_ctl_elem_value_alloca(&val);
if (st->has_pri_mm1 && st->saved_pri_mm1 == 0 &&
ctl_read_elem(st->ctl, "PRI_MI2S_RX Audio Mixer MultiMedia1",
info, val) == 0) {
snd_ctl_elem_value_set_boolean(val, 0, 1);
if (snd_ctl_elem_write(st->ctl, val) >= 0) st->changed_pri_mm1 = 1;
}
if (st->has_rx3_mux && st->saved_rx3_mux == 0 &&
ctl_read_elem(st->ctl, "RX3 MIX1 INP1", info, val) == 0) {
unsigned int items = snd_ctl_elem_info_get_items(info);
for (unsigned int i = 0; i < items; ++i) {
snd_ctl_elem_info_set_item(info, i);
if (snd_ctl_elem_info(st->ctl, info) == 0 &&
strcmp(snd_ctl_elem_info_get_item_name(info), "RX1") == 0) {
snd_ctl_elem_value_set_enumerated(val, 0, i);
if (snd_ctl_elem_write(st->ctl, val) >= 0) st->changed_rx3_mux = 1;
break;
}
}
}
if (st->has_spk_sw && st->saved_spk_sw == 0 &&
ctl_read_elem(st->ctl, "SPK DAC Switch", info, val) == 0) {
snd_ctl_elem_value_set_boolean(val, 0, 1);
if (snd_ctl_elem_write(st->ctl, val) >= 0) st->changed_spk_sw = 1;
}
if (st->has_rx3_vol && target_rx3_vol >= 0 &&
st->saved_rx3_vol != target_rx3_vol &&
ctl_read_elem(st->ctl, "RX3 Digital Volume", info, val) == 0) {
long target = target_rx3_vol;
if (target < st->min_rx3_vol) target = st->min_rx3_vol;
if (target > st->max_rx3_vol) target = st->max_rx3_vol;
snd_ctl_elem_value_set_integer(val, 0, target);
if (snd_ctl_elem_write(st->ctl, val) >= 0) {
st->changed_rx3_vol = 1;
st->active_rx3_vol = target;
}
}
}
static void haptic_restore_speaker_ctl(struct haptic_ctl_state* st) {
if (!st || !st->ctl) return;
snd_ctl_elem_info_t* info = NULL;
snd_ctl_elem_value_t* val = NULL;
snd_ctl_elem_info_alloca(&info);
snd_ctl_elem_value_alloca(&val);
if (st->changed_rx3_vol && st->has_rx3_vol &&
ctl_read_elem(st->ctl, "RX3 Digital Volume", info, val) == 0) {
snd_ctl_elem_value_set_integer(val, 0, st->saved_rx3_vol);
(void)snd_ctl_elem_write(st->ctl, val);
}
if (st->changed_spk_sw && st->has_spk_sw &&
ctl_read_elem(st->ctl, "SPK DAC Switch", info, val) == 0) {
snd_ctl_elem_value_set_boolean(val, 0, st->saved_spk_sw);
(void)snd_ctl_elem_write(st->ctl, val);
}
if (st->changed_rx3_mux && st->has_rx3_mux &&
ctl_read_elem(st->ctl, "RX3 MIX1 INP1", info, val) == 0) {
snd_ctl_elem_value_set_enumerated(val, 0, st->saved_rx3_mux);
(void)snd_ctl_elem_write(st->ctl, val);
}
if (st->changed_pri_mm1 && st->has_pri_mm1 &&
ctl_read_elem(st->ctl, "PRI_MI2S_RX Audio Mixer MultiMedia1",
info, val) == 0) {
snd_ctl_elem_value_set_boolean(val, 0, st->saved_pri_mm1);
(void)snd_ctl_elem_write(st->ctl, val);
}
snd_ctl_close(st->ctl);
st->ctl = NULL;
}
static int write_pcm_frames_all(snd_pcm_t* pcm, const void* buf,
snd_pcm_uframes_t frames,
size_t frame_bytes) {
const char* bytes = (const char*)buf;
snd_pcm_uframes_t off = 0;
while (off < frames && !g_stop) {
snd_pcm_sframes_t rc =
snd_pcm_writei(pcm, bytes + off * frame_bytes, frames - off);
if (rc == -EAGAIN || rc == -EINTR) {
continue;
}
if (rc < 0) {
rc = snd_pcm_recover(pcm, (int)rc, 1);
if (rc < 0) return -1;
continue;
}
off += (snd_pcm_uframes_t)rc;
}
return g_stop ? -1 : 0;
}
static double haptic_pulse_env(long idx, long total_frames, long fade_frames) {
if (fade_frames <= 0) return 1.0;
if (idx < fade_frames) {
return 0.5 * (1.0 - cos(M_PI * (double)idx / (double)fade_frames));
}
if (idx >= total_frames - fade_frames) {
long tail = total_frames - 1 - idx;
return 0.5 * (1.0 - cos(M_PI * (double)tail / (double)fade_frames));
}
return 1.0;
}
static int write_haptic_pulse(snd_pcm_t* pcm, long ms, double amp,
int is_float) {
if (ms <= 0 || g_stop) return 0;
const long rate = 48000L;
const double step = 2.0 * M_PI * 157.0 / (double)rate;
const long total_frames = (ms * rate) / 1000L;
long fade_frames = (10L * rate) / 1000L;
if (fade_frames > total_frames / 2) fade_frames = total_frames / 2;
short chunk_s16[2400 * 2];
float chunk_f32[2400 * 2];
long pos = 0;
while (pos < total_frames && !g_stop) {
long n = total_frames - pos;
if (n > 2400L) n = 2400L;
for (long i = 0; i < n; ++i) {
long idx = pos + i;
double v = haptic_pulse_env(idx, total_frames, fade_frames) * amp *
sin(step * (double)idx);
if (is_float) {
float fv = (float)v;
chunk_f32[i * 2] = fv;
chunk_f32[i * 2 + 1] = fv;
} else {
if (v > 32767.0) v = 32767.0;
if (v < -32767.0) v = -32767.0;
short s = (short)lrint(v);
chunk_s16[i * 2] = s;
chunk_s16[i * 2 + 1] = s;
}
}
const void* ptr = is_float ? (const void*)chunk_f32 : (const void*)chunk_s16;
size_t fbytes = is_float ? (sizeof(float) * 2U) : (sizeof(short) * 2U);
if (write_pcm_frames_all(pcm, ptr, (snd_pcm_uframes_t)n, fbytes) < 0) {
return -1;
}
pos += n;
}
return 0;
}
static int write_haptic_silence(snd_pcm_t* pcm, long ms, int is_float) {
if (ms <= 0 || g_stop) return 0;
const long total_frames = (ms * 48000L) / 1000L;
short zeros_s16[2400 * 2];
float zeros_f32[2400 * 2];
if (is_float) {
memset(zeros_f32, 0, sizeof(zeros_f32));
} else {
memset(zeros_s16, 0, sizeof(zeros_s16));
}
const void* ptr = is_float ? (const void*)zeros_f32 : (const void*)zeros_s16;
size_t fbytes = is_float ? (sizeof(float) * 2U) : (sizeof(short) * 2U);
long pos = 0;
while (pos < total_frames && !g_stop) {
long n = total_frames - pos;
if (n > 2400L) n = 2400L;
if (write_pcm_frames_all(pcm, ptr, (snd_pcm_uframes_t)n, fbytes) < 0) {
return -1;
}
pos += n;
}
return 0;
}
static void play_haptic_pattern(snd_pcm_t* pcm, long duration_ms, int level,
double amp, int is_float) {
if (duration_ms <= 90) {
long actual_ms = (level <= 1 && duration_ms > 60) ? 60 : duration_ms;
(void)write_haptic_pulse(pcm, actual_ms, amp, is_float);
return;
}
long on_ms = 140;
long off_ms = 90;
if (level <= 1) {
on_ms = 85;
off_ms = 115;
} else if (level >= 3) {
on_ms = 240;
off_ms = 60;
}
long rem = duration_ms;
while (rem > 0 && !g_stop) {
long cur_on = (rem < on_ms) ? rem : on_ms;
if (write_haptic_pulse(pcm, cur_on, amp, is_float) < 0) break;
rem -= cur_on;
if (rem <= 0 || g_stop) break;
long cur_off = (rem < off_ms) ? rem : off_ms;
if (write_haptic_silence(pcm, cur_off, is_float) < 0) break;
rem -= cur_off;
}
}
static snd_pcm_t* open_haptic_pcm(const char* dev, snd_pcm_format_t fmt) {
snd_pcm_t* pcm = NULL;
if (snd_pcm_open(&pcm, dev, SND_PCM_STREAM_PLAYBACK, 0) < 0) {
return NULL;
}
if (snd_pcm_set_params(pcm, fmt, SND_PCM_ACCESS_RW_INTERLEAVED, 2, 48000,
1, 500000) < 0) {
snd_pcm_close(pcm);
return NULL;
}
return pcm;
}
static int vibrate_haptic_audio(long duration_ms, int level) {
if (is_non_speaker_audio_route()) {
return 0;
}
/* Match PipeWire socket ownership when invoked from a root hook/shell. */
if (getuid() == 0 && access("/run/user/10000/pipewire-0", F_OK) == 0) {
(void)initgroups("user", 10000);
if (setgid(10000) == 0 && setuid(10000) == 0) {
(void)setenv("HOME", "/home/user", 1);
(void)setenv("XDG_RUNTIME_DIR", "/run/user/10000", 1);
}
} else {
const char* xdg = getenv("XDG_RUNTIME_DIR");
struct stat st_rt;
if (!xdg || !*xdg || stat(xdg, &st_rt) != 0) {
char rt_buf[64];
snprintf(rt_buf, sizeof(rt_buf), "/run/user/%lu",
(unsigned long)getuid());
(void)setenv("XDG_RUNTIME_DIR", rt_buf, 1);
}
}
struct haptic_pw_state pw;
haptic_pw_connect_and_query(&pw);
if (pw.non_speaker || g_stop) {
haptic_pw_restore_and_close(&pw);
return 0;
}
double amp_ref = HAPTIC_REF_AMP_L2;
if (level <= 1) amp_ref = HAPTIC_REF_AMP_L1;
else if (level >= 3) amp_ref = HAPTIC_REF_AMP_L3;
amp_ref *= read_haptic_scale_env();
double amp_norm = amp_ref / 32768.0;
if (amp_norm > 0.92) amp_norm = 0.92;
struct haptic_ctl_state ctl_st;
haptic_ctl_open(&ctl_st);
snd_pcm_t* pcm = NULL;
int use_float = 0;
double play_amp = amp_ref;
int pw_unmuted = pw.connected && pw.sink_found && !pw.sink_muted &&
pw.linear_gain >= 1e-4 && !is_pw_sink_muted();
if (pw_unmuted) {
long cur_rx3 = ctl_st.has_rx3_vol ? ctl_st.saved_rx3_vol : HAPTIC_REF_RX3_VOL;
double cur_gain_rx3 =
(cur_rx3 <= 0) ? 0.0 : pow(10.0, ((double)cur_rx3 - 84.0) / 20.0);
long target_rx3 = -1;
if (cur_rx3 <= 0 ||
(pw.n_inputs == 0 && (cur_gain_rx3 <= 0.0 ||
amp_norm / cur_gain_rx3 > 0.92))) {
target_rx3 = HAPTIC_REF_RX3_VOL;
}
haptic_ensure_speaker_ctl(&ctl_st, target_rx3);
long eff_rx3 =
ctl_st.has_rx3_vol ? ctl_st.active_rx3_vol : HAPTIC_REF_RX3_VOL;
double gain_rx3 = pow(10.0, ((double)eff_rx3 - 84.0) / 20.0);
double post_pw = (gain_rx3 > 1e-6) ? (amp_norm / gain_rx3) : 0.92;
if (post_pw > 0.92) post_pw = 0.92;
pcm = open_haptic_pcm("default", SND_PCM_FORMAT_FLOAT_LE);
if (pcm) {
use_float = 1;
play_amp = post_pw / pw.linear_gain;
} else {
haptic_restore_speaker_ctl(&ctl_st);
haptic_ctl_open(&ctl_st);
}
}
if (!pcm) {
pcm = open_haptic_pcm("plughw:0,0", SND_PCM_FORMAT_S16_LE);
if (pcm) {
haptic_ensure_speaker_ctl(&ctl_st, HAPTIC_REF_RX3_VOL);
long eff_rx3 =
ctl_st.has_rx3_vol ? ctl_st.active_rx3_vol : HAPTIC_REF_RX3_VOL;
double gain_rx3 = pow(10.0, ((double)eff_rx3 - 84.0) / 20.0);
double post_pw = (gain_rx3 > 1e-6) ? (amp_norm / gain_rx3) : 0.92;
if (post_pw > 0.92) post_pw = 0.92;
use_float = 0;
play_amp = post_pw * 32767.0;
} else if (pw.connected && pw.sink_found) {
if (haptic_pw_prepare_muted_bypass(&pw) == 0) {
haptic_ensure_speaker_ctl(&ctl_st, HAPTIC_REF_RX3_VOL);
pcm = open_haptic_pcm("default", SND_PCM_FORMAT_FLOAT_LE);
if (pcm) {
long eff_rx3 =
ctl_st.has_rx3_vol ? ctl_st.active_rx3_vol : HAPTIC_REF_RX3_VOL;
double gain_rx3 = pow(10.0, ((double)eff_rx3 - 84.0) / 20.0);
double post_pw = (gain_rx3 > 1e-6) ? (amp_norm / gain_rx3) : 0.92;
if (post_pw > 0.92) post_pw = 0.92;
use_float = 1;
play_amp = post_pw;
}
}
}
}
if (!pcm) {
haptic_restore_speaker_ctl(&ctl_st);
haptic_pw_restore_and_close(&pw);
fprintf(stderr, "sxmo_vibrate: cannot open haptic audio PCM\n");
return 1;
}
play_haptic_pattern(pcm, duration_ms, level, play_amp, use_float);
if (g_stop) {
(void)snd_pcm_drop(pcm);
} else {
(void)snd_pcm_drain(pcm);
}
snd_pcm_close(pcm);
haptic_restore_speaker_ctl(&ctl_st);
haptic_pw_restore_and_close(&pw);
return 0;
}
int main(int argc, char** argv) {
if (argc < 2 || argc > 3) {
fprintf(stderr, "Usage: sxmo_vibrate duration_ms [strength_number]\n");
return 1;
}
char* endp = NULL;
errno = 0;
long duration_ms = strtol(argv[1], &endp, 10);
if (errno != 0 || !endp || *endp != '\0' || duration_ms <= 0) {
fprintf(stderr, "sxmo_vibrate: invalid duration\n");
return 1;
}
if (is_vibrate_muted()) {
return 0;
}
int raw_strength = 2;
int has_strength = 0;
if (argc == 3) {
endp = NULL;
errno = 0;
long s = strtol(argv[2], &endp, 10);
if (errno == 0 && endp && *endp == '\0' && s >= 1 && s <= 65535) {
raw_strength = (int)s;
has_strength = 1;
}
}
int level = 2;
int magnitude = resolve_level_and_magnitude(raw_strength, has_strength, &level);
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = handle_signal;
sigemptyset(&sa.sa_mask);
sigaction(SIGINT, &sa, NULL);
sigaction(SIGTERM, &sa, NULL);
sigaction(SIGHUP, &sa, NULL);
if (is_haptic_audio_device()) {
return vibrate_haptic_audio(duration_ms, level);
}
int fd = open_vibrator_device();
if (fd < 0) {
fprintf(stderr, "sxmo_vibrate: cannot open vibrator device: %s\n",
strerror(errno));
return 1;
}
struct ff_effect effect;
memset(&effect, 0, sizeof(effect));
effect.type = FF_RUMBLE;
effect.id = -1;
effect.u.rumble.strong_magnitude = (unsigned short)magnitude;
effect.u.rumble.weak_magnitude = (unsigned short)magnitude;
if (ioctl(fd, EVIOCSFF, &effect) < 0) {
close(fd);
return 1;
}
struct input_event play;
memset(&play, 0, sizeof(play));
play.type = EV_FF;
play.code = (unsigned short)effect.id;
if (level >= 3 || duration_ms <= 90) {
long actual_ms = (level == 1 && duration_ms > 55) ? 55 : duration_ms;
play.value = 1;
if (write(fd, &play, sizeof(play)) >= 0) {
sleep_ms_interruptible(actual_ms);
}
} else {
long on_ms = (level == 1) ? 75 : 160;
long off_ms = (level == 1) ? 125 : 80;
long rem = duration_ms;
while (rem > 0 && !g_stop) {
long cur_on = (rem < on_ms) ? rem : on_ms;
play.value = 1;
if (write(fd, &play, sizeof(play)) < 0) break;
sleep_ms_interruptible(cur_on);
rem -= cur_on;
play.value = 0;
(void)write(fd, &play, sizeof(play));
if (rem <= 0 || g_stop) break;
long cur_off = (rem < off_ms) ? rem : off_ms;
sleep_ms_interruptible(cur_off);
rem -= cur_off;
}
}
play.value = 0;
(void)write(fd, &play, sizeof(play));
(void)ioctl(fd, EVIOCRMFF, effect.id);
close(fd);
return 0;
}