为 Chromium 推流添加设备签名并修复喊话音量

parent 50068b95
#include "main.h"
#include "device_identity.h"
#include "volume_control.h"
#include "volume_output.h"
#include "wifi_hotspot.h"
#include <unistd.h>
......@@ -58,6 +59,11 @@ static int init_audio_runtime(void)
{
my_zlog_info("音频命令执行初始化成功");
}
/* Apply a bounded default before removing the old USB hardware attenuation. */
if (volume_output_apply_browser() != 0)
my_zlog_warn("初始化浏览器默认音量失败");
if (volume_output_ensure_usb_pcm() != 0)
my_zlog_warn("启动检查 USB PCM 100%% 失败,将在服务初始化后重试");
return 0;
}
......@@ -74,7 +80,12 @@ static int init_go_deploy(void)
static int init_local_audio_volume(void)
{
return volume_control_load(mqtt_topic_pure_number());
int result = volume_control_load(mqtt_topic_pure_number());
if (volume_output_apply_browser() != 0)
my_zlog_warn("接口音量应用到 Chromium 系统输出失败");
if (volume_output_ensure_usb_pcm() != 0)
my_zlog_warn("USB PCM 100%% 检查失败");
return result;
}
static int init_ipc_unix_server(void)
......
......@@ -2,6 +2,7 @@
#include "audioplay.h"
#include "audio_sink.h" /* USB声卡排队锁 */
#include "volume_control.h"
#include "volume_output.h"
#include "device_identity.h"
#include "mqtt_init.h"
#include "http_config_mqtt.h"
......@@ -231,9 +232,10 @@ int audioplay_file_with_browser_preempt(const char *filepath, double volume) {
AUDIO_LOCAL_ALSA_DEVICE);
} else {
/* PulseAudio 无法暂停时走其默认输出,避免直接打开同一声卡导致 device busy。 */
double filter_gain = volume_output_pulse_filter_gain(volume);
snprintf(command, sizeof(command),
"timeout -s KILL %ds ffplay -nodisp -autoexit -loglevel warning -af \"volume=%.3f\" %s >/dev/null 2>&1",
AUDIO_ANNOUNCEMENT_TIMEOUT_SEC, volume, quoted_path);
AUDIO_ANNOUNCEMENT_TIMEOUT_SEC, filter_gain, quoted_path);
}
my_zlog_info("local audio: playback started volume=%.3f mode=%s",
......@@ -277,9 +279,10 @@ int audioplay_url_with_browser_preempt(const char *url, double volume) {
AUDIO_ANNOUNCEMENT_TIMEOUT_SEC, quoted_url, volume,
AUDIO_LOCAL_ALSA_DEVICE);
} else {
double filter_gain = volume_output_pulse_filter_gain(volume);
snprintf(command, sizeof(command),
"timeout -s KILL %ds ffplay -nodisp -autoexit -loglevel warning -af \"volume=%.3f\" %s >/dev/null 2>&1",
AUDIO_ANNOUNCEMENT_TIMEOUT_SEC, volume, quoted_url);
AUDIO_ANNOUNCEMENT_TIMEOUT_SEC, filter_gain, quoted_url);
}
exit_code = audio_system_exit_code(system(command));
......
......@@ -210,6 +210,13 @@ master/
运行数据目录由 CMake `CAR_RUNTIME_DIR` 指定,默认 `/home/orangepi/car/master`。在临时目录编译时也使用部署目录读取 `Deviceld.txt`、日志及配置,不能将源码临时路径作为运行数据目录。部署到其他位置时通过 `-DCAR_RUNTIME_DIR=/实际部署目录` 设置。
### 手机喊话与 USB PCM
- Chromium 喊话:启动时将同一接口缓存增益设置到 PulseAudio 系统输出,使用绝对音量,重复应用不会累积衰减。
- 原生 DataChannel 喊话:保持 ALSA 路径,在播放器内应用一次接口缓存增益。
- 每次启动检查 USB 播放 PCM,任一声道不是 100% 就恢复到 100%;不改麦克风。
- 保留原有浏览器启动及音频传输逻辑。本地音频在 PulseAudio 回退时补偿系统增益,避免重复衰减。
### 阅读顺序建议(给接手同事)
1. `app/device_identity/device_identity.c` → 搞清「设备号如何落到具体车型」。
......
......@@ -5,11 +5,16 @@
#include "http_config_mqtt.h"
#include "pthrpoll.h"
#include "delay.h"
#include "volume_output.h"
#include <dirent.h>
#include <openssl/evp.h>
#define BROWSER_URL_SIZE 768
#define MD5_HEX_SIZE 33
static char s_webcam[2048];//存放启动火狐网站命令
static char s_active_stream_url[768]; /* 最近一次启动 chromium 的完整推流网址 */
static char s_active_stream_url[BROWSER_URL_SIZE]; /* 最近一次启动 chromium 的推流网址 */
static int s_open_cam_enter_count = 0; // 记录 opencamsh 进入次数
static int s_open_cam_fail_streak = 0; // 连续启动失败次数
static int s_refresh_cam_enter_count = 0; // 记录 refresh_cam 进入次数
......@@ -29,18 +34,17 @@ static ThreadPool_t *s_refresh_pool = NULL;
#define BROWSER_AUTO_RESTART_FAIL_SEC 5
static int browser_launch_chromium(const char *launch_url);
static int browser_launch_chromium(const char *url);
static int browser_build_stream_urls(const char *url, char *base_url, size_t base_size,
char *launch_url, size_t launch_size);
static int browser_chromium_found_cb(int pid, const char *cmdline, void *ctx);
int opencamsh() {
char urls[512];
int rc;
s_open_cam_enter_count++;
my_zlog_info("opencamsh enter count:%d", s_open_cam_enter_count);
snprintf(urls, sizeof(urls), "%s%s", g_mqtt_cam_config_t->videourl, mqtt_topic_pure_number());
pthread_mutex_lock(&s_browser_ops_mutex);
if (s_browser_external_switch) {
pthread_mutex_unlock(&s_browser_ops_mutex);
......@@ -48,7 +52,7 @@ int opencamsh() {
return -1;
}
rc = browser_launch_chromium(urls);
rc = browser_launch_chromium(g_mqtt_cam_config_t->videourl);
pthread_mutex_unlock(&s_browser_ops_mutex);
if (rc != 0) {
......@@ -481,6 +485,8 @@ static int browser_chromium_url_cb(int pid, const char *cmdline, void *ctx)
int browser_get_stream_url_info(char *url, size_t url_size, bool *running)
{
bool chromium_running = is_browser_running();
char proc_url[BROWSER_URL_SIZE];
char base_url[BROWSER_URL_SIZE];
if (running) {
*running = chromium_running;
......@@ -500,33 +506,26 @@ int browser_get_stream_url_info(char *url, size_t url_size, bool *running)
return 0;
}
if (browser_read_url_from_proc(url, url_size) == 0) {
if (browser_read_url_from_proc(proc_url, sizeof(proc_url)) != 0) {
if (!g_mqtt_cam_config_t) {
return 0;
}
if (g_mqtt_cam_config_t && g_mqtt_cam_config_t->videourl[0] != '\0') {
const char *device_no = mqtt_topic_pure_number();
snprintf(url, url_size, "%s%s",
g_mqtt_cam_config_t->videourl,
device_no ? device_no : "");
snprintf(proc_url, sizeof(proc_url), "%s", g_mqtt_cam_config_t->videourl);
}
if (browser_build_stream_urls(proc_url, base_url, sizeof(base_url), NULL, 0) == 0) {
snprintf(url, url_size, "%s", base_url);
}
return 0;
}
static void shell_escape_single_quoted(const char *input, char *out, size_t out_size)
static int shell_escape_single_quoted(const char *input, char *out, size_t out_size)
{
size_t i = 0;
size_t j = 0;
if (!out || out_size == 0) {
return;
}
out[0] = '\0';
if (!input) {
return;
for (size_t i = 0; input[i] != '\0'; i++) {
if (j + (input[i] == '\'' ? 4 : 1) >= out_size) {
return -1;
}
for (i = 0; input[i] != '\0' && j + 4 < out_size; i++) {
if (input[i] == '\'') {
out[j++] = '\'';
out[j++] = '\\';
......@@ -537,6 +536,7 @@ static void shell_escape_single_quoted(const char *input, char *out, size_t out_
}
}
out[j] = '\0';
return 0;
}
static int browser_validate_stream_url(const char *url)
......@@ -556,48 +556,148 @@ static int browser_validate_stream_url(const char *url)
return 0;
}
static void browser_build_launch_url(const char *url, char *launch_url, size_t launch_size)
static int browser_md5_hex(const char *input, char output[MD5_HEX_SIZE])
{
size_t len;
const char *device_no;
unsigned char digest[EVP_MAX_MD_SIZE];
unsigned int digest_len;
if (!url || !launch_url || launch_size == 0) {
return;
if (EVP_Digest(input, strlen(input), digest, &digest_len, EVP_md5(), NULL) != 1 ||
digest_len != 16) {
return -1;
}
for (unsigned int i = 0; i < digest_len; i++) {
snprintf(output + i * 2, 3, "%02x", (unsigned int)digest[i]);
}
return 0;
}
len = strlen(url);
device_no = mqtt_topic_pure_number();
if (len > 0 && url[len - 1] == '=') {
snprintf(launch_url, launch_size, "%s%s", url, device_no ? device_no : "");
return;
static bool browser_query_key_is(const char *param, size_t key_len, const char *key)
{
return key_len == strlen(key) && memcmp(param, key, key_len) == 0;
}
static int browser_build_stream_urls(const char *url, char *base_url, size_t base_size,
char *launch_url, size_t launch_size)
{
if (!url || !url[0]) {
return -1;
}
const char *fragment = url + strcspn(url, "#");
const char *query = memchr(url, '?', fragment - url);
size_t used = (query ? query : fragment) - url;
if (used >= base_size) {
return -1;
}
memcpy(base_url, url, used);
const char *dev = NULL;
size_t dev_len = 0;
char separator = '?';
for (const char *param = query ? query + 1 : fragment; param < fragment;) {
const char *end = memchr(param, '&', fragment - param);
if (!end) {
end = fragment;
}
const char *next = end < fragment ? end + 1 : fragment;
size_t param_len = end - param;
const char *equals = memchr(param, '=', param_len);
size_t key_len = (equals ? equals : end) - param;
if (param_len != 0 && !browser_query_key_is(param, key_len, "type") &&
!browser_query_key_is(param, key_len, "token") &&
!browser_query_key_is(param, key_len, "timestamp")) {
if (browser_query_key_is(param, key_len, "dev")) {
if (dev || !equals || equals + 1 == end) {
param = next;
continue;
}
dev = equals + 1;
dev_len = end - dev;
}
if (param_len + 1 >= base_size - used) {
return -1;
}
base_url[used++] = separator;
memcpy(base_url + used, param, param_len);
used += param_len;
separator = '&';
}
param = next;
}
if (!dev) {
dev = mqtt_topic_pure_number();
dev_len = strlen(dev);
int written = snprintf(base_url + used, base_size - used, "%cdev=%s", separator, dev);
if (written < 0 || (size_t)written >= base_size - used) {
return -1;
}
used += (size_t)written;
}
if (launch_url) {
/* Unix 时间戳以秒为单位,与设备设置的时区无关。 */
time_t now = time(NULL);
if (now == (time_t)-1) {
return -1;
}
char timestamp[32];
snprintf(timestamp, sizeof(timestamp), "%lld", (long long)now);
char *decoded_dev = curl_easy_unescape(NULL, dev, (int)dev_len, NULL);
if (!decoded_dev) {
return -1;
}
char input[BROWSER_URL_SIZE + sizeof(timestamp)];
int written = snprintf(input, sizeof(input), "%s%sfcrs@2026", timestamp, decoded_dev);
curl_free(decoded_dev);
char first_md5[MD5_HEX_SIZE];
char token[MD5_HEX_SIZE];
if (written < 0 || (size_t)written >= sizeof(input) ||
browser_md5_hex(input, first_md5) != 0 || browser_md5_hex(first_md5, token) != 0) {
return -1;
}
written = snprintf(launch_url, launch_size, "%.*s&type=device&timestamp=%s&token=%s%s",
(int)used, base_url, timestamp, token, fragment);
if (written < 0 || (size_t)written >= launch_size) {
return -1;
}
if (len >= 5 && strcmp(url + len - 5, "?dev=") == 0) {
snprintf(launch_url, launch_size, "%s%s", url, device_no ? device_no : "");
return;
}
snprintf(launch_url, launch_size, "%s", url);
int written = snprintf(base_url + used, base_size - used, "%s", fragment);
return written >= 0 && (size_t)written < base_size - used ? 0 : -1;
}
static int browser_launch_chromium(const char *launch_url)
static int browser_launch_chromium(const char *url)
{
char escaped_url[1024];
char cmd[2048];
char base_url[BROWSER_URL_SIZE];
char launch_url[BROWSER_URL_SIZE];
char escaped_url[4 * BROWSER_URL_SIZE];
char cmd[sizeof(escaped_url) + 256];
int ret;
if (!launch_url || !launch_url[0]) {
if (!url || !url[0]) {
return -1;
}
browser_prepare_display_env();
shell_escape_single_quoted(launch_url, escaped_url, sizeof(escaped_url));
if (volume_output_apply_browser() != 0)
my_zlog_warn("Chromium 启动前应用接口音量失败");
if (browser_build_stream_urls(url, base_url, sizeof(base_url), launch_url, sizeof(launch_url)) != 0 ||
shell_escape_single_quoted(launch_url, escaped_url, sizeof(escaped_url)) != 0) {
my_zlog_error("browser_launch_chromium: failed to build stream URL");
return -1;
}
snprintf(cmd, sizeof(cmd),
"su - orangepi -c 'export DISPLAY=:0 XAUTHORITY=/home/orangepi/.Xauthority; "
"nohup chromium-browser --use-fake-ui-for-media-stream %s "
">/tmp/chromium-stream.log 2>&1 &'",
"nohup chromium-browser --use-fake-ui-for-media-stream \"$1\" "
">/tmp/chromium-stream.log 2>&1 &' sh '%s'",
escaped_url);
my_zlog_info("browser_launch_chromium: %s", launch_url);
my_zlog_info("browser_launch_chromium: %s", base_url);
ret = system(cmd);
if (ret != 0) {
my_zlog_error("browser_launch_chromium failed ret=%d", ret);
......@@ -609,14 +709,12 @@ static int browser_launch_chromium(const char *launch_url)
return -1;
}
strncpy(s_active_stream_url, launch_url, sizeof(s_active_stream_url) - 1);
s_active_stream_url[sizeof(s_active_stream_url) - 1] = '\0';
snprintf(s_active_stream_url, sizeof(s_active_stream_url), "%s", base_url);
return 0;
}
int browser_switch_stream_url(const char *url, char *effective_url, size_t effective_size)
{
char launch_url[768];
int ret;
if (browser_validate_stream_url(url) != 0) {
......@@ -624,11 +722,7 @@ int browser_switch_stream_url(const char *url, char *effective_url, size_t effec
return -1;
}
browser_build_launch_url(url, launch_url, sizeof(launch_url));
strncpy(g_mqtt_cam_config_t->videourl, url, sizeof(g_mqtt_cam_config_t->videourl) - 1);
g_mqtt_cam_config_t->videourl[sizeof(g_mqtt_cam_config_t->videourl) - 1] = '\0';
my_zlog_info("browser_switch_stream_url: kill old chromium, launch %s", launch_url);
my_zlog_info("browser_switch_stream_url: kill old chromium before launch");
browser_begin_external_switch();
if (browser_kill_chromium() != 0) {
my_zlog_warn("browser_switch_stream_url: old chromium may still be exiting, continue launch");
......@@ -636,7 +730,11 @@ int browser_switch_stream_url(const char *url, char *effective_url, size_t effec
delay_ms(1000);
pthread_mutex_lock(&s_browser_ops_mutex);
ret = browser_launch_chromium(launch_url);
memmove(g_mqtt_cam_config_t->videourl, url, strlen(url) + 1);
ret = browser_launch_chromium(g_mqtt_cam_config_t->videourl);
if (ret == 0 && effective_url && effective_size > 0) {
snprintf(effective_url, effective_size, "%s", s_active_stream_url);
}
pthread_mutex_unlock(&s_browser_ops_mutex);
browser_end_external_switch();
......@@ -645,10 +743,6 @@ int browser_switch_stream_url(const char *url, char *effective_url, size_t effec
return -1;
}
if (effective_url && effective_size > 0) {
snprintf(effective_url, effective_size, "%s", launch_url);
}
my_zlog_info("browser_switch_stream_url: ok %s", launch_url);
my_zlog_info("browser_switch_stream_url: ok");
return 0;
}
......@@ -15,7 +15,7 @@ void browser_begin_external_switch(void);
void browser_end_external_switch(void);
int browser_auto_restart_allowed(void);
/* 推流调试:仅浏览器 webrtc 模式可切换;effective_url 输出实际打开的完整网址 */
/* 推流调试:仅浏览器 webrtc 模式可切换;effective_url 输出用于诊断的推流网址 */
int browser_switch_stream_url(const char *url, char *effective_url, size_t effective_size);
/* 查询 chromium 运行状态与当前推流网址(url 缓冲区未运行时置空串) */
......
......@@ -20,6 +20,8 @@ typedef struct {
/* 参考板 orangepi3b @ 5.10.160-rockchip-rk356x */
static const DebPkgPin s_webrtc_debs[] = {
{"alsa-utils", "1.2.6-1ubuntu1"},
{"pulseaudio-utils", "1:15.99.1+dfsg1-1ubuntu2"},
{"gstreamer1.0-nice", "0.1.18-2"},
{"gstreamer1.0-pulseaudio", "1.20.3-0ubuntu1"},
{"librockchip-mpp1", "1.5.0-2"},
......@@ -31,6 +33,8 @@ static const DebPkgPin s_webrtc_debs[] = {
};
static const DebPkgPin s_browser_debs[] = {
{"alsa-utils", "1.2.6-1ubuntu1"},
{"pulseaudio-utils", "1:15.99.1+dfsg1-1ubuntu2"},
{"chromium-browser", "1:110.0.5481.4-0ubuntu1~jammy~rkmpp20230130"},
{"xdotool", "1:3.20160805.1-4"},
};
......
......@@ -3,6 +3,7 @@
#include "mpp_h264_source.h"
#include "audio_source.h"
#include "audio_sink.h"
#include "volume_control.h"
#include "webrtcpush_config.h"
#include "webrtcpush_log.h"
#include "ws_signaling.h"
......@@ -665,6 +666,9 @@ static gpointer dc_play_queue_thread(gpointer data)
}
gchar *quoted = g_shell_quote(path);
char playback_gain[G_ASCII_DTOSTR_BUF_SIZE];
g_ascii_formatd(playback_gain, sizeof(playback_gain), "%.9g",
volume_control_get_local_volume());
gchar *cmd = g_strdup_printf(
/*
* 修复两个问题:
......@@ -675,8 +679,8 @@ static gpointer dc_play_queue_thread(gpointer data)
* gst_audio_ring_buffer_set_channel_positions 的 "should not be reached"
* CRITICAL; 用 audioconvert 上混到 2 声道规避。
*/
"timeout 20s gst-launch-1.0 -q playbin uri=file://%s audio-sink=\"audioconvert ! audioresample ! audio/x-raw,channels=2 ! alsasink device=%s sync=true\" video-sink=fakesink",
quoted, WEBRTCPUSH_AUDIO_PLAYBACK_DEVICE);
"timeout 20s gst-launch-1.0 -q playbin uri=file://%s audio-sink=\"audioconvert ! volume volume=%s ! audioresample ! audio/x-raw,channels=2 ! alsasink device=%s sync=true\" video-sink=fakesink",
quoted, playback_gain, WEBRTCPUSH_AUDIO_PLAYBACK_DEVICE);
int status = -1;
gchar *child_out = NULL, *child_err = NULL;
my_zlog_info("libdatachannel: playing %u bytes (seq=%u)", (guint)task->size, task->seq);
......
......@@ -7,7 +7,7 @@
#include <errno.h>
/*
* 开机联网后拉取一次后端音量,缓存给 MQTT 2017 本地播报使用。
* 开机联网后拉取一次后端音量,缓存给本地播报、Chromium 和原生 DataChannel 喊话使用。
*
* 接口:GET https://fcrs-api.yd-ss.com/api/drive/use/status/{vehicleId}
* businessJson 是字符串(需二次解析),volume 支持数值和数字字符串:"0.01" = 1%。
......
......@@ -4,7 +4,7 @@
/* 开机联网后、音频工作线程启动前调用一次。失败保留默认音量 0.3。 */
int volume_control_load(const char *vehicle_id);
/* MQTT 2017 本地播报音量,保存在运行内存中,范围 0~1。 */
/* 播报及两条喊话路径共用的接口线性增益,运行内存缓存,范围 0~1。 */
double volume_control_get_local_volume(void);
#endif
#include "volume_output.h"
#include "volume_control.h"
#include "webrtcpush_config.h"
#include "mylog.h"
#include <glib.h>
#include <cjson/cJSON.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
static gint s_browser_volume_applied;
static int run_audio_command(const char *tool, const char *const args[], char **output)
{
const char *argv[16] = {"timeout", "-k", "1", "3", tool};
guint n = 5;
for (guint i = 0; args[i] && n + 1 < G_N_ELEMENTS(argv); i++) argv[n++] = args[i];
gchar *out = NULL, *err = NULL;
GError *error = NULL;
gint status = -1;
gchar **env = g_get_environ();
env = g_environ_setenv(env, "LC_ALL", "C", TRUE);
gboolean started = g_spawn_sync(NULL, (gchar **)argv, env,
G_SPAWN_SEARCH_PATH, NULL, NULL, &out, &err, &status, &error);
g_strfreev(env);
int ok = started && g_spawn_check_wait_status(status, NULL);
if (!ok) my_zlog_warn("volume output: %s failed: %s", tool,
error ? error->message : (err && err[0] ? err : "command failed"));
if (output) *output = out; else g_free(out);
g_free(err);
g_clear_error(&error);
return ok ? 0 : -1;
}
int volume_output_ensure_usb_pcm(void)
{
unsigned card, device;
int consumed = 0;
const char *playback = WEBRTCPUSH_AUDIO_PLAYBACK_DEVICE;
if (sscanf(playback, "plughw:%u,%u%n", &card, &device, &consumed) != 2 &&
sscanf(playback, "hw:%u,%u%n", &card, &device, &consumed) != 2) {
my_zlog_warn("volume output: unsupported PCM playback device %s", playback);
return -1;
}
if (playback[consumed] || card > 255) return -1;
char usb_path[64], card_text[16];
g_snprintf(usb_path, sizeof(usb_path), "/proc/asound/card%u/usbid", card);
if (!g_file_test(usb_path, G_FILE_TEST_IS_REGULAR)) {
my_zlog_warn("volume output: playback card %u is not an available USB card", card);
return -1;
}
g_snprintf(card_text, sizeof(card_text), "%u", card);
const char *get[] = {"-c", card_text, "sget", "PCM", NULL};
char *output = NULL;
if (run_audio_command("amixer", get, &output) != 0) { g_free(output); return -1; }
GRegex *pattern = g_regex_new("Playback[ \\t]+[0-9]+[ \\t]+\\[([0-9]+)%\\]", 0, 0, NULL);
GMatchInfo *matches = NULL;
g_regex_match(pattern, output ? output : "", 0, &matches);
guint channels = 0;
int full = 1;
while (g_match_info_matches(matches)) {
char *percent = g_match_info_fetch(matches, 1);
if (strcmp(percent, "100") != 0) full = 0;
channels++;
g_free(percent);
g_match_info_next(matches, NULL);
}
g_match_info_free(matches);
g_regex_unref(pattern);
g_free(output);
if (!channels) {
my_zlog_warn("volume output: cannot read USB PCM playback percentages");
return -1;
}
if (!full) {
const char *set[] = {"-c", card_text, "sset", "PCM", "100%", NULL};
if (run_audio_command("amixer", set, NULL) != 0) return -1;
my_zlog_info("volume output: USB card %u PCM restored to 100%%", card);
} else {
my_zlog_info("volume output: USB card %u PCM already 100%%", card);
}
return 0;
}
static char *default_sink(void)
{
char *sink = NULL;
const char *get[] = {"get-default-sink", NULL};
if (run_audio_command("pactl", get, &sink) != 0) { g_free(sink); return NULL; }
if (!sink || !g_strstrip(sink)[0]) { g_free(sink); return NULL; }
return sink;
}
int volume_output_apply_browser(void)
{
char *sink = default_sink();
if (!sink) return -1;
double gain = volume_control_get_local_volume();
char raw[16];
/* PulseAudio's raw scale is cubic; unsigned raw values are absolute.
* A negative dB argument would instead attenuate repeatedly on every call. */
g_snprintf(raw, sizeof(raw), "%u", (guint)lround(cbrt(gain) * 65536.0));
const char *set[] = {"set-sink-volume", sink, raw, NULL};
const char *unmute[] = {"set-sink-mute", sink, "0", NULL};
int result = run_audio_command("pactl", set, NULL);
if (result == 0) {
g_atomic_int_set(&s_browser_volume_applied, 1);
result = run_audio_command("pactl", unmute, NULL);
}
if (result == 0) my_zlog_info("volume output: Chromium sink=%s linear gain=%.6f", sink, gain);
g_free(sink);
return result;
}
double volume_output_pulse_filter_gain(double requested_gain)
{
if (!g_atomic_int_get(&s_browser_volume_applied)) return requested_gain;
double master = volume_control_get_local_volume();
char *sink = default_sink();
char *output = NULL;
const char *get[] = {"--format=json", "list", "sinks", NULL};
if (sink && run_audio_command("pactl", get, &output) == 0) {
cJSON *list = cJSON_Parse(output);
const cJSON *entry;
cJSON_ArrayForEach(entry, list) {
const cJSON *name = cJSON_GetObjectItemCaseSensitive(entry, "name");
if (!cJSON_IsString(name) || strcmp(name->valuestring, sink) != 0) continue;
const cJSON *channel;
double max_gain = -1.0;
cJSON_ArrayForEach(channel, cJSON_GetObjectItemCaseSensitive(entry, "volume")) {
const cJSON *value = cJSON_GetObjectItemCaseSensitive(channel, "value");
if (cJSON_IsNumber(value) && isfinite(value->valuedouble) && value->valuedouble >= 0) {
double gain = pow(value->valuedouble / 65536.0, 3.0);
if (gain > max_gain) max_gain = gain;
}
}
if (max_gain >= 0) master = max_gain;
break;
}
cJSON_Delete(list);
}
g_free(sink);
g_free(output);
return master > 0 ? requested_gain / master : 0.0;
}
#ifndef VOLUME_OUTPUT_H
#define VOLUME_OUTPUT_H
/* Startup check for the configured USB playback card. Only change PCM when
* at least one playback channel is below 100%; never change capture controls. */
int volume_output_ensure_usb_pcm(void);
/* Apply cached interface gain to the PulseAudio default output for Chromium.
* Gain remains linear; zero is silent. No browser stream mute is changed. */
int volume_output_apply_browser(void);
/* ffplay's PulseAudio fallback already passes through the system gain. This
* compensating filter keeps the requested local gain from being applied twice. */
double volume_output_pulse_filter_gain(double requested_gain);
#endif
/* gcc -Dg_spawn_sync=output_test_spawn -Dg_file_test=output_test_file_test \
* tests/volume_output_test.c modules/webrtcpush/volume_output.c \
* third_party/cjson/cJSON.c -Imodules/webrtcpush -Imodules/logger -Ithird_party \
* $(pkg-config --cflags --libs glib-2.0) -lm -o volume_output_test
* All child processes and USB detection are mocked: no hardware is changed. */
#include "volume_output.h"
#include <glib.h>
#include <assert.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
static double interface_gain = 0.1;
static guint raw_volume = 65536;
static int usb_present = 1;
static int pcm_full;
static int malformed_pcm;
static int asymmetric_pcm;
static int pcm_set_calls;
static int fail_amixer;
static int fail_pactl;
double volume_control_get_local_volume(void) { return interface_gain; }
void my_zlog_info(const char *format, ...) { (void)format; }
void my_zlog_warn(const char *format, ...) { (void)format; }
gboolean output_test_file_test(const gchar *path, GFileTest test)
{
assert(strcmp(path, "/proc/asound/card2/usbid") == 0);
assert(test == G_FILE_TEST_IS_REGULAR);
return usb_present;
}
gboolean output_test_spawn(const gchar *cwd, gchar **argv, gchar **env,
GSpawnFlags flags, GSpawnChildSetupFunc setup, gpointer data,
gchar **out, gchar **err, gint *status, GError **error)
{
(void)cwd; (void)flags; (void)setup; (void)data; (void)error;
assert(strcmp(argv[0], "timeout") == 0 && strcmp(argv[3], "3") == 0);
assert(strcmp(g_environ_getenv(env, "LC_ALL"), "C") == 0);
*out = g_strdup(""); *err = g_strdup(""); *status = 0;
if (strcmp(argv[4], "amixer") == 0) {
assert(strcmp(argv[5], "-c") == 0 && strcmp(argv[6], "2") == 0);
assert(strcmp(argv[8], "PCM") == 0); /* No capture control changes. */
if (fail_amixer) { *status = 1; return TRUE; }
if (strcmp(argv[7], "sget") == 0) {
g_free(*out);
if (malformed_pcm) *out = g_strdup("unrecognized mixer output");
else *out = g_strdup_printf(
"Simple mixer control 'PCM',0\nLimits: Playback 0 - 147\n"
"Front Left: Playback %d [%d%%] [-0.94dB] [on]\n"
"Front Right: Playback %d [%d%%] [-0.94dB] [on]\n",
pcm_full ? 147 : 44, pcm_full ? 100 : 30,
pcm_full && !asymmetric_pcm ? 147 : 44,
pcm_full && !asymmetric_pcm ? 100 : 30);
} else {
assert(strcmp(argv[7], "sset") == 0 && strcmp(argv[9], "100%") == 0);
assert(argv[10] == NULL); /* Preserve switch/capture state. */
pcm_set_calls++; pcm_full = 1; asymmetric_pcm = 0;
}
return TRUE;
}
assert(strcmp(argv[4], "pactl") == 0);
if (fail_pactl) { *status = 1; return TRUE; }
if (strcmp(argv[5], "get-default-sink") == 0) {
g_free(*out); *out = g_strdup("usb-output\n");
} else if (strcmp(argv[5], "set-sink-volume") == 0) {
assert(strcmp(argv[6], "usb-output") == 0);
const char *p = argv[7];
assert(*p);
for (; *p; p++) assert(g_ascii_isdigit(*p)); /* Absolute/idempotent, no negative dB. */
raw_volume = (guint)g_ascii_strtoull(argv[7], NULL, 10);
} else if (strcmp(argv[5], "set-sink-mute") == 0) {
assert(strcmp(argv[6], "usb-output") == 0 && strcmp(argv[7], "0") == 0);
} else {
assert(strcmp(argv[5], "--format=json") == 0 && strcmp(argv[6], "list") == 0);
assert(strcmp(argv[7], "sinks") == 0);
g_free(*out);
*out = g_strdup_printf("[{\"name\":\"usb-output\",\"volume\":{"
"\"left\":{\"value\":%u},\"right\":{\"value\":%u}}}]", raw_volume, raw_volume);
}
return TRUE;
}
int main(void)
{
assert(volume_output_pulse_filter_gain(0.3) == 0.3);
assert(volume_output_ensure_usb_pcm() == 0 && pcm_set_calls == 1 && pcm_full);
assert(volume_output_ensure_usb_pcm() == 0 && pcm_set_calls == 1); /* 100% stays untouched. */
asymmetric_pcm = 1;
assert(volume_output_ensure_usb_pcm() == 0 && pcm_set_calls == 2);
usb_present = 0;
assert(volume_output_ensure_usb_pcm() == -1 && pcm_set_calls == 2);
usb_present = 1; malformed_pcm = 1;
assert(volume_output_ensure_usb_pcm() == -1 && pcm_set_calls == 2);
malformed_pcm = 0; fail_amixer = 1;
assert(volume_output_ensure_usb_pcm() == -1);
fail_amixer = 0;
const double gains[] = {0, 0.01, 0.1, 0.3, 1};
for (guint i = 0; i < G_N_ELEMENTS(gains); i++) {
interface_gain = gains[i];
assert(volume_output_apply_browser() == 0);
guint first = raw_volume;
assert(volume_output_apply_browser() == 0 && raw_volume == first);
double actual = pow(raw_volume / 65536.0, 3.0);
assert(fabs(actual - interface_gain) < 1e-4);
if (interface_gain == 0) {
assert(raw_volume == 0 && volume_output_pulse_filter_gain(0.5) == 0);
} else {
assert(fabs(volume_output_pulse_filter_gain(0.5) * actual - 0.5) < 1e-9);
}
}
interface_gain = 0.1;
assert(volume_output_apply_browser() == 0);
raw_volume = 65536; /* Compensate actual output after an external mixer change. */
assert(volume_output_pulse_filter_gain(0.5) == 0.5);
fail_pactl = 1;
assert(volume_output_apply_browser() == -1);
assert(fabs(volume_output_pulse_filter_gain(0.3) - 3.0) < 1e-9);
puts("PASS: startup USB PCM check, absolute browser gain, silence and single-gain fallback");
return 0;
}
# MQTT 维护反馈与热点配网
# MQTT 维护反馈与热点配网
# MQTT 维护反馈与热点配网
## 播报音量
## 播报与喊话音量
开机从 `/api/drive/use/status/{设备号}` 读取 `businessJson.volume`,兼容数值和数字字符串,范围限制为 0–1,默认 0.3。2017 本地播报、联网成功/失败语音使用这个缓存倍率。后台修改后需重启程序重新读取。配网系统短音单独固定为 0.5(50%),不受 `businessJson.volume` 影响。
开机从 `/api/drive/use/status/{设备号}` 读取 `businessJson.volume`,兼容数值和数字字符串,范围限制为 0–1,默认 0.3。运行期间只读缓存,后台修改后需重启程序重新读取。现在该缓存还应用到两条手机喊话路径:
- Chromium 网页:按 `round(cbrt(volume)*65536)` 转成 PulseAudio 的绝对系统音量;保留线性增益语义,不用负 dB 相对参数。0 为静音。
- 原生 WebRTC DataChannel:保持直连 ALSA,通过 GStreamer `volume` 元素应用缓存增益一次,不经过 PulseAudio 系统音量;0 为静音。
- 本地 2017 和联网语音仍沿用已有 ALSA 播放倍率。PulseAudio 回退播放时按实际系统增益补偿滤镜,避免再次乘接口倍率;系统音量为 0 时该回退输出静音。
每次程序启动检查 `WEBRTCPUSH_AUDIO_PLAYBACK_DEVICE` 对应的 USB 声卡 PCM。任一播放声道不是 100% 就执行 `amixer -c <card> sset PCM 100%`;已经为 100% 时不写。用 `/proc/asound/cardN/usbid` 验证 USB,非 USB 卡和麦克风不改。当前 Yundea 声卡 100% 为原始值 147,约 −0.94dB。依赖 `alsa-utils`、`pulseaudio-utils`。缺失或检查失败记录日志,并在服务依赖初始化后重试。
系统音量与硬件 PCM 在启动时先建立默认增益,再在接口读取完成后应用实际缓存增益。Chromium 重启前也重应用缓存值;不修改浏览器 DataChannel、音频格式或浏览器流静音状态。
配网系统短音仍为独立播放倍率 0.5。
热点开启成功、配网成功、失败均使用同一个系统 `bell.oga` 音色,通过节奏区分:开启热点成功为三声、间隔 180 毫秒;配网成功为两声、间隔 450 毫秒;失败为一声。系统铃声缺失时各状态统一尝试相同的系统音效回退,不回退到语音。短音在后台播放,不阻塞热点 HTTP 服务或连接清理,固定 50% 音量。
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment