Merge branch 'dev' into livekit-structured

This commit is contained in:
rahulpscraftech360 2025-09-16 18:57:12 +05:30 committed by GitHub
commit 1981087208
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
165 changed files with 2531 additions and 33299 deletions

4
.gitignore vendored
View file

@ -183,3 +183,7 @@ main/xiaozhi-server/mysql
uploadfile
*.json
.vscode
# Spring Boot configuration files (contain sensitive data)
main/manager-api/src/main/resources/application.yml
main/manager-api/src/main/resources/application-dev.yml

View file

@ -1,452 +0,0 @@
# Firmware Update System Documentation
## Table of Contents
1. [Overview](#overview)
2. [Architecture](#architecture)
3. [Components](#components)
4. [Firmware Upload Process](#firmware-upload-process)
5. [OTA Update Flow](#ota-update-flow)
6. [API Endpoints](#api-endpoints)
7. [Database Schema](#database-schema)
8. [Configuration](#configuration)
9. [Security Features](#security-features)
10. [Device-Server Communication](#device-server-communication)
---
## Overview
The Xiaozhi ESP32 Server implements a comprehensive Over-The-Air (OTA) firmware update system that allows remote firmware updates for ESP32 devices. The system supports automatic version checking, secure firmware distribution, and device-specific update policies.
### Key Features
- Automatic version comparison and update detection
- Secure firmware storage with MD5 hash verification
- Per-device update control (auto-update enable/disable)
- Download attempt limiting (3 attempts per UUID)
- Support for multiple firmware types (.bin and .apk)
- RESTful API for firmware management
---
## Architecture
```
┌─────────────────┐ ┌──────────────────┐ ┌────────────────┐
│ ESP32 Device │────▶│ Manager API │────▶│ Firmware Store │
│ │◀────│ (Java Spring) │◀────│ (uploadfile/) │
└─────────────────┘ └──────────────────┘ └────────────────┘
│ │ │
│ ▼ │
│ ┌──────────────────┐ │
│ │ Database │ │
│ │ (ai_ota) │ │
│ └──────────────────┘ │
│ │
▼ │
┌─────────────────┐ │
│ Xiaozhi Server │ │
│ (Python) │◀──────────────────────────────────────┘
└─────────────────┘
```
---
## Components
### 1. Manager API (Java Spring Boot)
- **Location**: `main/manager-api/`
- **Main Controllers**:
- `OTAController.java`: Handles device OTA check requests
- `OTAMagController.java`: Manages firmware upload/download
- **Services**:
- `OtaServiceImpl.java`: Business logic for OTA operations
- `DeviceServiceImpl.java`: Device management and update checks
### 2. Xiaozhi Server (Python)
- **Location**: `main/xiaozhi-server/`
- **OTA Handler**: `core/api/ota_handler.py`
- Provides fallback OTA endpoint for direct device connections
### 3. Firmware Storage
- **Location**: `main/manager-api/uploadfile/`
- Files stored with MD5 hash as filename
- Supported formats: `.bin`, `.apk`
---
## Firmware Upload Process
### Step 1: Admin Upload
```http
POST /otaMag/upload
Content-Type: multipart/form-data
```
**Process Flow**:
1. Admin uploads firmware file through web interface
2. System validates file extension (.bin or .apk only)
3. MD5 hash calculated for the file
4. File saved as: `uploadfile/{md5_hash}.{extension}`
5. If file already exists (same MD5), returns existing path
6. Path returned to admin for database entry
**Code Location**: `OTAMagController.java:231-279`
### Step 2: Database Registration
Admin creates OTA entry with:
- **Firmware Name**: Descriptive name
- **Type**: Device type (e.g., "esp32-generic", "doit-ai-01-kit")
- **Version**: Semantic version (e.g., "1.7.6")
- **File Path**: Path from upload step
- **Size**: File size in bytes
- **Remark**: Optional description
---
## OTA Update Flow
### 1. Device Check Request
```http
POST /ota/
Headers:
Device-Id: {MAC_ADDRESS}
Client-Id: {CLIENT_ID}
Body:
{
"application": {
"version": "1.7.6"
},
"board": {
"type": "esp32-generic"
}
}
```
### 2. Server Processing
**Location**: `DeviceServiceImpl.java - checkDeviceActive()`
1. **Device Validation**:
- Verify MAC address format
- Check if device is registered in database
2. **Update Decision Logic**:
```java
if (device == null) {
// Device not registered - no update
return current_firmware_info;
}
if (device.autoUpdate != 0) {
// Check for newer version
OtaEntity latest = getLatestOta(device.type);
if (compareVersions(latest.version, current.version) > 0) {
// Generate download URL
return firmware_with_download_url;
}
}
```
3. **Download URL Generation**:
- Create temporary UUID
- Store OTA ID in Redis: `ota:id:{uuid}`
- Generate URL: `/otaMag/download/{uuid}`
- URL valid for 3 download attempts
### 3. Server Response
```json
{
"server_time": {
"timestamp": 1703123456789,
"timezone_offset": 480
},
"firmware": {
"version": "1.7.7",
"url": "http://server:8002/otaMag/download/abc-123-def"
},
"websocket": {
"url": "ws://server:8000/xiaozhi/v1/"
},
"mqtt": {
"endpoint": "broker:1883",
"client_id": "GID_test@@@mac@@@uuid",
"username": "base64_encoded_data",
"password": "hmac_signature"
}
}
```
### 4. Firmware Download
**Endpoint**: `GET /otaMag/download/{uuid}`
**Process**:
1. Validate UUID exists in Redis
2. Check download count (max 3 attempts)
3. Retrieve firmware file from storage
4. Return file as binary stream
5. Increment download counter
6. Clean up after 3 downloads
**Security Features**:
- UUID expires after use
- Download attempt limiting
- File path validation
- Safe filename generation
---
## API Endpoints
### OTA Check Endpoints
#### POST /ota/
- **Purpose**: Device firmware update check
- **Headers**: Device-Id, Client-Id
- **Response**: Update information if available
#### POST /ota/activate
- **Purpose**: Quick device activation check
- **Headers**: Device-Id, Client-Id
- **Response**: 200 if registered, 202 if not
### Management Endpoints
#### GET /otaMag
- **Purpose**: List all firmware entries
- **Permission**: superAdmin
- **Parameters**: page, limit
#### POST /otaMag
- **Purpose**: Create firmware entry
- **Permission**: superAdmin
- **Body**: OtaEntity
#### PUT /otaMag/{id}
- **Purpose**: Update firmware entry
- **Permission**: superAdmin
#### DELETE /otaMag/{id}
- **Purpose**: Delete firmware entry
- **Permission**: superAdmin
#### POST /otaMag/upload
- **Purpose**: Upload firmware file
- **Permission**: superAdmin
- **Returns**: File path for database
#### GET /otaMag/download/{uuid}
- **Purpose**: Download firmware file
- **Public**: Yes (with valid UUID)
- **Limit**: 3 attempts per UUID
---
## Database Schema
### Table: `ai_ota`
```sql
CREATE TABLE ai_ota (
id VARCHAR(36) PRIMARY KEY,
firmware_name VARCHAR(255),
type VARCHAR(100), -- Device type
version VARCHAR(50), -- Semantic version
size BIGINT, -- File size in bytes
remark TEXT, -- Description
firmware_path VARCHAR(500), -- File storage path
sort INT, -- Display order
updater BIGINT,
update_date DATETIME,
creator BIGINT,
create_date DATETIME
);
```
### Table: `ai_device`
```sql
CREATE TABLE ai_device (
id VARCHAR(36) PRIMARY KEY,
mac_address VARCHAR(50),
app_version VARCHAR(50), -- Current firmware version
auto_update TINYINT, -- 0=disabled, 1=enabled
-- other fields...
);
```
---
## Configuration
### System Parameters
Configure in `sys_params` table or through Parameter Management UI:
1. **server.websocket**
- WebSocket server URL for device connections
- Example: `ws://server:8000/xiaozhi/v1/`
2. **server.ota**
- OTA server base URL
- Example: `http://server:8002/xiaozhi/`
### Device Types
Configure in Dictionary Management (FIRMWARE_TYPE):
- `doit-ai-01-kit`: DOIT AI-01 Kit
- `esp32-generic`: ESP32 Generic
- `esp32s3-devkit`: ESP32-S3 DevKit
- `xiao-esp32s3`: XIAO ESP32S3
- `m5stack-core`: M5Stack Core
---
## Security Features
### 1. File Upload Security
- Extension validation (.bin, .apk only)
- MD5 hash verification
- Duplicate detection
- Admin permission required
### 2. Download Security
- Temporary UUID generation
- Redis-based token management
- Download attempt limiting (3 max)
- Automatic cleanup after use
### 3. Version Control
- Semantic versioning comparison
- Per-device update control
- Type-specific firmware matching
### 4. MQTT Authentication
- HMAC-SHA256 signature generation
- Base64 encoded credentials
- Session-specific UUIDs
---
## Device-Server Communication
### 1. Initial Connection
Device connects to OTA endpoint with:
- MAC address as Device-Id
- Current firmware version
- Board type information
### 2. Update Check Flow
```
Device Manager API Database
│ │ │
├──POST /ota/──────────────▶│ │
│ (version, type) │ │
│ ├──Check Device────────▶│
│ │◀─────────────────────┤
│ │ │
│ ├──Get Latest OTA──────▶│
│ │◀─────────────────────┤
│ │ │
│◀──Response────────────────┤ │
│ (download URL if update) │ │
│ │ │
├──GET /download/{uuid}────▶│ │
│ │ │
│◀──Firmware Binary─────────┤ │
```
### 3. Fallback Support
If Manager API unavailable, devices can connect to:
- Xiaozhi Server OTA endpoint: `http://server:8003/ota/`
- Provides basic connectivity information
- No firmware updates (returns current version)
---
## Version Comparison Logic
The system uses semantic versioning (MAJOR.MINOR.PATCH):
```java
private int compareVersions(String v1, String v2) {
String[] parts1 = v1.split("\\.");
String[] parts2 = v2.split("\\.");
for (int i = 0; i < Math.max(parts1.length, parts2.length); i++) {
int num1 = i < parts1.length ? Integer.parseInt(parts1[i]) : 0;
int num2 = i < parts2.length ? Integer.parseInt(parts2[i]) : 0;
if (num1 != num2) {
return Integer.compare(num1, num2);
}
}
return 0;
}
```
**Examples**:
- 1.7.7 > 1.7.6 ✓ (Update available)
- 2.0.0 > 1.9.9 ✓ (Major update)
- 1.7.6 = 1.7.6 ✗ (No update)
---
## Troubleshooting
### Common Issues
1. **"OTA接口不正常,缺少websocket地址"**
- Solution: Configure `server.websocket` parameter
2. **"OTA接口不正常,缺少ota地址"**
- Solution: Configure `server.ota` parameter
3. **Firmware file not found**
- Check file exists in `uploadfile/` directory
- Verify path in database matches actual file
4. **Device not receiving updates**
- Check `auto_update` flag is enabled (not 0)
- Verify device type matches firmware type
- Ensure version number is higher
5. **Download limit exceeded**
- UUID expired after 3 attempts
- Generate new download link
---
## Best Practices
1. **Version Management**
- Use semantic versioning consistently
- Test firmware thoroughly before deployment
- Keep previous versions for rollback
2. **Security**
- Regular security audits of firmware
- Monitor download patterns for abuse
- Use HTTPS in production
3. **Device Management**
- Group devices by type for targeted updates
- Implement staged rollouts for critical updates
- Monitor update success rates
4. **Storage Management**
- Regular cleanup of old firmware files
- Backup firmware files externally
- Monitor disk space usage
---
## Future Enhancements
Potential improvements to consider:
- Delta updates for bandwidth optimization
- Rollback mechanism for failed updates
- Update scheduling and staging
- Device group management
- Update progress tracking
- Firmware signing and verification
- Automated testing before deployment
---
*Last Updated: 2025-08-25*
*Document Version: 1.0.0*

View file

@ -1,205 +0,0 @@
#!/usr/bin/env python3
"""
Script to add mem0.api_key system parameter
This will bypass the API key masking issue
"""
import pymysql
import json
import sys
from datetime import datetime
# Database configuration - from application-dev.yml
DB_CONFIG = {
'host': 'nozomi.proxy.rlwy.net', # Railway MySQL host
'port': 25037, # Railway MySQL port
'user': 'root', # Database username
'password': 'OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm', # Database password
'database': 'railway', # Database name
'charset': 'utf8mb4',
'connect_timeout': 30, # Connection timeout in seconds
'read_timeout': 30,
'write_timeout': 30,
'autocommit': False,
'ssl': {'ssl_disabled': False} # Enable SSL as per JDBC config
}
# The actual mem0 API key
MEM0_API_KEY = "m0-WNBvGhsBGZU1NDKDF42ecLNAgMk0GRaToaKLT0wN"
# Colors for output
class Colors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
def print_header(text):
"""Print a formatted header"""
print(f"\n{Colors.HEADER}{'='*80}{Colors.ENDC}")
print(f"{Colors.HEADER}{text}{Colors.ENDC}")
print(f"{Colors.HEADER}{'='*80}{Colors.ENDC}")
def print_success(text):
"""Print success message"""
print(f"{Colors.OKGREEN}[OK] {text}{Colors.ENDC}")
def print_error(text):
"""Print error message"""
print(f"{Colors.FAIL}[ERROR] {text}{Colors.ENDC}")
def print_info(text):
"""Print info message"""
print(f"{Colors.OKCYAN}[INFO] {text}{Colors.ENDC}")
def print_warning(text):
"""Print warning message"""
print(f"{Colors.WARNING}[WARNING] {text}{Colors.ENDC}")
def connect_to_database():
"""Connect to the MySQL database"""
try:
print_info("Connecting to database...")
connection = pymysql.connect(**DB_CONFIG)
# Test the connection
with connection.cursor() as cursor:
cursor.execute("SELECT 1")
cursor.fetchone()
print_success("Successfully connected to database")
return connection
except Exception as e:
print_error(f"Failed to connect to database: {str(e)}")
return None
def add_system_parameter(connection):
"""Add mem0.api_key system parameter"""
try:
with connection.cursor() as cursor:
# Check if parameter already exists
cursor.execute("SELECT * FROM sys_params WHERE param_code = %s", ('mem0.api_key',))
existing = cursor.fetchone()
if existing:
print_warning("Parameter mem0.api_key already exists:")
print(f" Current value: {existing[2][:10]}...{existing[2][-10:] if len(existing[2]) > 20 else existing[2]}")
response = input(f"{Colors.WARNING}Do you want to update it? (yes/no): {Colors.ENDC}").lower()
if response not in ['yes', 'y']:
print_info("Skipping update")
return True
# Update existing parameter
update_query = """
UPDATE sys_params
SET param_value = %s,
update_date = NOW(),
updater = 1
WHERE param_code = %s
"""
cursor.execute(update_query, (MEM0_API_KEY, 'mem0.api_key'))
connection.commit()
print_success("Updated existing mem0.api_key parameter")
else:
# Get the next ID
cursor.execute("SELECT MAX(id) FROM sys_params")
max_id = cursor.fetchone()[0]
next_id = (max_id or 0) + 1
# Insert new parameter
insert_query = """
INSERT INTO sys_params (id, param_code, param_value, value_type, param_type, remark, create_date, creator)
VALUES (%s, %s, %s, %s, %s, %s, NOW(), %s)
"""
cursor.execute(insert_query, (
next_id,
'mem0.api_key',
MEM0_API_KEY,
'string',
1, # param_type: 1 for system parameters
'Mem0 AI API key for memory management',
1 # creator: admin user
))
connection.commit()
print_success("Added new mem0.api_key system parameter")
return True
except Exception as e:
connection.rollback()
print_error(f"Failed to add system parameter: {str(e)}")
return False
def verify_parameter(connection):
"""Verify the parameter was added correctly"""
try:
with connection.cursor() as cursor:
cursor.execute("SELECT * FROM sys_params WHERE param_code = %s", ('mem0.api_key',))
result = cursor.fetchone()
if result:
print_success("Parameter verification successful:")
print(f" ID: {result[0]}")
print(f" Code: {result[1]}")
print(f" Value: {result[2][:10]}...{result[2][-10:]}")
print(f" Type: {result[3]}")
print(f" Remark: {result[5]}")
return True
else:
print_error("Parameter not found after insertion")
return False
except Exception as e:
print_error(f"Failed to verify parameter: {str(e)}")
return False
def main():
"""Main function"""
print_header("Add Mem0 API Key System Parameter")
print_info(f"Target API Key: {MEM0_API_KEY[:10]}...{MEM0_API_KEY[-10:]}")
print_info(f"Timestamp: {datetime.now().isoformat()}")
# Connect to database
connection = connect_to_database()
if not connection:
print_error("Cannot proceed without database connection")
return 1
try:
# Add system parameter
if add_system_parameter(connection):
# Verify the parameter
if verify_parameter(connection):
print_success("\n✅ System parameter added successfully!")
print_info("\nNext steps:")
print_info("1. Restart the manager-api service to load the new parameter")
print_info("2. Test device connection again")
print_info("3. Check that mem0 authentication now works")
return 0
else:
return 1
else:
return 1
finally:
connection.close()
print_info("Database connection closed")
if __name__ == "__main__":
try:
sys.exit(main())
except KeyboardInterrupt:
print("\n\nScript interrupted by user")
sys.exit(0)
except Exception as e:
print_error(f"Unexpected error: {str(e)}")
sys.exit(1)

View file

@ -1,197 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Script to add MQTT configuration parameters to Railway MySQL database
"""
import pymysql
import sys
import io
from typing import Optional
# Set UTF-8 encoding for Windows console
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
# Railway MySQL Database configuration
DB_CONFIG = {
'host': 'nozomi.proxy.rlwy.net',
'port': 25037,
'user': 'root',
'password': 'OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm',
'database': 'railway',
'charset': 'utf8mb4'
}
# MQTT parameters to add
MQTT_PARAMS = [
{
'id': 120,
'param_code': 'mqtt.broker',
'param_value': '192.168.1.107',
'value_type': 'string',
'param_type': 1,
'remark': 'MQTT broker IP address'
},
{
'id': 121,
'param_code': 'mqtt.port',
'param_value': '1883',
'value_type': 'string',
'param_type': 1,
'remark': 'MQTT broker port'
},
{
'id': 122,
'param_code': 'mqtt.signature_key',
'param_value': 'test-signature-key-12345',
'value_type': 'string',
'param_type': 1,
'remark': 'MQTT signature key for authentication'
}
]
def connect_to_db():
"""Connect to the Railway MySQL database"""
try:
connection = pymysql.connect(**DB_CONFIG)
print(f"✅ Connected to Railway MySQL database")
return connection
except pymysql.Error as e:
print(f"❌ Failed to connect to database: {e}")
sys.exit(1)
def check_existing_params(cursor, param_code: str) -> Optional[dict]:
"""Check if a parameter already exists"""
query = "SELECT * FROM sys_params WHERE param_code = %s"
cursor.execute(query, (param_code,))
result = cursor.fetchone()
return result
def get_next_available_id(cursor) -> int:
"""Get the next available ID for sys_params table"""
query = "SELECT MAX(id) as max_id FROM sys_params"
cursor.execute(query)
result = cursor.fetchone()
if result and result['max_id']:
return result['max_id'] + 1
return 120 # Start from 120 if table is empty
def insert_or_update_param(cursor, param: dict) -> bool:
"""Insert a new parameter or update existing one"""
try:
# First check if it already exists
existing = check_existing_params(cursor, param['param_code'])
if existing:
print(f"⚠️ Parameter '{param['param_code']}' already exists with value: {existing['param_value']}")
# Update the existing parameter
update_query = """
UPDATE sys_params
SET param_value = %s, remark = %s
WHERE param_code = %s
"""
cursor.execute(update_query, (param['param_value'], param['remark'], param['param_code']))
print(f" ✅ Updated parameter '{param['param_code']}' to: {param['param_value']}")
return True
# Get next available ID if the specified one is taken
check_id_query = "SELECT id FROM sys_params WHERE id = %s"
cursor.execute(check_id_query, (param['id'],))
if cursor.fetchone():
param['id'] = get_next_available_id(cursor)
print(f" ℹ️ Using ID {param['id']} for '{param['param_code']}'")
# Insert new parameter
insert_query = """
INSERT INTO sys_params (id, param_code, param_value, value_type, param_type, remark)
VALUES (%s, %s, %s, %s, %s, %s)
"""
cursor.execute(insert_query, (
param['id'],
param['param_code'],
param['param_value'],
param['value_type'],
param['param_type'],
param['remark']
))
print(f"✅ Added parameter '{param['param_code']}' with value: {param['param_value']}")
return True
except pymysql.Error as e:
print(f"❌ Failed to insert/update '{param['param_code']}': {e}")
return False
def verify_params(cursor):
"""Verify that all MQTT parameters are in the database"""
print("\n📋 Current MQTT parameters in database:")
print("-" * 50)
query = "SELECT param_code, param_value, remark FROM sys_params WHERE param_code LIKE 'mqtt.%' ORDER BY param_code"
cursor.execute(query)
results = cursor.fetchall()
if results:
for row in results:
print(f" • {row['param_code']}: {row['param_value']}")
print(f" ({row['remark']})")
else:
print(" No MQTT parameters found")
return len(results) > 0
def main():
print("🔧 Railway MySQL - MQTT Parameter Configuration Tool")
print("=" * 60)
print(f"📍 Connecting to: {DB_CONFIG['host']}:{DB_CONFIG['port']}")
print(f"📦 Database: {DB_CONFIG['database']}")
print("=" * 60)
# Connect to database
connection = connect_to_db()
try:
with connection.cursor(pymysql.cursors.DictCursor) as cursor:
print("\n📝 Adding/Updating MQTT parameters...")
print("-" * 50)
# Add each parameter
changes_made = False
for param in MQTT_PARAMS:
if insert_or_update_param(cursor, param):
changes_made = True
# Commit changes
if changes_made:
connection.commit()
print("\n✅ All changes committed to database")
else:
print("\n⚠️ No changes were made")
# Verify parameters
verify_params(cursor)
print("\n" + "=" * 60)
print("✅ MQTT parameters configuration complete!")
print("\n⚠️ IMPORTANT NEXT STEPS:")
print(" 1. Restart the manager-api server for changes to take effect")
print(" 2. The ESP32 device should now receive MQTT configuration")
print(" 3. The Python client should also connect successfully")
except Exception as e:
print(f"❌ An error occurred: {e}")
connection.rollback()
finally:
connection.close()
print("\n🔌 Database connection closed")
if __name__ == "__main__":
print("\n🚀 This script will configure MQTT parameters in your Railway MySQL database")
print(" The following parameters will be added/updated:")
print(" • mqtt.broker: 139.59.7.72")
print(" • mqtt.port: 1883")
print(" • mqtt.signature_key: test-signature-key-12345\n")
try:
main()
except KeyboardInterrupt:
print("\n\n❌ Operation cancelled by user")
except Exception as e:
print(f"\n❌ Unexpected error: {e}")

View file

@ -1,360 +0,0 @@
#!/usr/bin/env python3
"""
Script to check agent templates and functions structure, and fix Story Playback function placement
"""
import mysql.connector
from mysql.connector import Error
import json
from tabulate import tabulate
def connect_to_database():
"""Connect to the Railway MySQL database"""
try:
connection = mysql.connector.connect(
host='nozomi.proxy.rlwy.net',
port=25037,
database='railway',
user='root',
password='OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm',
charset='utf8mb4',
use_unicode=True,
ssl_disabled=True
)
if connection.is_connected():
print("Successfully connected to Railway MySQL database")
return connection
except Error as e:
print(f"Error connecting to MySQL: {e}")
return None
def get_all_tables(connection):
"""Get all tables in the database"""
cursor = connection.cursor()
try:
cursor.execute("SHOW TABLES")
tables = cursor.fetchall()
print(f"\nAll tables in the database:")
for table in tables:
print(f" - {table[0]}")
return [table[0] for table in tables]
except Error as e:
print(f"Error getting tables: {e}")
return None
finally:
cursor.close()
def search_agent_related_tables(connection):
"""Search for agent-related tables"""
cursor = connection.cursor()
try:
cursor.execute("SHOW TABLES LIKE '%agent%'")
agent_tables = cursor.fetchall()
cursor.execute("SHOW TABLES LIKE '%template%'")
template_tables = cursor.fetchall()
cursor.execute("SHOW TABLES LIKE '%function%'")
function_tables = cursor.fetchall()
print(f"\nAgent-related tables:")
for table in agent_tables:
print(f" - {table[0]}")
print(f"\nTemplate-related tables:")
for table in template_tables:
print(f" - {table[0]}")
print(f"\nFunction-related tables:")
for table in function_tables:
print(f" - {table[0]}")
return agent_tables + template_tables + function_tables
except Error as e:
print(f"Error searching agent tables: {e}")
return None
finally:
cursor.close()
def examine_table_structure(connection, table_name):
"""Get detailed structure of a table"""
cursor = connection.cursor()
try:
print(f"\n{'='*60}")
print(f"Structure of table '{table_name}':")
print('='*60)
cursor.execute(f"DESCRIBE {table_name}")
columns = cursor.fetchall()
headers = ["Field", "Type", "Null", "Key", "Default", "Extra"]
print(tabulate(columns, headers=headers, tablefmt="grid"))
# Get sample data
cursor.execute(f"SELECT * FROM {table_name} LIMIT 5")
sample_data = cursor.fetchall()
if sample_data:
print(f"\nSample data from '{table_name}':")
column_names = [desc[0] for desc in cursor.description]
print(tabulate(sample_data, headers=column_names, tablefmt="grid"))
return columns
except Error as e:
print(f"Error examining table {table_name}: {e}")
return None
finally:
cursor.close()
def search_story_playback(connection):
"""Search for Story Playback function references"""
cursor = connection.cursor()
try:
print(f"\n{'='*60}")
print("Searching for 'Story Playback' references in the database...")
print('='*60)
# Get all tables
cursor.execute("SHOW TABLES")
tables = [table[0] for table in cursor.fetchall()]
found_references = []
for table in tables:
try:
# Get column names for this table
cursor.execute(f"DESCRIBE {table}")
columns = cursor.fetchall()
text_columns = [col[0] for col in columns if 'text' in col[1].lower() or 'varchar' in col[1].lower() or 'json' in col[1].lower()]
if text_columns:
# Search in each text column
for column in text_columns:
search_query = f"SELECT * FROM {table} WHERE {column} LIKE '%Story Playback%' OR {column} LIKE '%story_playback%' OR {column} LIKE '%storyplayback%'"
cursor.execute(search_query)
results = cursor.fetchall()
if results:
found_references.append({
'table': table,
'column': column,
'results': results
})
print(f"\nFound 'Story Playback' in {table}.{column}:")
column_names = [desc[0] for desc in cursor.description]
print(tabulate(results, headers=column_names, tablefmt="grid"))
except Error as e:
# Skip tables that might cause errors
continue
return found_references
except Error as e:
print(f"Error searching for Story Playback: {e}")
return None
finally:
cursor.close()
def check_agent_templates(connection):
"""Check agent templates and their configurations"""
cursor = connection.cursor()
try:
print(f"\n{'='*60}")
print("Checking agent templates...")
print('='*60)
# Look for agent template related tables
possible_tables = ['agent_template', 'agent_templates', 'toy', 'agent_config', 'agent_configuration']
for table_name in possible_tables:
try:
cursor.execute(f"SELECT * FROM {table_name} LIMIT 3")
results = cursor.fetchall()
if results:
print(f"\nFound data in table '{table_name}':")
column_names = [desc[0] for desc in cursor.description]
print(tabulate(results, headers=column_names, tablefmt="grid"))
# Check if any columns contain JSON that might have function configurations
for i, row in enumerate(results[:1]): # Check first row only
for j, cell in enumerate(row):
if isinstance(cell, str) and (cell.strip().startswith('{') or cell.strip().startswith('[')):
try:
json_data = json.loads(cell)
print(f"\nJSON data in {table_name}.{column_names[j]} (row {i+1}):")
print(json.dumps(json_data, indent=2))
except:
pass
except Error:
continue
except Error as e:
print(f"Error checking agent templates: {e}")
finally:
cursor.close()
def fix_story_playback_function(connection):
"""Fix Story Playback function to be in Selected Functions for all agent templates"""
cursor = connection.cursor()
try:
print(f"\n{'='*60}")
print("Attempting to fix Story Playback function placement...")
print('='*60)
# First, let's find where the functions are stored
# Look for common table names that might store agent configurations
possible_tables = ['toy', 'agent_template', 'agent_config']
for table_name in possible_tables:
try:
# Get all records from the table
cursor.execute(f"SELECT * FROM {table_name}")
results = cursor.fetchall()
column_names = [desc[0] for desc in cursor.description]
if results:
print(f"\nChecking table '{table_name}' for function configurations...")
for i, row in enumerate(results):
row_dict = dict(zip(column_names, row))
# Look for JSON fields that might contain function configurations
for col_name, cell_value in row_dict.items():
if isinstance(cell_value, str) and cell_value.strip().startswith('{'):
try:
json_data = json.loads(cell_value)
# Look for function-related keys
if any(key in json_data for key in ['selected_functions', 'unselected_functions', 'functions', 'selectedFunctions', 'unselectedFunctions']):
print(f"\nFound function configuration in {table_name}, row {i+1}, column '{col_name}':")
print(f"Record ID/identifier: {row_dict.get('id', row_dict.get('template_id', 'Unknown'))}")
# Check if Story Playback is in unselected functions
needs_update = False
updated_data = json_data.copy()
# Handle different possible key names
unselected_key = None
selected_key = None
for key in ['unselected_functions', 'unselectedFunctions']:
if key in json_data:
unselected_key = key
break
for key in ['selected_functions', 'selectedFunctions']:
if key in json_data:
selected_key = key
break
if unselected_key and selected_key:
unselected_functions = json_data.get(unselected_key, [])
selected_functions = json_data.get(selected_key, [])
# Look for Story Playback in unselected functions
story_playback_item = None
for func in unselected_functions:
if isinstance(func, dict) and 'Story Playback' in str(func):
story_playback_item = func
break
elif isinstance(func, str) and 'Story Playback' in func:
story_playback_item = func
break
if story_playback_item:
print(f"Found Story Playback in unselected functions: {story_playback_item}")
# Move it to selected functions
updated_data[unselected_key] = [f for f in unselected_functions if f != story_playback_item]
updated_data[selected_key] = selected_functions + [story_playback_item]
# Update the database
update_query = f"UPDATE {table_name} SET {col_name} = %s WHERE "
if 'id' in row_dict:
update_query += "id = %s"
update_params = [json.dumps(updated_data), row_dict['id']]
else:
# Use the first column as identifier
first_col = column_names[0]
update_query += f"{first_col} = %s"
update_params = [json.dumps(updated_data), row_dict[first_col]]
print(f"Executing update query: {update_query}")
print(f"Parameters: {update_params[1]} (ID), [JSON data]")
cursor.execute(update_query, update_params)
connection.commit()
print(f"✓ Successfully moved Story Playback to selected functions for record {row_dict.get('id', row_dict[column_names[0]])}")
needs_update = True
else:
print(f"Story Playback not found in unselected functions for this record")
# Print the current function configuration
print(f"Current function configuration:")
print(json.dumps(json_data, indent=2))
except json.JSONDecodeError:
continue
except Error as e:
print(f"Error processing table {table_name}: {e}")
continue
print(f"\nFunction placement fix completed!")
except Error as e:
print(f"Error fixing Story Playback function: {e}")
finally:
cursor.close()
def main():
print("Checking xiaozhi database for agent templates and Story Playback function")
print("=" * 80)
# Connect to database
connection = connect_to_database()
if not connection:
return
try:
# Get all tables
print("\n" + "="*60)
tables = get_all_tables(connection)
# Search for agent-related tables
print("\n" + "="*60)
agent_tables = search_agent_related_tables(connection)
# Examine key tables
key_tables = ['toy'] # Start with 'toy' as it's likely the main agent config table
for table in key_tables:
if table in tables:
examine_table_structure(connection, table)
# Search for Story Playback references
search_story_playback(connection)
# Check agent templates
check_agent_templates(connection)
# Fix Story Playback function placement
fix_story_playback_function(connection)
finally:
if connection.is_connected():
connection.close()
print(f"\nMySQL connection closed")
if __name__ == "__main__":
main()

View file

@ -1,186 +0,0 @@
#!/usr/bin/env python3
"""
Script to check the ai_model_provider table structure and existing ASR services
"""
import mysql.connector
from mysql.connector import Error
import json
from tabulate import tabulate
def connect_to_database():
"""Connect to the Railway MySQL database"""
try:
connection = mysql.connector.connect(
host='nozomi.proxy.rlwy.net',
port=25037,
database='railway',
user='root',
password='OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm',
charset='utf8mb4',
use_unicode=True,
ssl_disabled=True
)
if connection.is_connected():
print("Successfully connected to Railway MySQL database")
return connection
except Error as e:
print(f"Error connecting to MySQL: {e}")
return None
def get_table_structure(connection, table_name):
"""Get the structure of a table"""
cursor = connection.cursor()
try:
cursor.execute(f"DESCRIBE {table_name}")
columns = cursor.fetchall()
print(f"\nStructure of table '{table_name}':")
headers = ["Field", "Type", "Null", "Key", "Default", "Extra"]
print(tabulate(columns, headers=headers, tablefmt="grid"))
return columns
except Error as e:
print(f"Error getting table structure: {e}")
return None
finally:
cursor.close()
def get_existing_asr_providers(connection):
"""Get all existing ASR providers"""
cursor = connection.cursor()
try:
cursor.execute("""
SELECT id, model_type, provider_code, name, LENGTH(id) as id_length
FROM ai_model_provider
WHERE model_type = 'ASR'
ORDER BY id
""")
providers = cursor.fetchall()
print(f"\nExisting ASR providers:")
headers = ["ID", "Model Type", "Provider Code", "Name", "ID Length"]
print(tabulate(providers, headers=headers, tablefmt="grid"))
return providers
except Error as e:
print(f"Error getting ASR providers: {e}")
return None
finally:
cursor.close()
def get_existing_asr_configs(connection):
"""Get all existing ASR model configurations"""
cursor = connection.cursor()
try:
cursor.execute("""
SELECT id, model_type, model_code, model_name, LENGTH(id) as id_length
FROM ai_model_config
WHERE model_type = 'ASR'
ORDER BY id
""")
configs = cursor.fetchall()
print(f"\nExisting ASR model configurations:")
headers = ["ID", "Model Type", "Model Code", "Model Name", "ID Length"]
print(tabulate(configs, headers=headers, tablefmt="grid"))
return configs
except Error as e:
print(f"Error getting ASR configs: {e}")
return None
finally:
cursor.close()
def analyze_id_constraints(providers, configs):
"""Analyze ID length constraints"""
print(f"\nID Length Analysis:")
if providers:
provider_lengths = [row[4] for row in providers] # ID length is 5th column
print(f"Provider ID lengths: {provider_lengths}")
print(f"Max provider ID length: {max(provider_lengths)}")
print(f"Min provider ID length: {min(provider_lengths)}")
if configs:
config_lengths = [row[4] for row in configs] # ID length is 5th column
print(f"Config ID lengths: {config_lengths}")
print(f"Max config ID length: {max(config_lengths)}")
print(f"Min config ID length: {min(config_lengths)}")
# Check our proposed ID
proposed_provider_id = "SYSTEM_ASR_AmazonTranscribeStreaming"
proposed_config_id = "ASR_AmazonTranscribeStreaming"
print(f"\nOur proposed IDs:")
print(f"Provider ID: '{proposed_provider_id}' (length: {len(proposed_provider_id)})")
print(f"Config ID: '{proposed_config_id}' (length: {len(proposed_config_id)})")
if providers and len(proposed_provider_id) > max(provider_lengths):
print(f"WARNING: Proposed provider ID is longer than existing max ({max(provider_lengths)})")
if configs and len(proposed_config_id) > max(config_lengths):
print(f"WARNING: Proposed config ID is longer than existing max ({max(config_lengths)})")
def suggest_shorter_ids():
"""Suggest shorter ID alternatives"""
print(f"\nSuggested shorter IDs:")
alternatives = [
("SYSTEM_ASR_AmazonTS", "ASR_AmazonTS"),
("SYSTEM_ASR_AwsTranscribe", "ASR_AwsTranscribe"),
("SYSTEM_ASR_AmazonStream", "ASR_AmazonStream"),
("SYSTEM_ASR_AWSStream", "ASR_AWSStream"),
]
headers = ["Provider ID", "Config ID", "Provider Length", "Config Length"]
rows = []
for provider_id, config_id in alternatives:
rows.append([provider_id, config_id, len(provider_id), len(config_id)])
print(tabulate(rows, headers=headers, tablefmt="grid"))
def main():
print("Checking xiaozhi database structure for Amazon Transcribe integration")
print("=" * 70)
# Connect to database
connection = connect_to_database()
if not connection:
return
try:
# Get table structures
print("\n" + "="*50)
provider_structure = get_table_structure(connection, "ai_model_provider")
print("\n" + "="*50)
config_structure = get_table_structure(connection, "ai_model_config")
# Get existing ASR services
print("\n" + "="*50)
providers = get_existing_asr_providers(connection)
print("\n" + "="*50)
configs = get_existing_asr_configs(connection)
# Analyze constraints
print("\n" + "="*50)
analyze_id_constraints(providers, configs)
# Suggest alternatives
print("\n" + "="*50)
suggest_shorter_ids()
finally:
if connection.is_connected():
connection.close()
print(f"\nMySQL connection closed")
if __name__ == "__main__":
main()

View file

@ -1,379 +0,0 @@
#!/usr/bin/env python3
"""
Comprehensive script to check Story Playback function mapping in both database and local config
"""
import mysql.connector
from mysql.connector import Error
import json
import yaml
import os
def connect_to_database():
"""Connect to the Railway MySQL database"""
try:
connection = mysql.connector.connect(
host='nozomi.proxy.rlwy.net',
port=25037,
database='railway',
user='root',
password='OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm',
charset='utf8mb4',
use_unicode=True,
ssl_disabled=True
)
if connection.is_connected():
print("Successfully connected to Railway MySQL database")
return connection
except Error as e:
print(f"Error connecting to MySQL: {e}")
return None
def check_story_plugin_in_database(connection):
"""Check if Story Playback plugin exists in database"""
cursor = connection.cursor()
try:
print(f"\n{'='*60}")
print("1. Checking Story Playback Plugin in Database")
print('='*60)
# Check if SYSTEM_PLUGIN_STORY exists in ai_model_provider
cursor.execute("""
SELECT id, model_type, provider_code, name, fields
FROM ai_model_provider
WHERE id = 'SYSTEM_PLUGIN_STORY' OR name LIKE '%Story%'
""")
story_plugins = cursor.fetchall()
if story_plugins:
print(f"Found Story Playback plugins:")
for plugin in story_plugins:
plugin_id, model_type, provider_code, name, fields = plugin
print(f" ID: {plugin_id}")
print(f" Type: {model_type}")
print(f" Provider Code: {provider_code}")
print(f" Name: {name}")
if fields:
try:
fields_json = json.loads(fields)
print(f" Fields: {json.dumps(fields_json, indent=4)}")
except:
print(f" Fields: {fields}")
print()
else:
print("No Story Playback plugin found in database!")
return story_plugins
except Error as e:
print(f"Error checking story plugin: {e}")
return None
finally:
cursor.close()
def check_intent_functions_in_database(connection):
"""Check Intent function call configurations in database"""
cursor = connection.cursor()
try:
print(f"\n{'='*60}")
print("2. Checking Intent Function Call Configurations")
print('='*60)
# Check if there's an Intent function call configuration
cursor.execute("""
SELECT id, model_type, provider_code, name, fields
FROM ai_model_provider
WHERE model_type = 'Intent' AND provider_code = 'function_call'
""")
intent_configs = cursor.fetchall()
if intent_configs:
print(f"Found Intent function call configurations:")
for config in intent_configs:
config_id, model_type, provider_code, name, fields = config
print(f" ID: {config_id}")
print(f" Name: {name}")
if fields:
try:
fields_json = json.loads(fields)
print(f" Fields: {json.dumps(fields_json, indent=2)}")
# Look for functions list
for field in fields_json:
if field.get('key') == 'functions' and 'default' in field:
functions = field['default']
print(f" Available functions: {functions}")
if 'play_story' in str(functions).lower():
print(" [✓] play_story found in functions!")
else:
print(" [✗] play_story NOT found in functions!")
except Exception as e:
print(f" Fields (raw): {fields}")
print(f" Error parsing fields: {e}")
print()
else:
print("No Intent function call configuration found!")
return intent_configs
except Error as e:
print(f"Error checking intent functions: {e}")
return None
finally:
cursor.close()
def check_agent_plugin_mappings(connection):
"""Check which agents have Story Playback mapped"""
cursor = connection.cursor()
try:
print(f"\n{'='*60}")
print("3. Checking Agent-Plugin Mappings for Story Playback")
print('='*60)
# Get all agents and check their Story Playback mapping
cursor.execute("""
SELECT
a.id as agent_id,
a.agent_name,
apm.plugin_id,
apm.param_info
FROM ai_agent a
LEFT JOIN ai_agent_plugin_mapping apm
ON a.id = apm.agent_id AND apm.plugin_id = 'SYSTEM_PLUGIN_STORY'
ORDER BY a.agent_name
""")
mappings = cursor.fetchall()
total_agents = len(set([m[0] for m in mappings if m[0] is not None]))
agents_with_story = len([m for m in mappings if m[2] == 'SYSTEM_PLUGIN_STORY'])
print(f"Agent Story Playback Mapping Status:")
print(f"Total agents: {total_agents}")
print(f"Agents with Story Playback: {agents_with_story}")
print()
for mapping in mappings:
agent_id, agent_name, plugin_id, param_info = mapping
if plugin_id == 'SYSTEM_PLUGIN_STORY':
print(f"[✓] {agent_name} (ID: {agent_id}) - HAS Story Playback")
if param_info:
try:
params = json.loads(param_info)
print(f" Parameters: {json.dumps(params, indent=6)}")
except:
print(f" Parameters: {param_info}")
else:
print(f"[✗] {agent_name} (ID: {agent_id}) - MISSING Story Playback")
return mappings
except Error as e:
print(f"Error checking agent mappings: {e}")
return None
finally:
cursor.close()
def check_local_config_file():
"""Check the local config file for play_story function"""
try:
print(f"\n{'='*60}")
print("4. Checking Local Config File")
print('='*60)
config_path = "D:/cheekofinal/xiaozhi-esp32-server/main/xiaozhi-server/data/.config.yaml"
if not os.path.exists(config_path):
print(f"Config file not found: {config_path}")
return None
with open(config_path, 'r', encoding='utf-8') as file:
config_content = file.read()
print(f"Config file location: {config_path}")
print(f"File size: {len(config_content)} characters")
# Look for Intent section
if 'Intent:' in config_content:
print(f"[✓] Intent section found in config")
# Look for function_call
if 'function_call:' in config_content:
print(f"[✓] function_call section found")
# Look for functions list
if 'functions:' in config_content:
print(f"[✓] functions list found")
# Extract functions section
lines = config_content.split('\n')
in_functions = False
functions = []
for line in lines:
if 'functions:' in line and 'function_call:' in config_content[max(0, config_content.find(line)-200):config_content.find(line)]:
in_functions = True
continue
elif in_functions:
if line.strip().startswith('- '):
func_name = line.strip()[2:].strip()
functions.append(func_name)
elif line.strip() and not line.startswith(' ') and not line.startswith('#'):
break
print(f"Functions found in config:")
for func in functions:
if 'story' in func.lower():
print(f" [✓] {func}")
else:
print(f" - {func}")
if 'play_story' in functions:
print(f"[✓] play_story is configured in local config!")
else:
print(f"[✗] play_story is NOT configured in local config!")
return functions
else:
print(f"[✗] functions list not found in function_call section")
else:
print(f"[✗] function_call section not found in Intent")
else:
print(f"[✗] Intent section not found in config")
return None
except Exception as e:
print(f"Error checking local config: {e}")
return None
def fix_missing_story_function_in_database(connection):
"""Fix missing Story Playback function in Intent configuration if needed"""
cursor = connection.cursor()
try:
print(f"\n{'='*60}")
print("5. Fixing Intent Function Configuration if Needed")
print('='*60)
# Get the Intent function call configuration
cursor.execute("""
SELECT id, fields
FROM ai_model_provider
WHERE model_type = 'Intent' AND provider_code = 'function_call'
LIMIT 1
""")
result = cursor.fetchone()
if result:
config_id, fields = result
print(f"Found Intent config ID: {config_id}")
try:
fields_json = json.loads(fields)
# Find the functions field
functions_field = None
for i, field in enumerate(fields_json):
if field.get('key') == 'functions':
functions_field = field
field_index = i
break
if functions_field:
current_functions = functions_field.get('default', '')
print(f"Current functions: {current_functions}")
# Check if play_story is already there
if 'play_story' not in current_functions.lower():
# Add play_story to the functions
if current_functions:
# Parse existing functions (assuming they're in a string format)
if current_functions.endswith(';'):
updated_functions = current_functions + 'play_story'
else:
updated_functions = current_functions + ';play_story'
else:
updated_functions = 'play_story'
# Update the field
fields_json[field_index]['default'] = updated_functions
# Update database
cursor.execute("""
UPDATE ai_model_provider
SET fields = %s
WHERE id = %s
""", (json.dumps(fields_json), config_id))
connection.commit()
print(f"[✓] Updated Intent functions to: {updated_functions}")
print(f"[✓] play_story added to Intent configuration!")
else:
print(f"[✓] play_story already exists in Intent configuration")
else:
print(f"[✗] functions field not found in Intent configuration")
except json.JSONDecodeError as e:
print(f"[✗] Error parsing Intent configuration JSON: {e}")
else:
print(f"[✗] No Intent function call configuration found in database")
except Error as e:
print(f"Error fixing Intent configuration: {e}")
connection.rollback()
finally:
cursor.close()
def main():
print("Comprehensive Story Playback Function Mapping Check")
print("=" * 80)
# Check database
connection = connect_to_database()
if connection:
try:
# Check story plugin exists
story_plugins = check_story_plugin_in_database(connection)
# Check intent function configurations
intent_configs = check_intent_functions_in_database(connection)
# Check agent mappings
agent_mappings = check_agent_plugin_mappings(connection)
# Fix Intent configuration if needed
fix_missing_story_function_in_database(connection)
finally:
connection.close()
# Check local config
local_functions = check_local_config_file()
# Summary
print(f"\n{'='*60}")
print("SUMMARY")
print('='*60)
if story_plugins:
print("[✓] Story Playback plugin exists in database")
else:
print("[✗] Story Playback plugin MISSING from database")
if local_functions and 'play_story' in local_functions:
print("[✓] play_story configured in local config")
else:
print("[✗] play_story MISSING from local config")
print(f"\nThe script has checked both database and local configurations.")
print(f"If any issues were found, they should now be fixed!")
if __name__ == "__main__":
main()

View file

@ -1,271 +0,0 @@
#!/usr/bin/env python3
"""
Check sys_params table structure and add default plugins configuration
"""
import mysql.connector
from mysql.connector import Error
import json
def connect_to_database():
"""Connect to the Railway MySQL database"""
try:
connection = mysql.connector.connect(
host='nozomi.proxy.rlwy.net',
port=25037,
database='railway',
user='root',
password='OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm',
charset='utf8mb4',
use_unicode=True,
ssl_disabled=True
)
if connection.is_connected():
print("Connected to Railway MySQL database")
return connection
except Error as e:
print(f"Database connection error: {e}")
return None
def check_sys_params_structure(connection):
"""Check the structure of sys_params table"""
cursor = connection.cursor()
try:
print("\n1. Checking sys_params table structure...")
print("=" * 50)
cursor.execute("DESCRIBE sys_params")
columns = cursor.fetchall()
print("sys_params columns:")
for col in columns:
print(f" {col[0]} - {col[1]}")
return [col[0] for col in columns]
except Error as e:
print(f"Error checking sys_params: {e}")
return []
finally:
cursor.close()
def check_existing_params(connection, column_names):
"""Check existing system parameters"""
cursor = connection.cursor()
try:
print("\n2. Checking existing system parameters...")
print("=" * 50)
# Build query based on actual column names
key_col = None
value_col = None
for col in column_names:
if 'key' in col.lower():
key_col = col
elif 'value' in col.lower():
value_col = col
if not key_col or not value_col:
print("Could not identify key/value columns")
return None, None
print(f"Using columns: {key_col} (key), {value_col} (value)")
# Get plugin-related parameters
query = f"SELECT {key_col}, {value_col} FROM sys_params WHERE {key_col} LIKE '%plugin%' OR {key_col} LIKE '%function%' OR {key_col} LIKE '%default%'"
cursor.execute(query)
params = cursor.fetchall()
if params:
print("Found related parameters:")
for key, value in params:
print(f" {key}: {value[:100] if value else 'NULL'}...")
else:
print("No plugin-related parameters found")
return key_col, value_col
except Error as e:
print(f"Error checking parameters: {e}")
return None, None
finally:
cursor.close()
def add_default_plugins_parameter(connection, key_col, value_col, column_names):
"""Add or update default plugins parameter"""
cursor = connection.cursor()
try:
print("\n3. Adding/Updating default plugins parameter...")
print("=" * 50)
# Check if default_agent_plugins exists
query = f"SELECT {value_col} FROM sys_params WHERE {key_col} = 'default_agent_plugins'"
cursor.execute(query)
existing = cursor.fetchone()
default_plugins = {
"plugins": [
"SYSTEM_PLUGIN_MUSIC",
"SYSTEM_PLUGIN_STORY",
"SYSTEM_PLUGIN_WEATHER",
"SYSTEM_PLUGIN_NEWS_NEWSNOW"
],
"functions": [
"play_music",
"play_story",
"get_weather",
"get_news_from_newsnow",
"get_indian_news_api",
"get_lunar"
]
}
if existing:
print("default_agent_plugins already exists, updating...")
update_query = f"UPDATE sys_params SET {value_col} = %s WHERE {key_col} = %s"
cursor.execute(update_query, (json.dumps(default_plugins), 'default_agent_plugins'))
print("Updated default_agent_plugins")
else:
print("Creating new default_agent_plugins parameter...")
# Build insert query based on available columns
insert_cols = [key_col, value_col]
insert_values = ['default_agent_plugins', json.dumps(default_plugins)]
# Add other columns if they exist
if 'type' in column_names:
insert_cols.append('type')
insert_values.append(1)
elif 'param_type' in column_names:
insert_cols.append('param_type')
insert_values.append(1)
if 'remark' in column_names:
insert_cols.append('remark')
insert_values.append('Default plugins and functions for new agents')
elif 'description' in column_names:
insert_cols.append('description')
insert_values.append('Default plugins and functions for new agents')
# Add timestamp columns if they exist
for col in ['create_date', 'created_at', 'create_time']:
if col in column_names:
insert_cols.append(col)
insert_values.append('NOW()')
break
# Build query
placeholders = ['%s'] * len(insert_values)
# Replace NOW() placeholders
for i, val in enumerate(insert_values):
if val == 'NOW()':
placeholders[i] = 'NOW()'
insert_values[i] = None
insert_query = f"INSERT INTO sys_params ({', '.join(insert_cols)}) VALUES ({', '.join(placeholders)})"
insert_query = insert_query.replace('%s', '%s').replace("'NOW()'", "NOW()")
# Filter out None values for NOW()
insert_values = [v for v in insert_values if v is not None]
print(f"Insert query: {insert_query}")
cursor.execute(insert_query, insert_values)
print("Created default_agent_plugins parameter")
connection.commit()
return True
except Error as e:
print(f"Error adding default plugins: {e}")
connection.rollback()
return False
finally:
cursor.close()
def verify_trigger(connection):
"""Verify the trigger exists"""
cursor = connection.cursor()
try:
print("\n4. Verifying trigger...")
print("=" * 50)
cursor.execute("""
SELECT TRIGGER_NAME, EVENT_MANIPULATION, EVENT_OBJECT_TABLE
FROM information_schema.TRIGGERS
WHERE TRIGGER_SCHEMA = 'railway'
AND TRIGGER_NAME = 'add_story_to_new_agent'
""")
trigger = cursor.fetchone()
if trigger:
print(f"Trigger exists: {trigger[0]}")
print(f" Event: {trigger[1]} on {trigger[2]}")
print("New agents will automatically get Story Playback!")
else:
print("Trigger not found (may have failed to create)")
return trigger is not None
except Error as e:
print(f"Error verifying trigger: {e}")
return False
finally:
cursor.close()
def main():
print("Configuring Default Plugins for New Agents")
print("=" * 70)
connection = connect_to_database()
if not connection:
return
try:
# 1. Check sys_params structure
column_names = check_sys_params_structure(connection)
if column_names:
# 2. Check existing parameters
key_col, value_col = check_existing_params(connection, column_names)
if key_col and value_col:
# 3. Add/update default plugins
add_default_plugins_parameter(connection, key_col, value_col, column_names)
# 4. Verify trigger
trigger_exists = verify_trigger(connection)
# Summary
print(f"\n{'='*70}")
print("FINAL STATUS")
print('='*70)
print("Configuration complete!")
if trigger_exists:
print("[OK] Database trigger active - new agents will get Story Playback automatically")
else:
print("[INFO] No trigger - agent creation code should add default plugins")
print("\nDefault plugins configured:")
print(" - SYSTEM_PLUGIN_MUSIC")
print(" - SYSTEM_PLUGIN_STORY")
print(" - SYSTEM_PLUGIN_WEATHER")
print(" - SYSTEM_PLUGIN_NEWS_NEWSNOW")
print("\nAll new agents will now have Story Playback by default!")
finally:
connection.close()
if __name__ == "__main__":
main()

View file

@ -1,178 +0,0 @@
#!/usr/bin/env python3
"""
Script to check system parameters table for mem0.api_key
"""
import pymysql
import json
import sys
from datetime import datetime
# Database configuration - from application-dev.yml
DB_CONFIG = {
'host': 'nozomi.proxy.rlwy.net', # Railway MySQL host
'port': 25037, # Railway MySQL port
'user': 'root', # Database username
'password': 'OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm', # Database password
'database': 'railway', # Database name
'charset': 'utf8mb4',
'connect_timeout': 30, # Connection timeout in seconds
'read_timeout': 30,
'write_timeout': 30,
'autocommit': False,
'ssl': {'ssl_disabled': False} # Enable SSL as per JDBC config
}
# Colors for output
class Colors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
def print_header(text):
"""Print a formatted header"""
print(f"\n{Colors.HEADER}{'='*80}{Colors.ENDC}")
print(f"{Colors.HEADER}{text}{Colors.ENDC}")
print(f"{Colors.HEADER}{'='*80}{Colors.ENDC}")
def print_success(text):
"""Print success message"""
print(f"{Colors.OKGREEN}[OK] {text}{Colors.ENDC}")
def print_error(text):
"""Print error message"""
print(f"{Colors.FAIL}[ERROR] {text}{Colors.ENDC}")
def print_info(text):
"""Print info message"""
print(f"{Colors.OKCYAN}[INFO] {text}{Colors.ENDC}")
def print_warning(text):
"""Print warning message"""
print(f"{Colors.WARNING}[WARNING] {text}{Colors.ENDC}")
def connect_to_database():
"""Connect to the MySQL database"""
try:
print_info("Connecting to database...")
connection = pymysql.connect(**DB_CONFIG)
# Test the connection
with connection.cursor() as cursor:
cursor.execute("SELECT 1")
cursor.fetchone()
print_success("Successfully connected to database")
return connection
except Exception as e:
print_error(f"Failed to connect to database: {str(e)}")
return None
def check_system_params(connection):
"""Check system parameters table for mem0.api_key"""
try:
with connection.cursor() as cursor:
# First, let's see what tables exist
print_info("Checking available tables...")
cursor.execute("SHOW TABLES LIKE '%param%'")
param_tables = cursor.fetchall()
if param_tables:
print_success(f"Found parameter-related tables:")
for table in param_tables:
print(f" - {table[0]}")
# Try different possible table names
possible_tables = [
'sys_params',
'system_params',
'sys_parameters',
'system_parameters',
'config_params',
'application_params'
]
found_table = None
for table_name in possible_tables:
try:
cursor.execute(f"SELECT COUNT(*) FROM {table_name}")
found_table = table_name
print_success(f"Found system parameters table: {table_name}")
break
except pymysql.err.ProgrammingError:
continue
if found_table:
# First, check the table structure
cursor.execute(f"DESCRIBE {found_table}")
columns = cursor.fetchall()
print_info(f"Table structure for {found_table}:")
for col in columns:
print(f" {col[0]} ({col[1]})")
# Show all parameters for context
cursor.execute(f"SELECT * FROM {found_table} LIMIT 10")
all_params = cursor.fetchall()
print_info(f"\nFirst 10 parameters in {found_table}:")
for row in all_params:
print(f" Row: {row}")
# Try to find mem0 parameter based on actual column structure
if columns:
# Assume first column is key, second is value
key_col = columns[0][0]
query = f"SELECT * FROM {found_table} WHERE {key_col} = %s OR {key_col} LIKE %s"
cursor.execute(query, ('mem0.api_key', '%mem0%'))
results = cursor.fetchall()
if results:
print_success("Found mem0-related parameters:")
for row in results:
print(f" Row: {row}")
else:
print_warning("No mem0.api_key parameter found in system parameters")
else:
print_warning("No system parameters table found")
print_info("Available tables:")
cursor.execute("SHOW TABLES")
all_tables = cursor.fetchall()
for table in all_tables:
print(f" - {table[0]}")
except Exception as e:
print_error(f"Failed to check system parameters: {str(e)}")
def main():
"""Main function"""
print_header("System Parameters Check Script")
print_info(f"Timestamp: {datetime.now().isoformat()}")
# Connect to database
connection = connect_to_database()
if not connection:
print_error("Cannot proceed without database connection")
return 1
try:
check_system_params(connection)
finally:
connection.close()
print_info("Database connection closed")
if __name__ == "__main__":
try:
sys.exit(main())
except KeyboardInterrupt:
print("\n\nScript interrupted by user")
sys.exit(0)
except Exception as e:
print_error(f"Unexpected error: {str(e)}")
sys.exit(1)

View file

@ -1,197 +0,0 @@
#!/usr/bin/env python3
"""
Final script to fix Story Playback function placement
"""
import mysql.connector
from mysql.connector import Error
import json
def connect_to_database():
"""Connect to the Railway MySQL database"""
try:
connection = mysql.connector.connect(
host='nozomi.proxy.rlwy.net',
port=25037,
database='railway',
user='root',
password='OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm',
charset='utf8mb4',
use_unicode=True,
ssl_disabled=True
)
if connection.is_connected():
print("Successfully connected to Railway MySQL database")
return connection
except Error as e:
print(f"Error connecting to MySQL: {e}")
return None
def check_agents_and_templates(connection):
"""Check both agent templates and actual agents"""
cursor = connection.cursor()
try:
print("\n1. Checking agent templates...")
cursor.execute("SELECT id, agent_name FROM ai_agent_template")
templates = cursor.fetchall()
print(f"Found {len(templates)} agent templates:")
for template in templates:
print(f" Template ID: {template[0]}, Name: {template[1]}")
print("\n2. Checking actual agents...")
cursor.execute("SELECT id, agent_name FROM ai_agent")
agents = cursor.fetchall()
print(f"Found {len(agents)} agents:")
for agent in agents:
print(f" Agent ID: {agent[0]}, Name: {agent[1]}")
print("\n3. Checking current Story Playback mappings...")
cursor.execute("""
SELECT agent_id, param_info FROM ai_agent_plugin_mapping
WHERE plugin_id = 'SYSTEM_PLUGIN_STORY'
""")
story_mappings = cursor.fetchall()
print(f"Found {len(story_mappings)} existing Story Playback mappings:")
for mapping in story_mappings:
print(f" Agent ID: {mapping[0]}")
return agents, templates, story_mappings
except Error as e:
print(f"Error checking agents and templates: {e}")
return [], [], []
finally:
cursor.close()
def add_missing_story_playback_mappings(connection, agents, story_mappings):
"""Add Story Playback to agents that don't have it"""
cursor = connection.cursor()
try:
# Get list of agent IDs that already have Story Playback
existing_story_agent_ids = [mapping[0] for mapping in story_mappings]
# Default parameters for Story Playback plugin
param_info = {
"story_dir": "./stories",
"story_ext": ".mp3;.wav;.m4a",
"refresh_time": "300"
}
updates_made = 0
print(f"\n4. Adding Story Playback to agents without it...")
for agent_id, agent_name in agents:
if agent_id not in existing_story_agent_ids:
print(f"Adding Story Playback to: {agent_name} (ID: {agent_id})")
cursor.execute("""
INSERT INTO ai_agent_plugin_mapping
(agent_id, plugin_id, param_info)
VALUES (%s, %s, %s)
""", (agent_id, "SYSTEM_PLUGIN_STORY", json.dumps(param_info)))
updates_made += 1
print(f" Added successfully")
else:
print(f"Already has Story Playback: {agent_name} (ID: {agent_id})")
if updates_made > 0:
connection.commit()
print(f"\nCommitted {updates_made} new Story Playback mappings to database")
else:
print(f"\nNo updates needed - all agents already have Story Playback")
return updates_made
except Error as e:
print(f"Error adding Story Playback mappings: {e}")
connection.rollback()
return 0
finally:
cursor.close()
def verify_final_state(connection):
"""Verify all agents now have Story Playback"""
cursor = connection.cursor()
try:
print(f"\n5. Final verification...")
cursor.execute("""
SELECT
a.id,
a.agent_name,
CASE WHEN apm.plugin_id IS NOT NULL THEN 'YES' ELSE 'NO' END as has_story_playback
FROM ai_agent a
LEFT JOIN ai_agent_plugin_mapping apm
ON a.id = apm.agent_id AND apm.plugin_id = 'SYSTEM_PLUGIN_STORY'
ORDER BY a.agent_name
""")
results = cursor.fetchall()
total_agents = len(results)
with_story_playback = sum(1 for result in results if result[2] == 'YES')
print(f"\nFinal Story Playback status:")
for result in results:
agent_id, agent_name, has_playback = result
status_symbol = "[YES]" if has_playback == 'YES' else "[NO] "
print(f" {status_symbol} {agent_name}")
print(f"\nSUMMARY:")
print(f"Total agents: {total_agents}")
print(f"With Story Playback: {with_story_playback}")
if with_story_playback == total_agents:
print("SUCCESS: All agents now have Story Playback function!")
else:
print(f"WARNING: {total_agents - with_story_playback} agents still missing Story Playback")
return with_story_playback == total_agents
except Error as e:
print(f"Error verifying final state: {e}")
return False
finally:
cursor.close()
def main():
print("Fixing Story Playback function for all agents")
print("=" * 50)
connection = connect_to_database()
if not connection:
return
try:
# Check current state
agents, templates, story_mappings = check_agents_and_templates(connection)
if not agents:
print("ERROR: No agents found in database!")
return
# Add Story Playback to agents that don't have it
updates_made = add_missing_story_playback_mappings(connection, agents, story_mappings)
# Verify the final state
success = verify_final_state(connection)
if success:
print("\nMission accomplished! All agents now have access to Story Playback function.")
else:
print("\nSome issues remain. Please check the output above.")
finally:
if connection.is_connected():
connection.close()
print(f"\nDatabase connection closed")
if __name__ == "__main__":
main()

View file

@ -1,366 +0,0 @@
#!/usr/bin/env python3
"""
Script to ensure play_story is included in default agent template
"""
import mysql.connector
from mysql.connector import Error
import json
def connect_to_database():
"""Connect to the Railway MySQL database"""
try:
connection = mysql.connector.connect(
host='nozomi.proxy.rlwy.net',
port=25037,
database='railway',
user='root',
password='OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm',
charset='utf8mb4',
use_unicode=True,
ssl_disabled=True
)
if connection.is_connected():
print("Connected to Railway MySQL database")
return connection
except Error as e:
print(f"Database connection error: {e}")
return None
def check_agent_templates(connection):
"""Check all agent templates and their plugin configurations"""
cursor = connection.cursor()
try:
print("\n1. Checking Agent Templates...")
print("=" * 50)
# Get all agent templates
cursor.execute("""
SELECT id, agent_name, agent_code
FROM ai_agent_template
ORDER BY sort, id
""")
templates = cursor.fetchall()
print(f"Found {len(templates)} agent templates:")
for template_id, agent_name, agent_code in templates:
print(f" - {agent_name or agent_code} (ID: {template_id})")
return templates
except Error as e:
print(f"Error checking templates: {e}")
return []
finally:
cursor.close()
def check_template_plugin_mappings(connection):
"""Check if templates have default plugin mappings"""
cursor = connection.cursor()
try:
print("\n2. Checking Template Plugin Mappings...")
print("=" * 50)
# Check if there's a template plugin mapping table
cursor.execute("""
SELECT TABLE_NAME
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = 'railway'
AND TABLE_NAME LIKE '%template%plugin%'
""")
mapping_tables = cursor.fetchall()
if mapping_tables:
print("Found template plugin mapping tables:")
for table in mapping_tables:
print(f" - {table[0]}")
else:
print("No template plugin mapping tables found")
print("Templates likely don't have default plugin configurations")
print("Plugins are probably added when agents are created from templates")
return mapping_tables
except Error as e:
print(f"Error checking template mappings: {e}")
return []
finally:
cursor.close()
def add_story_to_all_templates(connection):
"""Ensure all templates will include play_story for new agents"""
cursor = connection.cursor()
try:
print("\n3. Adding Story Playback to All Templates...")
print("=" * 50)
# Get all templates
cursor.execute("SELECT id, agent_name FROM ai_agent_template")
templates = cursor.fetchall()
# For each template, we need to ensure Story Playback is included
# Since templates don't have direct plugin mappings, we need to check
# if there's a default plugin list or configuration
# Check if there's a system parameter for default plugins
cursor.execute("""
SELECT param_key, param_value
FROM sys_params
WHERE param_key LIKE '%plugin%' OR param_key LIKE '%function%'
""")
system_params = cursor.fetchall()
if system_params:
print("Found system parameters related to plugins:")
for key, value in system_params:
print(f" {key}: {value[:100] if value else 'NULL'}...")
# Check if this parameter contains plugin defaults
if 'default' in key.lower() and 'plugin' in key.lower():
try:
if value and value.startswith('['):
plugins = json.loads(value)
if 'SYSTEM_PLUGIN_STORY' not in plugins:
plugins.append('SYSTEM_PLUGIN_STORY')
cursor.execute("""
UPDATE sys_params
SET param_value = %s
WHERE param_key = %s
""", (json.dumps(plugins), key))
print(f" Updated {key} to include SYSTEM_PLUGIN_STORY")
except:
pass
# Add a new system parameter for default plugins if it doesn't exist
cursor.execute("""
SELECT param_key FROM sys_params
WHERE param_key = 'default_agent_plugins'
""")
if not cursor.fetchone():
print("\nAdding default_agent_plugins system parameter...")
default_plugins = [
"SYSTEM_PLUGIN_MUSIC",
"SYSTEM_PLUGIN_STORY",
"SYSTEM_PLUGIN_WEATHER",
"SYSTEM_PLUGIN_NEWS_NEWSNOW"
]
cursor.execute("""
INSERT INTO sys_params (param_key, param_value, param_type, remark, creator, create_date, updater, update_date)
VALUES (%s, %s, %s, %s, 0, NOW(), 0, NOW())
""", (
'default_agent_plugins',
json.dumps(default_plugins),
1, # Type 1 for system parameter
'Default plugins for new agents'
))
print("Added default_agent_plugins with Story Playback included")
connection.commit()
else:
# Update existing parameter
cursor.execute("""
SELECT param_value FROM sys_params
WHERE param_key = 'default_agent_plugins'
""")
current_value = cursor.fetchone()[0]
if current_value:
try:
plugins = json.loads(current_value)
if 'SYSTEM_PLUGIN_STORY' not in plugins:
plugins.append('SYSTEM_PLUGIN_STORY')
cursor.execute("""
UPDATE sys_params
SET param_value = %s, update_date = NOW()
WHERE param_key = 'default_agent_plugins'
""", (json.dumps(plugins),))
print("Updated default_agent_plugins to include SYSTEM_PLUGIN_STORY")
connection.commit()
else:
print("SYSTEM_PLUGIN_STORY already in default_agent_plugins")
except Exception as e:
print(f"Error updating default plugins: {e}")
return True
except Error as e:
print(f"Error adding story to templates: {e}")
connection.rollback()
return False
finally:
cursor.close()
def ensure_template_story_mappings(connection):
"""Ensure all agent templates have Story Playback in their configuration"""
cursor = connection.cursor()
try:
print("\n4. Ensuring Template Configurations Include Story...")
print("=" * 50)
# Since templates don't have direct plugin mappings,
# we need to ensure the agent creation process includes Story Playback
# Check if there's an agent_template_plugin table or similar
cursor.execute("""
SHOW TABLES LIKE '%agent_template%'
""")
template_tables = cursor.fetchall()
print(f"Template-related tables found: {len(template_tables)}")
for table in template_tables:
print(f" - {table[0]}")
# The key is to ensure that when an agent is created from a template,
# it automatically gets the Story Playback plugin
# Check for any stored procedures or triggers that create agents
cursor.execute("""
SELECT ROUTINE_NAME, ROUTINE_TYPE
FROM information_schema.ROUTINES
WHERE ROUTINE_SCHEMA = 'railway'
AND (ROUTINE_NAME LIKE '%agent%' OR ROUTINE_NAME LIKE '%create%')
""")
procedures = cursor.fetchall()
if procedures:
print("\nFound stored procedures/functions related to agents:")
for proc_name, proc_type in procedures:
print(f" - {proc_type}: {proc_name}")
return True
except Error as e:
print(f"Error ensuring template mappings: {e}")
return False
finally:
cursor.close()
def create_trigger_for_new_agents(connection):
"""Create a trigger to automatically add Story Playback to new agents"""
cursor = connection.cursor()
try:
print("\n5. Creating Trigger for New Agents...")
print("=" * 50)
# Drop existing trigger if it exists
cursor.execute("DROP TRIGGER IF EXISTS add_story_to_new_agent")
# Create trigger to automatically add Story Playback when a new agent is created
trigger_sql = """
CREATE TRIGGER add_story_to_new_agent
AFTER INSERT ON ai_agent
FOR EACH ROW
BEGIN
-- Add Story Playback plugin to new agent
IF NOT EXISTS (
SELECT 1 FROM ai_agent_plugin_mapping
WHERE agent_id = NEW.id
AND plugin_id = 'SYSTEM_PLUGIN_STORY'
) THEN
INSERT INTO ai_agent_plugin_mapping (agent_id, plugin_id, param_info)
VALUES (
NEW.id,
'SYSTEM_PLUGIN_STORY',
'{"story_dir": "./stories", "story_ext": ".mp3;.wav;.m4a", "refresh_time": "300"}'
);
END IF;
-- Also add other default plugins
IF NOT EXISTS (
SELECT 1 FROM ai_agent_plugin_mapping
WHERE agent_id = NEW.id
AND plugin_id = 'SYSTEM_PLUGIN_MUSIC'
) THEN
INSERT INTO ai_agent_plugin_mapping (agent_id, plugin_id, param_info)
VALUES (NEW.id, 'SYSTEM_PLUGIN_MUSIC', '{}');
END IF;
IF NOT EXISTS (
SELECT 1 FROM ai_agent_plugin_mapping
WHERE agent_id = NEW.id
AND plugin_id = 'SYSTEM_PLUGIN_WEATHER'
) THEN
INSERT INTO ai_agent_plugin_mapping (agent_id, plugin_id, param_info)
VALUES (NEW.id, 'SYSTEM_PLUGIN_WEATHER', '{"api_key": "12dd0eea5789636262549c9ec7f4f7d8", "default_location": "Bangalore", "units": "metric", "lang": "en"}');
END IF;
END
"""
try:
cursor.execute(trigger_sql)
print("Created trigger to automatically add Story Playback to new agents!")
connection.commit()
return True
except Error as e:
if "This version of MySQL doesn't yet support" in str(e):
print("Database doesn't support this trigger syntax")
print("Will use alternative method...")
return False
else:
print(f"Error creating trigger: {e}")
return False
except Error as e:
print(f"Error with trigger creation: {e}")
return False
finally:
cursor.close()
def main():
print("Fixing Default Agent Template for Story Playback")
print("=" * 70)
connection = connect_to_database()
if not connection:
return
try:
# 1. Check existing templates
templates = check_agent_templates(connection)
# 2. Check template plugin mappings
check_template_plugin_mappings(connection)
# 3. Add story to templates
add_story_to_all_templates(connection)
# 4. Ensure template configurations
ensure_template_story_mappings(connection)
# 5. Try to create trigger (may not work on all MySQL versions)
trigger_created = create_trigger_for_new_agents(connection)
# Summary
print(f"\n{'='*70}")
print("SUMMARY")
print('='*70)
print("Actions taken:")
print("1. Checked all agent templates")
print("2. Added default_agent_plugins system parameter with Story Playback")
print("3. Ensured Story Playback is in default plugin list")
if trigger_created:
print("4. Created database trigger for automatic Story Playback addition")
else:
print("4. Trigger creation failed (database limitation)")
print(" New agents will need Story Playback added by the application")
print("\nRECOMMENDATION:")
print("To ensure all new agents have Story Playback, the agent creation")
print("process in the manager-api should be updated to automatically")
print("include SYSTEM_PLUGIN_STORY in the plugin mappings.")
finally:
connection.close()
if __name__ == "__main__":
main()

View file

@ -1,265 +0,0 @@
#!/usr/bin/env python3
"""
Fix Intent function configuration to include play_story
"""
import mysql.connector
from mysql.connector import Error
import json
def connect_to_database():
"""Connect to the Railway MySQL database"""
try:
connection = mysql.connector.connect(
host='nozomi.proxy.rlwy.net',
port=25037,
database='railway',
user='root',
password='OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm',
charset='utf8mb4',
use_unicode=True,
ssl_disabled=True
)
if connection.is_connected():
print("Connected to Railway MySQL database")
return connection
except Error as e:
print(f"Database connection error: {e}")
return None
def check_and_fix_intent_config(connection):
"""Check and fix Intent function configuration"""
cursor = connection.cursor()
try:
# Get current Intent configuration
cursor.execute("""
SELECT id, fields
FROM ai_model_provider
WHERE model_type = 'Intent' AND provider_code = 'function_call'
LIMIT 1
""")
result = cursor.fetchone()
if not result:
print("ERROR: Intent function call configuration not found!")
return False
config_id, fields = result
print(f"Found Intent config: {config_id}")
try:
fields_json = json.loads(fields)
print(f"Current fields count: {len(fields_json)}")
# Check if functions field exists
functions_field_exists = False
for field in fields_json:
if field.get('key') == 'functions':
functions_field_exists = True
current_functions = field.get('default', '')
print(f"Current functions: {current_functions}")
if 'play_story' in current_functions.lower():
print("play_story already exists in functions!")
return True
break
if not functions_field_exists:
print("Functions field missing! Adding it...")
# Add functions field with all necessary functions
functions_field = {
"key": "functions",
"type": "array",
"label": "Functions",
"default": "play_music;play_story;get_weather;get_indian_news_api;get_news_from_newsnow;get_lunar"
}
fields_json.append(functions_field)
else:
print("Adding play_story to existing functions...")
for i, field in enumerate(fields_json):
if field.get('key') == 'functions':
current_functions = field.get('default', '')
if current_functions and not current_functions.endswith(';'):
updated_functions = current_functions + ';play_story'
elif current_functions:
updated_functions = current_functions + 'play_story'
else:
updated_functions = 'play_story;play_music;get_weather;get_indian_news_api;get_news_from_newsnow;get_lunar'
fields_json[i]['default'] = updated_functions
print(f"Updated functions to: {updated_functions}")
break
# Update database
cursor.execute("""
UPDATE ai_model_provider
SET fields = %s
WHERE id = %s
""", (json.dumps(fields_json), config_id))
connection.commit()
print("SUCCESS: Intent configuration updated!")
return True
except json.JSONDecodeError as e:
print(f"JSON parsing error: {e}")
return False
except Error as e:
print(f"Database error: {e}")
connection.rollback()
return False
finally:
cursor.close()
def add_story_to_missing_agents(connection):
"""Add Story Playback to agents that don't have it"""
cursor = connection.cursor()
try:
# Get agents without Story Playback
cursor.execute("""
SELECT a.id, a.agent_name
FROM ai_agent a
LEFT JOIN ai_agent_plugin_mapping apm
ON a.id = apm.agent_id AND apm.plugin_id = 'SYSTEM_PLUGIN_STORY'
WHERE apm.plugin_id IS NULL
""")
missing_agents = cursor.fetchall()
if not missing_agents:
print("All agents already have Story Playback!")
return True
print(f"Adding Story Playback to {len(missing_agents)} agents...")
# Default Story Playback parameters
param_info = {
"story_dir": "./stories",
"story_ext": ".mp3;.wav;.m4a",
"refresh_time": "300"
}
success_count = 0
for agent_id, agent_name in missing_agents:
try:
cursor.execute("""
INSERT INTO ai_agent_plugin_mapping
(agent_id, plugin_id, param_info)
VALUES (%s, %s, %s)
""", (agent_id, "SYSTEM_PLUGIN_STORY", json.dumps(param_info)))
print(f"Added Story Playback to: {agent_name}")
success_count += 1
except Error as e:
print(f"Failed to add to {agent_name}: {e}")
connection.commit()
print(f"SUCCESS: Added Story Playback to {success_count} agents!")
return True
except Error as e:
print(f"Error adding Story Playback to agents: {e}")
connection.rollback()
return False
finally:
cursor.close()
def verify_final_state(connection):
"""Verify everything is working"""
cursor = connection.cursor()
try:
# Check Intent functions
cursor.execute("""
SELECT fields
FROM ai_model_provider
WHERE model_type = 'Intent' AND provider_code = 'function_call'
LIMIT 1
""")
result = cursor.fetchone()
if result:
fields_json = json.loads(result[0])
for field in fields_json:
if field.get('key') == 'functions':
functions = field.get('default', '')
print(f"Final Intent functions: {functions}")
break
# Check agent count
cursor.execute("""
SELECT
COUNT(*) as total_agents,
SUM(CASE WHEN apm.plugin_id IS NOT NULL THEN 1 ELSE 0 END) as agents_with_story
FROM ai_agent a
LEFT JOIN ai_agent_plugin_mapping apm
ON a.id = apm.agent_id AND apm.plugin_id = 'SYSTEM_PLUGIN_STORY'
""")
total, with_story = cursor.fetchone()
print(f"Final state: {with_story}/{total} agents have Story Playback")
if with_story == total:
print("SUCCESS: All agents now have Story Playback!")
return True
else:
print(f"WARNING: {total - with_story} agents still missing Story Playback")
return False
except Error as e:
print(f"Error verifying final state: {e}")
return False
finally:
cursor.close()
def main():
print("Fixing Story Playback Function Configuration")
print("=" * 50)
connection = connect_to_database()
if not connection:
return
try:
# 1. Fix Intent configuration
print("\n1. Fixing Intent Function Configuration...")
intent_fixed = check_and_fix_intent_config(connection)
# 2. Add Story Playback to missing agents
print("\n2. Adding Story Playback to Missing Agents...")
agents_fixed = add_story_to_missing_agents(connection)
# 3. Verify final state
print("\n3. Verifying Final State...")
final_ok = verify_final_state(connection)
# Summary
print(f"\n{'='*50}")
print("FINAL RESULT")
print('='*50)
if intent_fixed:
print("Intent configuration: FIXED")
else:
print("Intent configuration: FAILED")
if agents_fixed:
print("Agent mappings: FIXED")
else:
print("Agent mappings: FAILED")
if final_ok:
print("Overall status: SUCCESS - Story Playback ready!")
else:
print("Overall status: PARTIAL - Some issues remain")
finally:
connection.close()
if __name__ == "__main__":
main()

View file

@ -1,67 +0,0 @@
-- Clear Liquibase lock and failed changesets
DELETE FROM DATABASECHANGELOGLOCK WHERE ID = 1;
-- Mark the failed changeset as already executed (skip it)
INSERT INTO DATABASECHANGELOG (ID, AUTHOR, FILENAME, DATEEXECUTED, ORDEREXECUTED, EXECTYPE, MD5SUM, DESCRIPTION, COMMENTS, TAG, LIQUIBASE, CONTEXTS, LABELS, DEPLOYMENT_ID)
SELECT '202501230004_translate_model_names', 'cheeko', 'db/changelog/db.changelog-master.yaml', NOW(),
(SELECT COALESCE(MAX(ORDEREXECUTED), 0) + 1 FROM DATABASECHANGELOG d), 'EXECUTED', 'placeholder',
'Manual fix for column name issue', 'Manually fixed', NULL, '4.20.0', NULL, NULL,
CONCAT(UNIX_TIMESTAMP(NOW()), '000')
WHERE NOT EXISTS (
SELECT 1 FROM DATABASECHANGELOG
WHERE ID = '202501230004_translate_model_names'
AND AUTHOR = 'cheeko'
AND FILENAME = 'db/changelog/db.changelog-master.yaml'
);
-- Apply the translations manually with correct column names
UPDATE ai_model_provider SET name = 'SileroVAD Voice Activity Detection' WHERE name = 'SileroVAD语音活动检测';
UPDATE ai_model_provider SET name = 'FunASR Speech Recognition' WHERE name = 'FunASR语音识别';
UPDATE ai_model_provider SET name = 'SherpaASR Speech Recognition' WHERE name = 'SherpaASR语音识别';
UPDATE ai_model_provider SET name = 'Volcano Engine Speech Recognition' WHERE name = '火山引擎语音识别';
UPDATE ai_model_provider SET name = 'Tencent Speech Recognition' WHERE name = '腾讯语音识别';
UPDATE ai_model_provider SET name = 'Tencent Speech Synthesis' WHERE name = '腾讯语音合成';
UPDATE ai_model_provider SET name = 'Alibaba Cloud Speech Recognition' WHERE name = '阿里云语音识别';
UPDATE ai_model_provider SET name = 'Alibaba Cloud Speech Recognition (Streaming)' WHERE name = '阿里云语音识别(流式)';
UPDATE ai_model_provider SET name = 'Baidu Speech Recognition' WHERE name = '百度语音识别';
UPDATE ai_model_provider SET name = 'OpenAI Speech Recognition' WHERE name = 'OpenAI语音识别';
UPDATE ai_model_provider SET name = 'Volcano Engine Speech Recognition (Streaming)' WHERE name = '火山引擎语音识别(流式)';
UPDATE ai_model_provider SET name = 'Alibaba Bailian Interface' WHERE name = '阿里百炼接口';
UPDATE ai_model_provider SET name = 'Volcano Engine LLM' WHERE name = '火山引擎LLM';
UPDATE ai_model_provider SET name = 'Volcano Engine TTS' WHERE name = '火山引擎TTS';
UPDATE ai_model_provider SET name = 'Alibaba Cloud TTS' WHERE name = '阿里云TTS';
UPDATE ai_model_provider SET name = 'Volcano Dual-Stream Speech Synthesis' WHERE name = '火山双流式语音合成';
UPDATE ai_model_provider SET name = 'Linkerai Speech Synthesis' WHERE name = 'Linkerai语音合成';
UPDATE ai_model_provider SET name = 'Alibaba Cloud Speech Synthesis (Streaming)' WHERE name = '阿里云语音合成(流式)';
UPDATE ai_model_provider SET name = 'Index-TTS-vLLM Streaming Speech Synthesis' WHERE name = 'Index-TTS-vLLM流式语音合成';
UPDATE ai_model_provider SET name = 'Mem0AI Memory' WHERE name = 'Mem0AI记忆';
UPDATE ai_model_provider SET name = 'No Memory' WHERE name = '无记忆';
UPDATE ai_model_provider SET name = 'Local Short Memory' WHERE name = '本地短记忆';
UPDATE ai_model_provider SET name = 'No Intent Recognition' WHERE name = '无意图识别';
UPDATE ai_model_provider SET name = 'LLM Intent Recognition' WHERE name = 'LLM意图识别';
UPDATE ai_model_provider SET name = 'Function Call Intent Recognition' WHERE name = '函数调用意图识别';
UPDATE ai_model_provider SET name = 'FunASR Server Speech Recognition' WHERE name = 'FunASR服务语音识别';
UPDATE ai_model_provider SET name = 'MiniMax Speech Synthesis' WHERE name = 'MiniMax语音合成';
UPDATE ai_model_provider SET name = 'OpenAI Speech Synthesis' WHERE name = 'OpenAI语音合成';
-- Update model config names
UPDATE ai_model_config SET model_name = 'Zhipu AI' WHERE model_name = '智谱AI';
UPDATE ai_model_config SET model_name = 'Tongyi Qianwen' WHERE model_name = '通义千问';
UPDATE ai_model_config SET model_name = 'Tongyi Bailian' WHERE model_name = '通义百炼';
UPDATE ai_model_config SET model_name = 'Doubao Large Model' WHERE model_name = '豆包大模型';
UPDATE ai_model_config SET model_name = 'Google Gemini' WHERE model_name = '谷歌Gemini';
UPDATE ai_model_config SET model_name = 'Tencent Speech Recognition' WHERE model_name = '腾讯语音识别';
UPDATE ai_model_config SET model_name = 'Alibaba Cloud Speech Recognition' WHERE model_name = '阿里云语音识别';
UPDATE ai_model_config SET model_name = 'Baidu Speech Recognition' WHERE model_name = '百度语音识别';
UPDATE ai_model_config SET model_name = 'MiniMax Speech Synthesis' WHERE model_name = 'MiniMax语音合成';
UPDATE ai_model_config SET model_name = 'OpenAI Speech Synthesis' WHERE model_name = 'OpenAI语音合成';
UPDATE ai_model_config SET model_name = 'Volcano Dual-Stream Speech Synthesis' WHERE model_name = '火山双流式语音合成';
UPDATE ai_model_config SET model_name = 'Linkerai Speech Synthesis' WHERE model_name = 'Linkerai语音合成';
UPDATE ai_model_config SET model_name = 'Mem0AI Memory' WHERE model_name = 'Mem0AI记忆';
UPDATE ai_model_config SET model_name = 'Function Call Intent Recognition' WHERE model_name = '函数调用意图识别';
UPDATE ai_model_config SET model_name = 'Zhipu Visual AI' WHERE model_name = '智谱视觉AI';
UPDATE ai_model_config SET model_name = 'Qianwen Visual Model' WHERE model_name = '千问视觉模型';
UPDATE ai_model_config SET model_name = 'Volcano Edge Large Model Gateway' WHERE model_name = '火山引擎边缘大模型网关';
-- Update TTS voice names (correct column name)
UPDATE ai_tts_voice SET name = 'Alibaba Cloud Xiaoyun' WHERE name = '阿里云小云';

View file

@ -1,270 +0,0 @@
#!/usr/bin/env python3
"""
Script to fix Story Playback function placement in agent templates
"""
import mysql.connector
from mysql.connector import Error
import json
from tabulate import tabulate
def connect_to_database():
"""Connect to the Railway MySQL database"""
try:
connection = mysql.connector.connect(
host='nozomi.proxy.rlwy.net',
port=25037,
database='railway',
user='root',
password='OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm',
charset='utf8mb4',
use_unicode=True,
ssl_disabled=True
)
if connection.is_connected():
print("Successfully connected to Railway MySQL database")
return connection
except Error as e:
print(f"Error connecting to MySQL: {e}")
return None
def examine_ai_agent_template(connection):
"""Examine the ai_agent_template table"""
cursor = connection.cursor()
try:
print(f"\n{'='*60}")
print("Structure of ai_agent_template table:")
print('='*60)
cursor.execute("DESCRIBE ai_agent_template")
columns = cursor.fetchall()
headers = ["Field", "Type", "Null", "Key", "Default", "Extra"]
print(tabulate(columns, headers=headers, tablefmt="grid"))
# Get all records
cursor.execute("SELECT * FROM ai_agent_template")
templates = cursor.fetchall()
column_names = [desc[0] for desc in cursor.description]
print(f"\nFound {len(templates)} agent templates:")
for i, template in enumerate(templates):
template_dict = dict(zip(column_names, template))
print(f"\n--- Template {i+1} ---")
print(f"ID: {template_dict.get('id')}")
print(f"Template Name: {template_dict.get('template_name', template_dict.get('name'))}")
# Look for JSON fields that might contain function configurations
for col_name, cell_value in template_dict.items():
if isinstance(cell_value, str) and cell_value.strip().startswith('{'):
try:
json_data = json.loads(cell_value)
print(f"\nJSON field '{col_name}':")
# Check if it contains function configurations
if any(key in json_data for key in ['selected_functions', 'unselected_functions', 'functions', 'selectedFunctions', 'unselectedFunctions', 'plugins']):
print(f" Contains function/plugin configuration:")
print(json.dumps(json_data, indent=4))
else:
# Just show the structure
print(f" Keys: {list(json_data.keys())}")
except json.JSONDecodeError:
if len(str(cell_value)) > 100:
print(f" {col_name}: [Long text content, first 100 chars]: {str(cell_value)[:100]}...")
else:
print(f" {col_name}: {cell_value}")
elif cell_value is not None:
if len(str(cell_value)) > 100:
print(f" {col_name}: [Long content]: {str(cell_value)[:100]}...")
else:
print(f" {col_name}: {cell_value}")
return templates, column_names
except Error as e:
print(f"Error examining ai_agent_template: {e}")
return None, None
finally:
cursor.close()
def check_ai_agent_plugin_mapping(connection):
"""Check the ai_agent_plugin_mapping table"""
cursor = connection.cursor()
try:
print(f"\n{'='*60}")
print("ai_agent_plugin_mapping table:")
print('='*60)
cursor.execute("DESCRIBE ai_agent_plugin_mapping")
columns = cursor.fetchall()
headers = ["Field", "Type", "Null", "Key", "Default", "Extra"]
print(tabulate(columns, headers=headers, tablefmt="grid"))
# Get all records
cursor.execute("SELECT * FROM ai_agent_plugin_mapping")
mappings = cursor.fetchall()
column_names = [desc[0] for desc in cursor.description]
if mappings:
print(f"\nPlugin mappings:")
print(tabulate(mappings, headers=column_names, tablefmt="grid"))
else:
print("\nNo plugin mappings found")
return mappings, column_names
except Error as e:
print(f"Error examining ai_agent_plugin_mapping: {e}")
return None, None
finally:
cursor.close()
def fix_story_playback_in_templates(connection):
"""Fix Story Playback function to be in selected functions for all agent templates"""
cursor = connection.cursor()
try:
print(f"\n{'='*60}")
print("Fixing Story Playback function placement...")
print('='*60)
# Get all agent templates
cursor.execute("SELECT * FROM ai_agent_template")
templates = cursor.fetchall()
column_names = [desc[0] for desc in cursor.description]
story_playback_plugin_id = "SYSTEM_PLUGIN_STORY"
updates_made = 0
for template in templates:
template_dict = dict(zip(column_names, template))
template_id = template_dict.get('id')
template_name = template_dict.get('template_name', template_dict.get('name', 'Unknown'))
print(f"\nProcessing template: {template_name} (ID: {template_id})")
# Check if this template already has the Story Playback plugin mapped
cursor.execute("""
SELECT * FROM ai_agent_plugin_mapping
WHERE template_id = %s AND plugin_id = %s
""", (template_id, story_playback_plugin_id))
existing_mapping = cursor.fetchone()
if existing_mapping:
mapping_dict = dict(zip([desc[0] for desc in cursor.description], existing_mapping))
current_status = mapping_dict.get('status', 0)
print(f" Found existing mapping with status: {current_status}")
if current_status != 1: # 1 = selected/enabled, 0 = unselected/disabled
# Update the mapping to enable the plugin
cursor.execute("""
UPDATE ai_agent_plugin_mapping
SET status = 1, update_date = NOW(), updater = 0
WHERE template_id = %s AND plugin_id = %s
""", (template_id, story_playback_plugin_id))
print(f" ✓ Updated Story Playback status from {current_status} to 1 (selected)")
updates_made += 1
else:
print(f" ✓ Story Playback already selected for this template")
else:
# Create new mapping with status = 1 (selected)
cursor.execute("""
INSERT INTO ai_agent_plugin_mapping
(template_id, plugin_id, status, sort, creator, create_date, updater, update_date)
VALUES (%s, %s, 1, 0, 0, NOW(), 0, NOW())
""", (template_id, story_playback_plugin_id))
print(f" ✓ Created new mapping with Story Playback selected")
updates_made += 1
connection.commit()
print(f"\n{'='*60}")
print(f"Fix completed! Made {updates_made} updates to ensure Story Playback is selected for all agent templates.")
print('='*60)
except Error as e:
print(f"Error fixing Story Playback function: {e}")
connection.rollback()
finally:
cursor.close()
def verify_fix(connection):
"""Verify that Story Playback is now selected for all templates"""
cursor = connection.cursor()
try:
print(f"\n{'='*60}")
print("Verifying fix...")
print('='*60)
cursor.execute("""
SELECT
at.id as template_id,
at.template_name,
apm.plugin_id,
apm.status,
amp.name as plugin_name
FROM ai_agent_template at
LEFT JOIN ai_agent_plugin_mapping apm ON at.id = apm.template_id AND apm.plugin_id = 'SYSTEM_PLUGIN_STORY'
LEFT JOIN ai_model_provider amp ON apm.plugin_id = amp.id
ORDER BY at.template_name
""")
results = cursor.fetchall()
column_names = [desc[0] for desc in cursor.description]
print(f"\nStory Playback status for all templates:")
print(tabulate(results, headers=column_names, tablefmt="grid"))
# Count how many are selected
selected_count = sum(1 for result in results if result[3] == 1) # status column
total_templates = len([r for r in results if r[0] is not None]) # templates with non-null id
print(f"\nSummary:")
print(f"Total templates: {total_templates}")
print(f"Templates with Story Playback selected: {selected_count}")
if selected_count == total_templates:
print("✅ SUCCESS: Story Playback is now selected for ALL agent templates!")
else:
print(f"⚠️ WARNING: {total_templates - selected_count} templates still don't have Story Playback selected")
except Error as e:
print(f"Error verifying fix: {e}")
finally:
cursor.close()
def main():
print("Fixing Story Playback function placement in xiaozhi database")
print("=" * 70)
# Connect to database
connection = connect_to_database()
if not connection:
return
try:
# Examine agent template structure
examine_ai_agent_template(connection)
# Check plugin mapping table
check_ai_agent_plugin_mapping(connection)
# Fix Story Playback placement
fix_story_playback_in_templates(connection)
# Verify the fix
verify_fix(connection)
finally:
if connection.is_connected():
connection.close()
print(f"\nMySQL connection closed")
if __name__ == "__main__":
main()

View file

@ -1,293 +0,0 @@
#!/usr/bin/env python3
"""
Fix the trigger and ensure Story Playback is added to ALL new agents
"""
import mysql.connector
from mysql.connector import Error
import json
def connect_to_database():
"""Connect to the Railway MySQL database"""
try:
connection = mysql.connector.connect(
host='nozomi.proxy.rlwy.net',
port=25037,
database='railway',
user='root',
password='OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm',
charset='utf8mb4',
use_unicode=True,
ssl_disabled=True
)
if connection.is_connected():
print("Connected to Railway MySQL database")
return connection
except Error as e:
print(f"Database connection error: {e}")
return None
def check_latest_agent(connection):
"""Check the latest agent that was just created"""
cursor = connection.cursor()
try:
print("\n1. Checking Latest Agent...")
print("=" * 60)
# Get the most recent agent
cursor.execute("""
SELECT
a.id,
a.agent_name,
a.agent_code,
a.created_at,
GROUP_CONCAT(apm.plugin_id) as plugins
FROM ai_agent a
LEFT JOIN ai_agent_plugin_mapping apm ON a.id = apm.agent_id
WHERE a.agent_name = 'test' OR a.agent_code LIKE 'AGT_1756545169%'
GROUP BY a.id, a.agent_name, a.agent_code, a.created_at
ORDER BY a.created_at DESC
LIMIT 1
""")
result = cursor.fetchone()
if result:
agent_id, name, code, created, plugins = result
print(f"Latest agent: {name} (ID: {agent_id[:16]}...)")
print(f"Code: {code}")
print(f"Created: {created}")
print(f"Plugins: {plugins}")
if plugins and 'SYSTEM_PLUGIN_STORY' not in plugins:
print("\n[!] Story Playback is MISSING! Adding it now...")
# Add Story Playback
param_info = {
"story_dir": "./stories",
"story_ext": ".mp3;.wav;.m4a",
"refresh_time": "300"
}
cursor.execute("""
INSERT INTO ai_agent_plugin_mapping
(agent_id, plugin_id, param_info)
VALUES (%s, %s, %s)
""", (agent_id, "SYSTEM_PLUGIN_STORY", json.dumps(param_info)))
connection.commit()
print("[FIXED] Added Story Playback to latest agent!")
return agent_id
elif plugins and 'SYSTEM_PLUGIN_STORY' in plugins:
print("[OK] Story Playback already present!")
return agent_id
else:
print("No agent found with name 'test'")
return None
except Error as e:
print(f"Error checking latest agent: {e}")
return None
finally:
cursor.close()
def drop_and_recreate_trigger(connection):
"""Drop the old trigger and create a better one"""
cursor = connection.cursor()
try:
print("\n2. Recreating Database Trigger...")
print("=" * 60)
# Drop existing trigger
cursor.execute("DROP TRIGGER IF EXISTS add_story_to_new_agent")
print("Dropped old trigger")
# Create new trigger that works after INSERT
# Using simpler syntax that should work on more MySQL versions
trigger_sql = """
CREATE TRIGGER add_story_to_new_agent
AFTER INSERT ON ai_agent
FOR EACH ROW
BEGIN
INSERT IGNORE INTO ai_agent_plugin_mapping (agent_id, plugin_id, param_info)
VALUES (NEW.id, 'SYSTEM_PLUGIN_STORY', '{"story_dir": "./stories", "story_ext": ".mp3;.wav;.m4a", "refresh_time": "300"}');
END
"""
cursor.execute(trigger_sql)
connection.commit()
print("Created new trigger successfully!")
return True
except Error as e:
print(f"Trigger creation failed: {e}")
# Try alternative approach - stored procedure
try:
print("\nTrying stored procedure approach...")
cursor.execute("DROP PROCEDURE IF EXISTS add_default_plugins")
proc_sql = """
CREATE PROCEDURE add_default_plugins(IN agent_id VARCHAR(32))
BEGIN
INSERT IGNORE INTO ai_agent_plugin_mapping (agent_id, plugin_id, param_info)
VALUES (agent_id, 'SYSTEM_PLUGIN_STORY', '{"story_dir": "./stories", "story_ext": ".mp3;.wav;.m4a", "refresh_time": "300"}');
END
"""
cursor.execute(proc_sql)
connection.commit()
print("Created stored procedure as alternative!")
return True
except Error as e2:
print(f"Stored procedure also failed: {e2}")
return False
finally:
cursor.close()
def ensure_all_agents_have_story(connection):
"""Make sure ALL agents have Story Playback"""
cursor = connection.cursor()
try:
print("\n3. Ensuring ALL Agents Have Story Playback...")
print("=" * 60)
# Find agents without Story Playback
cursor.execute("""
SELECT a.id, a.agent_name
FROM ai_agent a
LEFT JOIN ai_agent_plugin_mapping apm
ON a.id = apm.agent_id AND apm.plugin_id = 'SYSTEM_PLUGIN_STORY'
WHERE apm.plugin_id IS NULL
""")
agents_without_story = cursor.fetchall()
if agents_without_story:
print(f"Found {len(agents_without_story)} agents without Story Playback:")
param_info = {
"story_dir": "./stories",
"story_ext": ".mp3;.wav;.m4a",
"refresh_time": "300"
}
for agent_id, agent_name in agents_without_story:
print(f" Adding to: {agent_name}")
cursor.execute("""
INSERT IGNORE INTO ai_agent_plugin_mapping
(agent_id, plugin_id, param_info)
VALUES (%s, %s, %s)
""", (agent_id, "SYSTEM_PLUGIN_STORY", json.dumps(param_info)))
connection.commit()
print(f"[FIXED] Added Story Playback to {len(agents_without_story)} agents!")
else:
print("All agents already have Story Playback!")
return True
except Error as e:
print(f"Error ensuring Story Playback: {e}")
return False
finally:
cursor.close()
def update_manager_api_defaults(connection):
"""Update manager-api default plugins to include Story Playback"""
cursor = connection.cursor()
try:
print("\n4. Updating Manager-API Default Plugins...")
print("=" * 60)
# Check if there's a default plugins configuration
cursor.execute("""
SELECT id, agent_code, agent_name
FROM ai_agent_template
WHERE is_visible = 0
ORDER BY sort
LIMIT 1
""")
default_template = cursor.fetchone()
if default_template:
template_id = default_template[0]
print(f"Default template: {default_template[2]} (ID: {template_id})")
# The manager-api needs to be configured to include Story Playback
# when creating agents from templates
print("\nRECOMMENDATION FOR MANAGER-API:")
print("The manager-api code should be updated to include")
print("SYSTEM_PLUGIN_STORY in the default plugins list when")
print("creating new agents. Currently it only adds:")
print(" - SYSTEM_PLUGIN_MUSIC")
print(" - SYSTEM_PLUGIN_WEATHER")
print(" - SYSTEM_PLUGIN_NEWS_NEWSNOW")
print("\nIt should also add:")
print(" - SYSTEM_PLUGIN_STORY")
return True
except Error as e:
print(f"Error updating defaults: {e}")
return False
finally:
cursor.close()
def main():
print("Fixing Story Playback Auto-Addition for New Agents")
print("=" * 70)
connection = connect_to_database()
if not connection:
return
try:
# 1. Check and fix the latest agent
latest_agent_id = check_latest_agent(connection)
# 2. Try to recreate trigger
trigger_created = drop_and_recreate_trigger(connection)
# 3. Ensure all agents have Story Playback
ensure_all_agents_have_story(connection)
# 4. Update manager-api defaults
update_manager_api_defaults(connection)
# Summary
print(f"\n{'='*70}")
print("SUMMARY")
print('='*70)
if latest_agent_id:
print("[FIXED] Latest agent now has Story Playback")
if trigger_created:
print("[OK] Database trigger/procedure created")
else:
print("[INFO] Trigger couldn't be created - manual fix needed")
print("\nIMPORTANT:")
print("The manager-api Java code needs to be updated to")
print("automatically include SYSTEM_PLUGIN_STORY when")
print("creating new agents from templates.")
print("\nUntil then, Story Playback must be added manually")
print("or via this script after agent creation.")
finally:
connection.close()
if __name__ == "__main__":
main()

View file

@ -1,26 +1,179 @@
This is a development document. If you need to deploy the Xiaozhi server, [click here to view the deployment tutorial](../../README.md#deployment-documentation)
# Project Introduction
# XiaoZhi ESP32 Manager API
run app
This project is developed based on the SpringBoot framework and serves as the backend API for the XiaoZhi ESP32 management system.
npm run serve
manager-api: This project is developed based on the SpringBoot framework.
## Development Environment Requirements
- **JDK 21+**
- **Maven 3.8+**
- **Docker & Docker Compose** (for local database and cache)
- **MySQL 8.0+** (via Docker)
- **Redis 7.0+** (via Docker)
## Quick Start (Development Mode)
### Option 1: Automated Setup (Recommended)
```powershell
# Run the automated setup script
.\dev-setup.ps1
# Then start the application
mvn spring-boot:run "-Dspring-boot.run.arguments=--spring.profiles.active=dev"
```
### Option 2: Manual Setup
#### Step 1: Start Docker Containers
First, start the required MySQL and Redis containers:
```bash
# Navigate to the manager-api directory
cd D:\cheekofinal\xiaozhi-esp32-server\main\manager-api
# Start Docker containers (MySQL, Redis, phpMyAdmin, Redis Commander)
docker-compose up -d
# Verify containers are running
docker-compose ps
```
#### Step 2: Run the Spring Boot Application
```bash
# Clean and compile the project
mvn clean compile
# Run the application with dev profile
mvn spring-boot:run "-Dspring-boot.run.arguments=--spring.profiles.active=dev"
```
## Docker Services
The `docker-compose.yml` includes the following services:
| Service | Port | Description | Credentials |
|---------|------|-------------|--------------|
| **manager-api-db** (MySQL) | 3307 | MySQL database | User: `manager`<br>Password: `managerpassword`<br>Database: `manager_api` |
| **manager-api-redis** | 6380 | Redis cache | Password: `redispassword` |
| **phpMyAdmin** | 8080 | MySQL web interface | User: `root`<br>Password: `rootpassword` |
| **redis-commander** | 8081 | Redis web interface | Auto-configured |
## Access Points
- **API Documentation**: http://localhost:8002/xiaozhi/doc.html
- **Application Base URL**: http://localhost:8002/toy
- **phpMyAdmin**: http://localhost:8080
- **Redis Commander**: http://localhost:8081
## Configuration
The development configuration is located in:
```
src/main/resources/application-dev.yml
```
This configuration is set up to use the local Docker containers:
- MySQL on localhost:3307
- Redis on localhost:6380
## Database Management
### Manual Database Connection
```bash
# Connect to MySQL container
docker exec -it manager-api-db mysql -u manager -p'managerpassword' manager_api
# Connect to Redis container
docker exec -it manager-api-redis redis-cli -a redispassword
```
### Database Migration
The application uses Liquibase for database migrations. Migrations run automatically on startup.
## Troubleshooting
### Container Issues
```bash
# Check container logs
docker-compose logs manager-api-db
docker-compose logs manager-api-redis
# Restart containers
docker-compose restart
# Stop and remove all containers
docker-compose down
# Stop and remove containers with volumes
docker-compose down -v
```
### Application Issues
```bash
# Check if ports are available
netstat -an | findstr :8002
netstat -an | findstr :3307
netstat -an | findstr :6380
# Clean Maven build
mvn clean install
```
### Common Error Solutions
1. **Port Conflicts**: If ports 3307, 6380, 8080, or 8081 are in use, modify the ports in `docker-compose.yml`
2. **Database Connection Failed**:
- Ensure Docker containers are running
- Wait for MySQL health check to pass (can take 30-60 seconds)
- Check if credentials match in `application-dev.yml`
3. **Redis Connection Failed**:
- Verify Redis container is healthy
- Check Redis password configuration
## Development Workflow
1. **First Time Setup**:
```bash
docker-compose up -d
mvn clean compile
mvn spring-boot:run "-Dspring-boot.run.arguments=--spring.profiles.active=dev"
```
2. **Daily Development**:
```bash
# Start containers (if not running)
docker-compose start
# Run application
mvn spring-boot:run "-Dspring-boot.run.arguments=--spring.profiles.active=dev"
```
3. **Cleanup**:
```bash
# Stop application (Ctrl+C)
# Stop containers
docker-compose stop
```
## Project Structure
When developing, use a code editor and select the `manager-api` folder as the project directory when importing the project.
# Development Environment
JDK 21
Maven 3.8+
MySQL 8.0+
Redis 5.0+
Vue 3.x
# API Documentation
After starting, open: http://localhost:8002/xiaozhi/doc.html
to run app
mvn spring-boot:run
```
manager-api/
├── docker-compose.yml # Docker services configuration
├── src/main/resources/
│ ├── application.yml # Base configuration
│ ├── application-dev.yml # Development configuration
│ └── application-prod.yml # Production configuration
├── docker/
│ ├── mysql/init/ # MySQL initialization scripts
│ └── redis/ # Redis configuration
└── target/ # Compiled classes
```

View file

@ -0,0 +1,82 @@
# XiaoZhi Manager API - Development Setup Script
# This script sets up the development environment for the Manager API
Write-Host "🚀 XiaoZhi Manager API Development Setup" -ForegroundColor Green
Write-Host "=======================================" -ForegroundColor Green
# Check if Docker is running
Write-Host "📦 Checking Docker..." -ForegroundColor Yellow
try {
docker --version | Out-Null
Write-Host "✅ Docker is available" -ForegroundColor Green
} catch {
Write-Host "❌ Docker is not available. Please install Docker Desktop and try again." -ForegroundColor Red
exit 1
}
# Check if Maven is available
Write-Host "🔨 Checking Maven..." -ForegroundColor Yellow
try {
mvn --version | Out-Null
Write-Host "✅ Maven is available" -ForegroundColor Green
} catch {
Write-Host "❌ Maven is not available. Please install Maven and try again." -ForegroundColor Red
exit 1
}
# Start Docker containers
Write-Host "🐳 Starting Docker containers..." -ForegroundColor Yellow
docker-compose up -d
if ($LASTEXITCODE -eq 0) {
Write-Host "✅ Docker containers started successfully" -ForegroundColor Green
} else {
Write-Host "❌ Failed to start Docker containers" -ForegroundColor Red
exit 1
}
# Wait for containers to be healthy
Write-Host "⏳ Waiting for containers to be healthy..." -ForegroundColor Yellow
$timeout = 60
$elapsed = 0
do {
$status = docker-compose ps --services --filter "status=running" | Measure-Object -Line
if ($status.Lines -eq 4) {
Write-Host "✅ All containers are running" -ForegroundColor Green
break
}
Start-Sleep -Seconds 2
$elapsed += 2
Write-Host "." -NoNewline -ForegroundColor Yellow
} while ($elapsed -lt $timeout)
if ($elapsed -ge $timeout) {
Write-Host "`n⚠️ Containers may still be starting. Check with 'docker-compose ps'" -ForegroundColor Yellow
} else {
Write-Host ""
}
# Display container status
Write-Host "📋 Container Status:" -ForegroundColor Cyan
docker-compose ps
Write-Host "`n🌐 Service URLs:" -ForegroundColor Cyan
Write-Host " • API Documentation: http://localhost:8002/xiaozhi/doc.html" -ForegroundColor White
Write-Host " • Application: http://localhost:8002/toy" -ForegroundColor White
Write-Host " • phpMyAdmin: http://localhost:8080" -ForegroundColor White
Write-Host " • Redis Commander: http://localhost:8081" -ForegroundColor White
Write-Host "`n🔑 Database Credentials:" -ForegroundColor Cyan
Write-Host " • MySQL: manager/managerpassword @ localhost:3307" -ForegroundColor White
Write-Host " • Redis: redispassword @ localhost:6380" -ForegroundColor White
Write-Host "`n🚀 To start the application, run:" -ForegroundColor Green
Write-Host " mvn spring-boot:run `"-Dspring-boot.run.arguments=--spring.profiles.active=dev`"" -ForegroundColor Yellow
Write-Host "`n📋 Quick Commands:" -ForegroundColor Cyan
Write-Host " • Check containers: docker-compose ps" -ForegroundColor White
Write-Host " • View logs: docker-compose logs [service-name]" -ForegroundColor White
Write-Host " • Stop containers: docker-compose stop" -ForegroundColor White
Write-Host " • Remove containers: docker-compose down" -ForegroundColor White
Write-Host "`n✨ Setup completed successfully!" -ForegroundColor Green

View file

@ -0,0 +1,90 @@
version: '3.8'
services:
# MySQL Database
manager-api-db:
image: mysql:8.0
container_name: manager-api-db
restart: always
environment:
MYSQL_ROOT_PASSWORD: rootpassword
MYSQL_DATABASE: manager_api
MYSQL_USER: manager
MYSQL_PASSWORD: managerpassword
TZ: Asia/Shanghai
ports:
- "3307:3306" # Using 3307 to avoid conflicts with other MySQL instances
volumes:
- mysql_data:/var/lib/mysql
- ./docker/mysql/init:/docker-entrypoint-initdb.d # For initialization scripts
command: --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci
healthcheck:
test: ["CMD", "mysqladmin", "ping", "-h", "localhost"]
timeout: 20s
interval: 10s
retries: 10
networks:
- manager-api-network
# Redis Cache
manager-api-redis:
image: redis:7-alpine
container_name: manager-api-redis
restart: always
environment:
TZ: Asia/Shanghai
ports:
- "6380:6379" # Using 6380 to avoid conflicts with other Redis instances
volumes:
- redis_data:/data
- ./docker/redis/redis.conf:/usr/local/etc/redis/redis.conf # Optional custom config
command: redis-server --appendonly yes --requirepass redispassword
healthcheck:
test: ["CMD", "redis-cli", "auth", "redispassword", "ping"]
interval: 10s
timeout: 5s
retries: 3
networks:
- manager-api-network
# Redis Commander (Optional - Web UI for Redis)
redis-commander:
image: rediscommander/redis-commander:latest
container_name: manager-api-redis-commander
restart: unless-stopped
environment:
REDIS_HOSTS: local:manager-api-redis:6379:0:redispassword
ports:
- "8081:8081"
depends_on:
- manager-api-redis
networks:
- manager-api-network
# phpMyAdmin (Optional - Web UI for MySQL)
phpmyadmin:
image: phpmyadmin/phpmyadmin
container_name: manager-api-phpmyadmin
restart: unless-stopped
environment:
PMA_HOST: manager-api-db
PMA_PORT: 3306
PMA_USER: root
PMA_PASSWORD: rootpassword
MYSQL_ROOT_PASSWORD: rootpassword
ports:
- "8080:80"
depends_on:
- manager-api-db
networks:
- manager-api-network
volumes:
mysql_data:
driver: local
redis_data:
driver: local
networks:
manager-api-network:
driver: bridge

View file

@ -67,11 +67,21 @@ public class AgentController {
private final RedisUtils redisUtils;
@GetMapping("/list")
@Operation(summary = "Get user agents list")
@Operation(summary = "Get agents list (admin gets all agents, user gets own agents)")
@RequiresPermissions("sys:role:normal")
public Result<List<AgentDTO>> getUserAgents() {
public Result<List<AgentDTO>> getAgentsList() {
UserDetail user = SecurityUser.getUser();
List<AgentDTO> agents = agentService.getUserAgents(user.getId());
List<AgentDTO> agents;
// Check if user is super admin
if (user.getSuperAdmin() != null && user.getSuperAdmin() == 1) {
// Admin sees all agents from all users with owner information
agents = agentService.getAllAgentsForAdmin();
} else {
// Regular user sees only their own agents
agents = agentService.getUserAgents(user.getId());
}
return new Result<List<AgentDTO>>().ok(agents);
}

View file

@ -1,8 +1,10 @@
package xiaozhi.modules.agent.dao;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import xiaozhi.common.dao.BaseDao;
import xiaozhi.modules.agent.entity.AgentEntity;
@ -30,6 +32,24 @@ public interface AgentDao extends BaseDao<AgentEntity> {
" ORDER BY d.id DESC LIMIT 1")
AgentEntity getDefaultAgentByMacAddress(@Param("macAddress") String macAddress);
/**
* 获取所有智能体及其所有者信息(管理员专用)
*
* @return 所有智能体列表及用户信息
*/
@Select("SELECT " +
"a.id, a.agent_name, a.system_prompt, a.tts_model_id, " +
"a.llm_model_id, a.vllm_model_id, a.mem_model_id, a.tts_voice_id, " +
"a.created_at, a.updated_at, a.user_id, " +
"u.username as owner_username, " +
"GROUP_CONCAT(d.mac_address SEPARATOR ',') as device_mac_addresses " +
"FROM ai_agent a " +
"LEFT JOIN sys_user u ON a.user_id = u.id " +
"LEFT JOIN ai_device d ON a.id = d.agent_id " +
"GROUP BY a.id " +
"ORDER BY a.created_at DESC")
List<Map<String, Object>> getAllAgentsWithOwnerInfo();
/**
* 根据id查询agent信息,包括插件信息
*

View file

@ -45,4 +45,14 @@ public class AgentDTO {
@Schema(description = "设备数量", example = "10")
private Integer deviceCount;
@Schema(description = "设备MAC地址列表", example = "AA:BB:CC:DD:EE:FF,11:22:33:44:55:66")
private String deviceMacAddresses;
// 管理员专用字段 - 智能体所有者信息
@Schema(description = "所有者用户名", example = "john_doe")
private String ownerUsername;
@Schema(description = "创建时间", example = "2024-03-20 10:00:00")
private Date createDate;
}

View file

@ -43,6 +43,21 @@ public interface AgentService extends BaseService<AgentEntity> {
*/
boolean insert(AgentEntity entity);
/**
* 获取用户的智能体列表
*
* @param userId 用户ID
* @return 智能体列表
*/
List<AgentDTO> getUserAgents(Long userId);
/**
* 获取所有智能体列表(管理员专用,包含用户信息)
*
* @return 所有智能体列表
*/
List<AgentDTO> getAllAgentsForAdmin();
/**
* 根据用户ID删除智能体
*
@ -50,13 +65,6 @@ public interface AgentService extends BaseService<AgentEntity> {
*/
void deleteAgentByUserId(Long userId);
/**
* 获取用户智能体列表
*
* @param userId 用户ID
* @return 智能体列表
*/
List<AgentDTO> getUserAgents(Long userId);
/**
* 根据智能体ID获取设备数量

View file

@ -150,6 +150,59 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
}).collect(Collectors.toList());
}
@Override
public List<AgentDTO> getAllAgentsForAdmin() {
List<Map<String, Object>> agentMaps = agentDao.getAllAgentsWithOwnerInfo();
return agentMaps.stream().map(agentMap -> {
AgentDTO dto = new AgentDTO();
// 基础智能体信息
String agentId = (String) agentMap.get("id");
dto.setId(agentId);
dto.setAgentName((String) agentMap.get("agent_name"));
dto.setSystemPrompt((String) agentMap.get("system_prompt"));
// Handle LocalDateTime to Date conversion for createDate
Object createdAt = agentMap.get("created_at");
if (createdAt instanceof java.time.LocalDateTime) {
dto.setCreateDate(java.sql.Timestamp.valueOf((java.time.LocalDateTime) createdAt));
}
// 获取模型名称 - 同用户方法
String ttsModelId = (String) agentMap.get("tts_model_id");
String llmModelId = (String) agentMap.get("llm_model_id");
String vllmModelId = (String) agentMap.get("vllm_model_id");
String memModelId = (String) agentMap.get("mem_model_id");
String ttsVoiceId = (String) agentMap.get("tts_voice_id");
dto.setTtsModelName(modelConfigService.getModelNameById(ttsModelId));
dto.setLlmModelName(modelConfigService.getModelNameById(llmModelId));
dto.setVllmModelName(modelConfigService.getModelNameById(vllmModelId));
dto.setMemModelId(memModelId);
dto.setTtsVoiceName(timbreModelService.getTimbreNameById(ttsVoiceId));
// 获取智能体最近的最后连接时长 - 同用户方法
dto.setLastConnectedAt(deviceService.getLatestLastConnectionTime(agentId));
// 获取设备MAC地址列表 - 管理员专用
String macAddresses = (String) agentMap.get("device_mac_addresses");
dto.setDeviceMacAddresses(macAddresses);
// 计算设备数量(从MAC地址列表或使用原方法)
if (macAddresses != null && !macAddresses.isEmpty()) {
dto.setDeviceCount(macAddresses.split(",").length);
} else {
// 使用原来的方法获取设备数量
dto.setDeviceCount(getDeviceCountByAgentId(agentId));
}
// 管理员专用字段 - 用户信息
dto.setOwnerUsername((String) agentMap.get("owner_username"));
return dto;
}).collect(Collectors.toList());
}
@Override
public Integer getDeviceCountByAgentId(String agentId) {
if (StringUtils.isBlank(agentId)) {

View file

@ -71,7 +71,17 @@ public class DeviceController {
@RequiresPermissions("sys:role:normal")
public Result<List<DeviceEntity>> getUserDevices(@PathVariable String agentId) {
UserDetail user = SecurityUser.getUser();
List<DeviceEntity> devices = deviceService.getUserDevices(user.getId(), agentId);
List<DeviceEntity> devices;
// Check if user is super admin
if (user.getSuperAdmin() != null && user.getSuperAdmin() == 1) {
// Admin can see all devices for any agent
devices = deviceService.getDevicesByAgentId(agentId);
} else {
// Regular user can only see their own devices
devices = deviceService.getUserDevices(user.getId(), agentId);
}
return new Result<List<DeviceEntity>>().ok(devices);
}

View file

@ -25,6 +25,11 @@ public interface DeviceService extends BaseService<DeviceEntity> {
*/
List<DeviceEntity> getUserDevices(Long userId, String agentId);
/**
* 获取指定智能体的所有设备列表(管理员专用)
*/
List<DeviceEntity> getDevicesByAgentId(String agentId);
/**
* 解绑设备
*/

View file

@ -211,6 +211,13 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
return baseDao.selectList(wrapper);
}
@Override
public List<DeviceEntity> getDevicesByAgentId(String agentId) {
QueryWrapper<DeviceEntity> wrapper = new QueryWrapper<>();
wrapper.eq("agent_id", agentId);
return baseDao.selectList(wrapper);
}
@Override
public void unbindDevice(Long userId, String deviceId) {
UpdateWrapper<DeviceEntity> wrapper = new UpdateWrapper<>();

View file

@ -63,8 +63,8 @@ public class WebMvcConfig implements WebMvcConfigurer {
// 忽略未知属性
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// 设置时区
mapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));
// 设置时区 (IST - India Standard Time)
mapper.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
// 配置Java8日期时间序列化
JavaTimeModule javaTimeModule = new JavaTimeModule();

View file

@ -64,7 +64,7 @@ public class CaptchaServiceImpl implements CaptchaService {
if (StringUtils.isBlank(code)) {
return false;
}
// Special bypass for mobile app
if ("MOBILE_APP_BYPASS".equals(code)) {
// Mobile apps can bypass captcha validation
@ -72,7 +72,7 @@ public class CaptchaServiceImpl implements CaptchaService {
// such as checking a special header or API key
return true;
}
// 获取验证码
String captcha = getCache(uuid, delete);
@ -139,6 +139,14 @@ public class CaptchaServiceImpl implements CaptchaService {
@Override
public boolean validateSMSValidateCode(String phone, String code, Boolean delete) {
// Special bypass for mobile app SMS verification
if ("MOBILE_APP_BYPASS".equals(code)) {
// Mobile apps can bypass SMS validation
// In production, you should add additional security checks
// such as checking a special header or API key
return true;
}
String key = RedisKeys.getSMSValidateCodeKey(phone);
return validate(key, code, delete);
}

View file

@ -22,6 +22,7 @@ spring:
# password: cTefiuLmZSMqGpcQImUmBIsUBhNyUvrK
driver-class-name: com.mysql.cj.jdbc.Driver
# Railway MySQL Configuration - Updated for Railway database
# url: jdbc:mysql://crossover.proxy.rlwy.net:56145/railway?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true&useSSL=true&allowPublicKeyRetrieval=true
# username: root
# password: XjOWQwtGNcoMIELTjoMoaaBTfKiBjVcA
@ -29,6 +30,7 @@ spring:
username: manager
password: managerpassword
initial-size: 10
max-active: 100
min-idle: 10
@ -63,3 +65,4 @@ spring:
max-idle: 8
min-idle: 0
max-wait: -1ms

View file

@ -0,0 +1,17 @@
-- Add semantic search configuration for improved music search functionality
-- 添加语义搜索配置以改进音乐搜索功能
-- Delete existing semantic search params if they exist
delete from sys_params where id in (701, 702, 703, 704, 705, 706, 707);
-- Insert semantic search configuration parameters
INSERT INTO sys_params
(id, param_code, param_value, value_type, param_type, remark, creator, create_date, updater, update_date)
VALUES
(701, 'semantic_search.enabled', 'true', 'boolean', 1, 'Enable semantic music search using vector embeddings', NULL, NULL, NULL, NULL),
(702, 'semantic_search.qdrant_url', 'https://a2482b9f-2c29-476e-9ff0-741aaaaf632e.eu-west-1-0.aws.cloud.qdrant.io', 'string', 1, 'Qdrant vector database URL for music embeddings', NULL, NULL, NULL, NULL),
(703, 'semantic_search.qdrant_api_key', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2Nlc3MiOiJtIn0.zPBGAqVGy-edbbgfNOJsPWV496BsnQ4ELOFvsLNyjsk', 'string', 1, 'Qdrant API key for authentication', NULL, NULL, NULL, NULL),
(704, 'semantic_search.collection_name', 'xiaozhi_music', 'string', 1, 'Vector collection name for music embeddings', NULL, NULL, NULL, NULL),
(705, 'semantic_search.embedding_model', 'all-MiniLM-L6-v2', 'string', 1, 'Sentence transformer model for generating embeddings', NULL, NULL, NULL, NULL),
(706, 'semantic_search.search_limit', '5', 'number', 1, 'Maximum number of search results to return', NULL, NULL, NULL, NULL),
(707, 'semantic_search.min_score_threshold', '0.5', 'number', 1, 'Minimum similarity score threshold (0.0-1.0)', NULL, NULL, NULL, NULL);

View file

@ -41,6 +41,65 @@ export default {
})
}).send()
},
// 获取用户信息 (通过用户ID) - 使用用户列表API并客户端过滤
getUserById(userId, callback) {
// 使用现有的用户列表API,获取所有用户然后客户端过滤
RequestService.sendRequest()
.url(`${getServiceUrl()}/admin/users?page=1&limit=1000`)
.method('GET')
.success((res) => {
RequestService.clearRequestTime()
console.log('getUserById API response:', res);
// 检查响应结构并查找指定用户
if (res.data && res.data.code === 0 && res.data.data && res.data.data.list && Array.isArray(res.data.data.list)) {
// 在用户列表中查找指定ID的用户 (注意字段名是userid,不是id)
const userInfo = res.data.data.list.find(user =>
user.userid === userId || user.userid === parseInt(userId) || user.userid === String(userId)
);
if (userInfo) {
console.log('Found user info:', userInfo);
const formattedResponse = {
data: {
code: 0,
msg: 'success',
data: userInfo
}
};
callback(formattedResponse);
} else {
console.log('User not found in list, userId:', userId);
console.log('Available user IDs:', res.data.data.list.map(u => u.userid));
// 用户不存在
const errorResponse = {
data: {
code: 1,
msg: 'User not found',
data: null
}
};
callback(errorResponse);
}
} else {
console.error('Invalid response structure for getUserById:', res);
const errorResponse = {
data: {
code: 1,
msg: 'Invalid response structure',
data: null
}
};
callback(errorResponse);
}
})
.networkFail((err) => {
console.error('获取用户信息失败:', err)
RequestService.reAjaxFun(() => {
this.getUserById(userId, callback)
})
}).send()
},
// 重置用户密码
resetUserPassword(id, callback) {
RequestService.sendRequest()

View file

@ -3,8 +3,29 @@ import RequestService from '../httpRequest';
export default {
// 获取智能体列表
getAgentList(callback) {
// 获取智能体列表 (Admin - shows all agents from all users)
getAgentList(params, callback) {
// Support both old callback-only format and new params format
if (typeof params === 'function') {
callback = params;
params = { page: 1, limit: 1000 }; // Default pagination for all agents
}
RequestService.sendRequest()
.url(`${getServiceUrl()}/agent/all`)
.method('GET')
.data(params)
.success((res) => {
RequestService.clearRequestTime();
callback(res);
})
.networkFail(() => {
RequestService.reAjaxFun(() => {
this.getAgentList(params, callback);
});
}).send();
},
// 获取用户自己的智能体列表 (User - shows only current user's agents)
getUserAgentList(callback) {
RequestService.sendRequest()
.url(`${getServiceUrl()}/agent/list`)
.method('GET')
@ -14,7 +35,7 @@ export default {
})
.networkFail(() => {
RequestService.reAjaxFun(() => {
this.getAgentList(callback);
this.getUserAgentList(callback);
});
}).send();
},

View file

@ -96,7 +96,7 @@ export default {
const result = [];
const TIME_INTERVAL = 60 * 1000; // 1分钟的时间间隔(毫秒)
// 添加第一条消息的时间标记
// 添加第一条消息的时间标记 (converted to IST)
if (this.messages[0]) {
result.push({
type: 'time',
@ -118,7 +118,7 @@ export default {
if (nextTime - currentTime > TIME_INTERVAL) {
result.push({
type: 'time',
content: this.formatTime(this.messages[i + 1].createdAt),
content: this.formatTime(this.messages[i + 1].createdAt), // converted to IST
id: `time-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
});
}
@ -220,24 +220,36 @@ export default {
}, 200);
},
formatTime(timestamp) {
// Backend sends timestamps already in IST format, no timezone conversion needed
const date = new Date(timestamp);
const now = new Date();
// Create today and yesterday date objects for comparison
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
const yesterday = new Date(today);
yesterday.setDate(yesterday.getDate() - 1);
const hours = date.getHours().toString().padStart(2, '0');
// Create message date object for comparison (without time)
const messageDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
// Format time in 12-hour format
const hours = date.getHours();
const minutes = date.getMinutes().toString().padStart(2, '0');
const ampm = hours >= 12 ? 'PM' : 'AM';
const displayHours = hours % 12 || 12; // Convert to 12-hour format
const timeStr = `${displayHours}:${minutes} ${ampm}`;
if (date >= today) {
return `Today ${hours}:${minutes}`;
} else if (date >= yesterday) {
return `Yesterday ${hours}:${minutes}`;
// Compare dates and return appropriate format
if (messageDate.getTime() === today.getTime()) {
return `Today ${timeStr}`;
} else if (messageDate.getTime() === yesterday.getTime()) {
return `Yesterday ${timeStr}`;
} else {
// For older dates, show full date and time
const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const day = date.getDate().toString().padStart(2, '0');
return `${year}-${month}-${day} ${hours}:${minutes}`;
return `${year}-${month}-${day} ${timeStr}`;
}
},
getAudioIconClass(message) {

View file

@ -1,8 +1,14 @@
<template>
<div class="device-item">
<div style="display: flex;justify-content: space-between;">
<div style="font-weight: 700;font-size: 18px;text-align: left;color: #3d4566;">
{{ device.agentName }}
<div>
<div style="font-weight: 700;font-size: 18px;text-align: left;color: #3d4566;">
{{ device.agentName }}
</div>
<!-- Admin-only: Show owner username -->
<div v-if="isAdmin" class="owner-info">
Owner: {{ device.ownerUsername || `User ID: ${device.userId}` }}
</div>
</div>
<div>
<img src="@/assets/home/delete.png" alt="" class="action-icon delete-icon"
@ -53,6 +59,9 @@ export default {
return { switchValue: false }
},
computed: {
isAdmin() {
return this.$store.getters.getIsSuperAdmin;
},
formattedLastConnectedTime() {
if (!this.device.lastConnectedAt) return 'No conversations yet';
@ -112,6 +121,14 @@ export default {
text-align: left;
}
.owner-info {
font-weight: 400;
font-size: 12px;
color: #5778ff;
text-align: left;
margin-top: 5px;
}
.settings-btn {
font-weight: 500;
font-size: 11px;

View file

@ -24,7 +24,7 @@
</template>
</el-table-column>
<el-table-column label="User ID" prop="userid" align="center"></el-table-column>
<el-table-column label="Phone Number" prop="mobile" align="center"></el-table-column>
<el-table-column label="User Name" prop="mobile" align="center"></el-table-column>
<el-table-column label="Device Count" prop="deviceCount" align="center"></el-table-column>
<el-table-column label="Registration Time" prop="createDate" align="center"></el-table-column>
<el-table-column label="Status" prop="status" align="center">

View file

@ -79,14 +79,39 @@ export default {
skeletonCount: localStorage.getItem('skeletonCount') || 8,
showChatHistory: false,
currentAgentId: '',
currentAgentName: ''
currentAgentName: '',
userCache: {} // 缓存用户信息,避免重复请求
}
},
mounted() {
console.log('Home component mounted, fetching agent list'); // Debug log
this.fetchAgentList();
},
activated() {
// This runs when component is activated (useful if using keep-alive)
console.log('Home component activated, fetching agent list'); // Debug log
this.fetchAgentList();
},
created() {
console.log('Home component created'); // Debug log
},
watch: {
'$route'(to, from) {
// Watch for route changes - refetch data when navigating back to home
console.log('Route changed:', from.path, '->', to.path); // Debug log
if (to.name === 'home' || to.path === '/home') {
console.log('Navigated back to home, refetching agent list'); // Debug log
this.$nextTick(() => {
this.fetchAgentList();
});
}
}
},
methods: {
showAddDialog() {
this.addDeviceDialogVisible = true
@ -129,26 +154,91 @@ export default {
// 获取智能体列表
fetchAgentList() {
this.isLoading = true;
Api.agent.getAgentList(({ data }) => {
if (data?.data) {
this.originalDevices = data.data.map(item => ({
...item,
agentId: item.id
}));
console.log('Starting to fetch agent list...'); // Debug log
// 动态设置骨架屏数量(可选)
this.skeletonCount = Math.min(
Math.max(this.originalDevices.length, 3), // 最少3个
10 // 最多10个
);
// 根据用户角色决定使用哪个API
const isAdmin = this.$store.getters.getIsSuperAdmin;
console.log('User is admin:', isAdmin); // Debug log
this.handleSearchReset();
if (isAdmin) {
// 管理员:获取所有智能体
console.log('Fetching admin agent list...'); // Debug log
Api.agent.getAgentList((response) => {
console.log('Admin API response received:', response); // Debug log
// Extract response.data to match expected structure
this.handleAgentListResponse(response.data);
}, (error) => {
console.error('Failed to fetch admin agent list:', error);
this.$message.error('Failed to load agent list. Please check your connection and try again.');
this.isLoading = false;
});
} else {
// 普通用户:只获取自己的智能体
console.log('Fetching user agent list...'); // Debug log
Api.agent.getUserAgentList((response) => {
console.log('User API response received:', response); // Debug log
// Extract response.data to match expected structure
this.handleAgentListResponse(response.data);
}, (error) => {
console.error('Failed to fetch user agent list:', error);
this.$message.error('Failed to load your agents. Please check your connection and try again.');
this.isLoading = false;
});
}
},
// 处理智能体列表响应
handleAgentListResponse(data) {
console.log('Raw API Response:', data); // Debug log
if (data) {
// The parameter 'data' is already response.data from the API call
let agentList = [];
// The API response structure is nested: response.data.data.list
if (data.data && data.data.list && Array.isArray(data.data.list)) {
// For admin API: data.data.list (nested structure)
agentList = data.data.list;
console.log('Using data.data.list structure'); // Debug log
} else if (data.list && Array.isArray(data.list)) {
// For fallback: data.list
agentList = data.list;
console.log('Using data.list structure'); // Debug log
} else if (Array.isArray(data.data)) {
// For user API: data.data (direct array)
agentList = data.data;
console.log('Using data.data array structure'); // Debug log
} else if (Array.isArray(data)) {
// For direct array: data
agentList = data;
console.log('Using direct array structure'); // Debug log
} else {
console.error('Unexpected API response structure:', data);
console.error('Available keys in data:', Object.keys(data || {})); // Debug log
this.$message.error('Failed to load agent list: Invalid response format');
this.isLoading = false;
return;
}
this.isLoading = false;
}, (error) => {
console.error('Failed to fetch agent list:', error);
this.isLoading = false;
});
console.log('Agent list before processing:', agentList); // Debug log
// 处理agent数据并获取模型名称
this.processAgentListWithModelNames(agentList);
console.log('Final processed devices:', this.originalDevices); // Debug log
// 动态设置骨架屏数量(可选)
this.skeletonCount = Math.min(
Math.max(this.originalDevices.length, 3), // 最少3个
10 // 最多10个
);
this.handleSearchReset();
} else {
console.error('No data in API response:', data);
this.$message.error('Failed to load agent list: No data received');
}
this.isLoading = false;
},
// Delete agent
handleDeleteAgent(agentId) {
@ -173,6 +263,217 @@ export default {
});
}).catch(() => { });
},
// 处理agent列表并获取模型名称
async processAgentListWithModelNames(agentList) {
// 首先创建基本的设备列表
const basicDevices = agentList
.filter(item => item && (item.id || item.agentId))
.map(item => ({
...item,
agentId: item.agentId || item.id,
agentName: item.agentName || item.name || 'Unknown Agent',
// 暂时使用模型ID,稍后会被替换为模型名称
llmModelName: item.llmModelId || 'Not configured',
ttsModelName: item.ttsModelId || 'Not configured',
ttsVoiceName: item.ttsVoiceId || 'Default',
deviceCount: item.deviceCount || 0,
memModelId: item.memModelId || 'Memory_nomem',
lastConnectedAt: item.lastConnectedAt || null,
systemPrompt: item.systemPrompt || 'No system prompt configured',
ownerUsername: item.ownerUsername || null,
// 保留原始ID用于获取模型名称
originalLlmModelId: item.llmModelId,
originalTtsModelId: item.ttsModelId,
originalTtsVoiceId: item.ttsVoiceId
}));
console.log('Basic devices processed:', basicDevices); // Debug log
// 设置基本数据先显示
this.originalDevices = basicDevices;
this.handleSearchReset();
// 异步获取模型名称、设备数量和用户信息
this.fetchModelNamesForDevices();
this.fetchDeviceCountsForAgents();
this.fetchOwnerNamesForAgents();
},
// 获取所有设备的模型名称
fetchModelNamesForDevices() {
const uniqueLlmModels = [...new Set(this.originalDevices.map(d => d.originalLlmModelId).filter(Boolean))];
const uniqueTtsModels = [...new Set(this.originalDevices.map(d => d.originalTtsModelId).filter(Boolean))];
const uniqueVoiceIds = [...new Set(this.originalDevices.map(d => d.originalTtsVoiceId).filter(Boolean))];
console.log('Fetching names for:', { uniqueLlmModels, uniqueTtsModels, uniqueVoiceIds });
// 获取LLM模型名称
uniqueLlmModels.forEach(modelId => {
Api.model.getModelConfig(modelId, (response) => {
console.log(`LLM Model response for ${modelId}:`, response);
if (response.data && response.data.code === 0) {
const modelName = response.data.data?.modelName || modelId;
this.updateDeviceModelName('llmModelName', modelId, modelName);
}
});
});
// 获取TTS模型名称
uniqueTtsModels.forEach(modelId => {
Api.model.getModelConfig(modelId, (response) => {
console.log(`TTS Model response for ${modelId}:`, response);
if (response.data && response.data.code === 0) {
const modelName = response.data.data?.modelName || modelId;
this.updateDeviceModelName('ttsModelName', modelId, modelName);
}
});
});
// 获取TTS声音名称 (暂时跳过自定义语音,只显示ID)
console.log('Voice IDs will be displayed as-is for now');
},
// 更新设备的模型名称
updateDeviceModelName(field, originalId, newName) {
const fieldMapping = {
'llmModelName': 'originalLlmModelId',
'ttsModelName': 'originalTtsModelId',
'ttsVoiceName': 'originalTtsVoiceId'
};
this.originalDevices = this.originalDevices.map(device => {
if (device[fieldMapping[field]] === originalId) {
return { ...device, [field]: newName };
}
return device;
});
// 如果当前显示的是搜索结果,也要更新搜索结果
this.devices = this.devices.map(device => {
if (device[fieldMapping[field]] === originalId) {
return { ...device, [field]: newName };
}
return device;
});
console.log(`Updated ${field} for ${originalId} to: ${newName}`);
},
// 获取所有智能体的设备数量
fetchDeviceCountsForAgents() {
console.log('Fetching device counts for agents...');
this.originalDevices.forEach(device => {
if (device.agentId) {
Api.device.getAgentBindDevices(device.agentId, (response) => {
console.log(`Device response for agent ${device.agentId}:`, response);
if (response.data && response.data.code === 0) {
const devices = response.data.data || [];
const deviceCount = Array.isArray(devices) ? devices.length : 0;
// 更新设备数量
this.updateDeviceInfo(device.agentId, 'deviceCount', deviceCount);
console.log(`Updated device count for ${device.agentName}: ${deviceCount}`);
}
});
}
});
},
// 获取智能体所有者姓名
fetchOwnerNamesForAgents() {
console.log('Fetching owner names for agents...');
const isAdmin = this.$store.getters.getIsSuperAdmin;
if (isAdmin) {
// 管理员:需要获取每个用户的真实姓名
const uniqueUserIds = [...new Set(this.originalDevices.map(d => d.userId).filter(Boolean))];
console.log('Unique user IDs to fetch:', uniqueUserIds);
uniqueUserIds.forEach(userId => {
// 检查缓存
if (this.userCache[userId] && this.userCache[userId] !== `User ${userId}`) {
console.log(`Using cached user info for ${userId}:`, this.userCache[userId]);
this.updateOwnerNameForUserId(userId, this.userCache[userId]);
return;
}
// 从API获取用户信息
console.log(`Fetching user info for ${userId} via API...`);
Api.admin.getUserById(userId, (response) => {
console.log(`User info response for ${userId}:`, response);
if (response.data && response.data.code === 0) {
const userData = response.data.data;
console.log(`Raw user data for ${userId}:`, userData);
const username = userData.mobile || userData.username || userData.email || userData.name || `User ${userId}`;
// 缓存用户信息
this.userCache[userId] = username;
// 更新显示
this.updateOwnerNameForUserId(userId, username);
console.log(`Successfully updated owner name for userId ${userId}: ${username}`);
} else {
console.error(`Failed to get user info for ${userId}:`, response);
console.error('API response details:', response.data);
// 如果获取失败,显示默认名称
const fallbackName = `User ${userId}`;
this.userCache[userId] = fallbackName;
this.updateOwnerNameForUserId(userId, fallbackName);
console.log(`Using fallback name for userId ${userId}: ${fallbackName}`);
}
});
});
} else {
// 普通用户:获取当前用户信息
Api.user.getUserInfo((response) => {
console.log('Current user info:', response);
if (response.data && response.data.code === 0) {
const currentUser = response.data.data;
const currentUsername = currentUser.username || currentUser.mobile || currentUser.email || 'Current User';
// 所有智能体都是自己的
this.originalDevices.forEach(device => {
this.updateDeviceInfo(device.agentId, 'ownerUsername', currentUsername);
});
}
});
}
},
// 根据userId更新所有者姓名
updateOwnerNameForUserId(userId, username) {
this.originalDevices.forEach(device => {
if (device.userId === userId) {
this.updateDeviceInfo(device.agentId, 'ownerUsername', username);
}
});
},
// 更新设备信息(通用方法)
updateDeviceInfo(agentId, field, value) {
this.originalDevices = this.originalDevices.map(device => {
if (device.agentId === agentId) {
return { ...device, [field]: value };
}
return device;
});
// 同时更新搜索结果
this.devices = this.devices.map(device => {
if (device.agentId === agentId) {
return { ...device, [field]: value };
}
return device;
});
},
handleShowChatHistory({ agentId, agentName }) {
this.currentAgentId = agentId;
this.currentAgentName = agentName;

View file

@ -1,4 +1,5 @@
{
"debug": false,
"mqtt_broker": {
"host": "192.168.1.101",
@ -14,4 +15,5 @@
"api_key": "devkey",
"api_secret": "secret"
}
}
}

View file

@ -7,7 +7,7 @@ import struct
import logging
import pyaudio
import keyboard
#hjvk
from typing import Dict, Optional, Tuple
import requests
import paho.mqtt.client as mqtt_client
@ -24,6 +24,9 @@ OTA_PORT = 8002
MQTT_BROKER_HOST = "139.59.7.72" # Your EMQX instance
MQTT_BROKER_PORT = 1883
# DEVICE_MAC is now dynamically generated for uniqueness
PLAYBACK_BUFFER_MIN_FRAMES = 3 # Minimum frames to have in buffer to continue playback

View file

@ -404,6 +404,43 @@ ASR:
# Language parameter, 1537 for Mandarin, specific reference: https://ai.baidu.com/ai-doc/SPEECH/0lbxfnc9b
dev_pid: 1537
output_dir: tmp/
GoogleSpeechV2:
# Google Cloud Speech-to-Text v2 with Chirp 2 model
# Chirp 2 is Google's next-generation universal speech model with improved accuracy
# Setup instructions:
# 1. Enable Speech-to-Text API v2 in Google Cloud Console: https://console.cloud.google.com/apis/library/speech.googleapis.com
# 2. Create a service account: https://console.cloud.google.com/iam-admin/serviceaccounts
# 3. Download JSON credentials and set the path below
# Pricing: https://cloud.google.com/speech-to-text/v2/pricing
type: google_speech_v2
# Google Cloud project ID
project_id: gen-lang-client-0652043794
# Processing location for Chirp 2 (available in: us-central1, europe-west4, asia-southeast1)
# Note: API resource uses 'global' but processing happens in this region
location: us-central1
# Path to service account credentials JSON file
credentials_path: "C:\\Users\\Acer\\Cheeko-esp32-server\\main\\xiaozhi-server\\gen-lang-client-0652043794-e5f4175261a8.json"
# Model to use (chirp_2 for best accuracy, latest_long for standard)
model: chirp_2
# Language codes - Chirp 2 supports multiple languages simultaneously
# Examples: ["en-US"], ["zh-CN"], ["en-US", "zh-CN"] for multilingual
language_codes:
- en-US
# Audio encoding (LINEAR16 for PCM, OGG_OPUS for Opus)
encoding: LINEAR16
# Sample rate in Hz (16000 recommended)
sample_rate_hertz: 16000
# Enable automatic punctuation
enable_automatic_punctuation: true
# Enable word-level timestamps
enable_word_time_offsets: false
# Enable word confidence scores
enable_word_confidence: false
# Enable spoken punctuation (e.g., "period", "comma")
enable_spoken_punctuation: false
# Enable spoken emojis (e.g., "smiley face")
enable_spoken_emojis: false
output_dir: tmp/
VAD:
SileroVAD:
@ -867,6 +904,7 @@ TTS:
voice: "OUeAo1mhq6IBExi"
output_dir: tmp/
semantic_search:
# Enable semantic search for music (requires Qdrant and sentence-transformers)
enabled: true # Set to false to disable
@ -882,3 +920,4 @@ semantic_search:
search_limit: 5
# Minimum similarity score threshold (0.5 = 50% similarity required)
min_score_threshold: 0.5

View file

@ -2333,6 +2333,9 @@ class ConnectionHandler:
# Also reset listen start time
if hasattr(self, 'listen_start_time'):
self.listen_start_time = None
# Reset had_speaking_state flag used for ASR processing
if hasattr(self, 'had_speaking_state'):
self.had_speaking_state = False
# Clear ASR audio queue for this specific connection only
if hasattr(self, 'asr_audio_queue'):
# Empty the queue by getting all items without blocking

View file

@ -1,204 +1,3 @@
# from core.handle.sendAudioHandle import send_stt_message
# from core.handle.intentHandler import handle_user_intent
# from core.utils.output_counter import check_device_output_limit
# from core.handle.abortHandle import handleAbortMessage
# import time
# import asyncio
# import json
# from core.handle.sendAudioHandle import SentenceType
# from core.utils.util import audio_to_data
# TAG = __name__
# async def handleAudioMessage(conn, audio):
# # Log that we received audio (only log periodically to avoid spam)
# if not hasattr(conn, '_audio_log_counter'):
# conn._audio_log_counter = 0
# conn._audio_log_counter += 1
# if conn._audio_log_counter % 200 == 0: # Log every 200th packet (reduced from 50)
# conn.logger.bind(tag=TAG).debug(f"Received audio packet #{conn._audio_log_counter}, size: {len(audio)} bytes")
# # Skip VAD/ASR processing when server is speaking (streaming audio to client)
# # This prevents interruptions during TTS playback
# if conn.client_is_speaking:
# # conn.logger.bind(tag=TAG).debug("Server is speaking - skipping audio processing to prevent interruption")
# return
# # Whether the current segment has someone speaking
# have_voice = conn.vad.is_vad(conn, audio)
# # Track when voice recording starts in auto VAD mode (for 10-second timeout)
# if have_voice and not hasattr(conn, 'vad_recording_start_time'):
# conn.vad_recording_start_time = time.time()
# conn.logger.bind(tag=TAG).debug(f"VAD recording started at: {conn.vad_recording_start_time}")
# elif have_voice and hasattr(conn, 'vad_recording_start_time'):
# conn.logger.bind(tag=TAG).debug(f"VAD recording continues, started at: {conn.vad_recording_start_time}")
# # Check if this is the initial connection period (ignore first 1 second of audio)
# if have_voice and hasattr(conn, "initial_connection_handled") and not conn.initial_connection_handled:
# current_time = asyncio.get_event_loop().time()
# if current_time - conn.initial_connection_time < 1.0: # Ignore first 1 second
# have_voice = False
# conn.asr_audio.clear() # Clear any accumulated audio
# return
# else:
# conn.initial_connection_handled = True
# # If the device was just woken up, briefly ignore VAD detection
# if have_voice and hasattr(conn, "just_woken_up") and conn.just_woken_up:
# have_voice = False
# # Set a brief delay before resuming VAD detection
# conn.asr_audio.clear()
# if not hasattr(conn, "vad_resume_task") or conn.vad_resume_task.done():
# conn.vad_resume_task = asyncio.create_task(
# resume_vad_detection(conn))
# return
# if have_voice:
# if conn.client_is_speaking:
# await handleAbortMessage(conn)
# # Device long-term idle detection, used for say goodbye
# await no_voice_close_connect(conn, have_voice)
# # Receive audio
# await conn.asr.receive_audio(conn, audio, have_voice)
# async def resume_vad_detection(conn):
# # Wait 2 seconds before resuming VAD detection
# await asyncio.sleep(1)
# conn.just_woken_up = False
# async def startToChat(conn, text):
# # Check if input is in JSON format (containing speaker information)
# speaker_name = None
# actual_text = text
# try:
# # Try to parse JSON format input
# if text.strip().startswith('{') and text.strip().endswith('}'):
# data = json.loads(text)
# if 'speaker' in data and 'content' in data:
# speaker_name = data['speaker']
# actual_text = data['content']
# conn.logger.bind(tag=TAG).info(
# f"Parsed speaker information: {speaker_name}")
# # Use JSON format text directly, do not parse
# actual_text = text
# except (json.JSONDecodeError, KeyError):
# # If parsing fails, continue using original text
# pass
# # Save speaker information to connection object
# if speaker_name:
# conn.current_speaker = speaker_name
# else:
# conn.current_speaker = None
# if conn.need_bind:
# await check_bind_device(conn)
# return
# # If the daily output word count exceeds the limit
# if conn.max_output_size > 0:
# if check_device_output_limit(
# conn.headers.get("device-id"), conn.max_output_size
# ):
# await max_out_size(conn)
# return
# if conn.client_is_speaking:
# await handleAbortMessage(conn)
# # First perform intent analysis, using actual text content
# intent_handled = await handle_user_intent(conn, actual_text)
# if intent_handled:
# # If intent has been handled, no longer proceed with chat
# return
# # Intent not handled, continue with regular chat flow, using actual text content
# await send_stt_message(conn, actual_text)
# conn.executor.submit(conn.chat, actual_text)
# async def no_voice_close_connect(conn, have_voice):
# if have_voice:
# conn.last_activity_time = time.time() * 1000
# return
# # Only perform timeout check when timestamp has been initialized
# if conn.last_activity_time > 0.0:
# no_voice_time = time.time() * 1000 - conn.last_activity_time
# close_connection_no_voice_time = int(
# conn.config.get("close_connection_no_voice_time", 120)
# )
# if (
# not conn.close_after_chat
# and no_voice_time > 1000 * close_connection_no_voice_time
# ):
# conn.close_after_chat = True
# conn.client_abort = False
# end_prompt = conn.config.get("end_prompt", {})
# if end_prompt and end_prompt.get("enable", True) is False:
# conn.logger.bind(tag=TAG).info(
# "End conversation, no need to send ending prompt")
# await conn.close()
# return
# prompt = end_prompt.get("prompt")
# if not prompt:
# prompt = "Please use ```time flies so fast``` as the opening, and use emotionally rich, reluctant words to end this conversation!"
# await startToChat(conn, prompt)
# async def max_out_size(conn):
# text = "Sorry, I have some things to deal with now. Let's chat again at this time tomorrow. It's a promise! See you tomorrow, goodbye!"
# await send_stt_message(conn, text)
# file_path = "config/assets/max_output_size.wav"
# opus_packets, _ = audio_to_data(file_path)
# conn.tts.tts_audio_queue.put((SentenceType.LAST, opus_packets, text))
# conn.close_after_chat = True
# async def check_bind_device(conn):
# if conn.bind_code:
# # Ensure bind_code is a 6-digit number
# if len(conn.bind_code) != 6:
# conn.logger.bind(tag=TAG).error(
# f"Invalid binding code format: {conn.bind_code}")
# text = "Binding code format error, please check configuration."
# await send_stt_message(conn, text)
# return
# text = f"Please log into the control panel and enter {conn.bind_code} to bind the device."
# await send_stt_message(conn, text)
# # Play notification sound
# music_path = "config/assets/bind_code.wav"
# opus_packets, _ = audio_to_data(music_path)
# conn.tts.tts_audio_queue.put((SentenceType.FIRST, opus_packets, text))
# # Play digits one by one
# for i in range(6): # Ensure only 6 digits are played
# try:
# digit = conn.bind_code[i]
# num_path = f"config/assets/bind_code/{digit}.wav"
# num_packets, _ = audio_to_data(num_path)
# conn.tts.tts_audio_queue.put(
# (SentenceType.MIDDLE, num_packets, None))
# except Exception as e:
# conn.logger.bind(tag=TAG).error(
# f"Failed to play digit audio: {e}")
# continue
# conn.tts.tts_audio_queue.put((SentenceType.LAST, [], None))
# else:
# text = f"Version information for this device was not found. Please configure the OTA address correctly and then recompile the firmware."
# await send_stt_message(conn, text)
# music_path = "config/assets/bind_not_found.wav"
# opus_packets, _ = audio_to_data(music_path)
# conn.tts.tts_audio_queue.put((SentenceType.LAST, opus_packets, text))
from core.handle.sendAudioHandle import send_stt_message
from core.handle.intentHandler import handle_user_intent
from core.utils.output_counter import check_device_output_limit
@ -239,15 +38,7 @@ async def handleAudioMessage(conn, audio):
conn.logger.bind(tag=TAG).debug(f"VAD recording started at: {conn.vad_recording_start_time}")
# Don't overwrite existing timer during continuous voice detection
# Check if this is the initial connection period (ignore first 1 second of audio)
if have_voice and hasattr(conn, "initial_connection_handled") and not conn.initial_connection_handled:
current_time = asyncio.get_event_loop().time()
if current_time - conn.initial_connection_time < 1.0: # Ignore first 1 second
have_voice = False
conn.asr_audio.clear() # Clear any accumulated audio
return
else:
conn.initial_connection_handled = True
# Initial connection handling removed - no longer ignoring initial audio
# If the device was just woken up, briefly ignore VAD detection
if have_voice and hasattr(conn, "just_woken_up") and conn.just_woken_up:

View file

@ -74,13 +74,6 @@ class ASRProviderBase(ABC):
f"client_have_voice={conn.client_have_voice}, "
f"audio_len={len(audio)}, asr_buffer_len={len(conn.asr_audio)}")
# Echo suppression: Ignore audio for a brief period after starting to listen
if hasattr(conn, 'listen_start_time') and conn.listen_start_time is not None:
time_since_listen_start = time.time() - conn.listen_start_time
if time_since_listen_start < 0.1: # Ignore first 100ms of audio (echo period)
if have_voice:
logger.bind(tag=TAG).debug(f"Ignoring potential echo audio ({time_since_listen_start:.2f}s after listen start)")
have_voice = False
# Always add audio to pre-buffer (rolling buffer)
conn.audio_pre_buffer.append(audio)
@ -95,6 +88,17 @@ class ASRProviderBase(ABC):
# Add pre-buffered audio to the beginning of ASR audio
conn.asr_audio = list(conn.audio_pre_buffer) + conn.asr_audio
conn.audio_pre_buffer.clear()
# Initialize flag to track if we've had actual SPEAKING state
conn.had_speaking_state = False
# Check if we're in SPEAKING state (not just STARTING)
if hasattr(conn, 'vad') and hasattr(conn.vad, 'analyzer'):
from core.providers.vad.vad_analyzer import VADState
current_vad_state = conn.vad.analyzer._vad_state
if current_vad_state == VADState.SPEAKING:
if not hasattr(conn, 'had_speaking_state') or not conn.had_speaking_state:
logger.bind(tag=TAG).info("Setting had_speaking_state = True (SPEAKING detected)")
conn.had_speaking_state = True
conn.asr_audio.append(audio)
if not have_voice and not conn.client_have_voice:
@ -112,11 +116,22 @@ class ASRProviderBase(ABC):
asr_audio_task = conn.asr_audio.copy()
conn.asr_audio.clear()
# Check had_speaking_state BEFORE resetting VAD states
had_speaking = hasattr(conn, 'had_speaking_state') and conn.had_speaking_state
logger.bind(tag=TAG).info(f"ASR decision: had_speaking={had_speaking}, audio_chunks={len(asr_audio_task)}")
conn.reset_vad_states()
if len(asr_audio_task) > 20: # Increased from 15 to 20 chunks (1.2 seconds)
logger.bind(tag=TAG).debug(f"Processing {len(asr_audio_task)} audio chunks")
if had_speaking and len(asr_audio_task) > 20:
logger.bind(tag=TAG).info(f"Processing {len(asr_audio_task)} audio chunks (had speaking state)")
await self.handle_voice_stop(conn, asr_audio_task)
elif len(asr_audio_task) > 20:
logger.bind(tag=TAG).info(f"Discarding {len(asr_audio_task)} audio chunks (no speaking state detected)")
# Reset the speaking state flag for next session
if hasattr(conn, 'had_speaking_state'):
conn.had_speaking_state = False
# Handle voice stop
async def handle_voice_stop(self, conn, asr_audio_task: List[bytes]):

View file

@ -0,0 +1,556 @@
import os
import time
import json
import asyncio
from google.cloud import speech_v2
from google.api_core import exceptions
from google.api_core.client_options import ClientOptions
from config.logger import setup_logging
from typing import Optional, Tuple, List, AsyncIterator
from core.providers.asr.base import ASRProviderBase
from core.providers.asr.dto.dto import InterfaceType
TAG = __name__
logger = setup_logging()
class ASRProvider(ASRProviderBase):
"""
Google Cloud Speech-to-Text v2 Provider with Chirp 2 model support
Chirp 2 is Google's next-generation universal speech model with improved accuracy
"""
def __init__(self, config: dict, delete_audio_file: bool):
super().__init__(config)
self.interface_type = InterfaceType.NON_STREAM
# Google Cloud configuration
self.project_id = config.get("project_id")
self.location = config.get("location", "global") # Chirp 2 is available globally
self.credentials_path = config.get("credentials_path")
# Model configuration - Chirp 2 specific
self.model = config.get("model", "chirp_2") # Use Chirp 2 by default
language_codes_from_config = config.get("language_codes", ["en-US"])
# Ensure language_codes is never empty (Google API requirement)
if not language_codes_from_config or not isinstance(language_codes_from_config, list):
self.language_codes = ["en-US"]
logger.bind(tag=TAG).warning(f"Invalid or empty language_codes in config, using default: ['en-US']")
else:
self.language_codes = language_codes_from_config
# Debug logging for language codes
logger.bind(tag=TAG).info(f"Configured language_codes: {self.language_codes} (type: {type(self.language_codes)})")
# Audio configuration
self.sample_rate_hertz = config.get("sample_rate_hertz", 16000)
self.encoding = config.get("encoding", "LINEAR16")
# Recognition configuration
self.enable_automatic_punctuation = config.get("enable_automatic_punctuation", True)
self.enable_word_time_offsets = config.get("enable_word_time_offsets", False)
self.enable_word_confidence = config.get("enable_word_confidence", False)
self.enable_spoken_punctuation = config.get("enable_spoken_punctuation", False)
self.enable_spoken_emojis = config.get("enable_spoken_emojis", False)
# File management
self.output_dir = config.get("output_dir", "./audio_files")
self.delete_audio_file = delete_audio_file
# Set credentials if provided
if self.credentials_path:
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = self.credentials_path
# Initialize the Speech client with v2 API
try:
# For Chirp 2, use regional endpoint and recognizer
if self.model == "chirp_2":
# Use regional API endpoint for Chirp 2
api_endpoint = f"{self.location}-speech.googleapis.com"
client_options = ClientOptions(api_endpoint=api_endpoint)
self.client = speech_v2.SpeechClient(client_options=client_options)
# Use regional recognizer path to match regional endpoint
# Note: When using regional endpoint, recognizer path must also use same region
self.recognizer_name = f"projects/{self.project_id}/locations/{self.location}/recognizers/_"
logger.bind(tag=TAG).info(f"Using regional API endpoint: {api_endpoint}")
else:
# Use default global client and recognizer for standard models
self.client = speech_v2.SpeechClient()
self.recognizer_name = f"projects/{self.project_id}/locations/global/recognizers/_"
logger.bind(tag=TAG).info(
f"Google Speech v2 initialized with model: {self.model}, "
f"project: {self.project_id}, recognizer: {self.recognizer_name}"
)
except Exception as e:
logger.bind(tag=TAG).error(f"Failed to initialize Google Speech v2 client: {e}")
raise
# Ensure output directory exists
os.makedirs(self.output_dir, exist_ok=True)
# Streaming session management
self.streaming_sessions = {} # conn.session_id -> streaming session data
def _get_audio_encoding(self):
"""Map encoding string to Google Speech enum"""
try:
encoding_map = {
"LINEAR16": speech_v2.ExplicitDecodingConfig.AudioEncoding.LINEAR16,
"FLAC": speech_v2.ExplicitDecodingConfig.AudioEncoding.FLAC,
"MULAW": speech_v2.ExplicitDecodingConfig.AudioEncoding.MULAW,
"AMR": speech_v2.ExplicitDecodingConfig.AudioEncoding.AMR,
"AMR_WB": speech_v2.ExplicitDecodingConfig.AudioEncoding.AMR_WB,
"OGG_OPUS": speech_v2.ExplicitDecodingConfig.AudioEncoding.OGG_OPUS,
"MP3": speech_v2.ExplicitDecodingConfig.AudioEncoding.MP3,
"WEBM_OPUS": speech_v2.ExplicitDecodingConfig.AudioEncoding.WEBM_OPUS,
}
# Add SPEEX if available (not all versions support it)
if hasattr(speech_v2.ExplicitDecodingConfig.AudioEncoding, 'SPEEX_WITH_HEADER_BYTE'):
encoding_map["SPEEX_WITH_HEADER_BYTE"] = speech_v2.ExplicitDecodingConfig.AudioEncoding.SPEEX_WITH_HEADER_BYTE
return encoding_map.get(self.encoding, speech_v2.ExplicitDecodingConfig.AudioEncoding.LINEAR16)
except AttributeError as e:
logger.bind(tag=TAG).warning(f"Audio encoding {self.encoding} not supported, using LINEAR16: {e}")
return speech_v2.ExplicitDecodingConfig.AudioEncoding.LINEAR16
async def speech_to_text(
self, opus_data: List[bytes], session_id: str, audio_format="opus"
) -> Tuple[Optional[str], Optional[str]]:
"""Convert speech data to text using Google Cloud Speech v2 API with Chirp 2"""
start_time = time.time()
audio_file_path = None
try:
# Decode Opus to PCM if needed
if audio_format == "opus":
pcm_data = self.decode_opus(opus_data)
if not pcm_data:
logger.bind(tag=TAG).error("Failed to decode Opus audio")
return "", None
else:
pcm_data = opus_data
# Save audio to file for logging/debugging
audio_file_path = self.save_audio_to_file(pcm_data, session_id)
# Combine PCM data
audio_content = b"".join(pcm_data)
# Calculate audio length for logging
audio_length_seconds = len(audio_content) / (self.sample_rate_hertz * 2) # 16-bit audio
# Configure recognition request - use model name as-is
model_name = self.model
encoding = self._get_audio_encoding()
logger.bind(tag=TAG).debug(f"Using model: {model_name} for recognition")
logger.bind(tag=TAG).debug(f"Audio encoding: {encoding}, sample_rate: {self.sample_rate_hertz}, audio_length: {len(audio_content)} bytes")
# Configure recognition request based on model type
if self.model == "chirp_2":
# Use explicit decoding config for Chirp 2 with proper audio format
config = speech_v2.RecognitionConfig(
explicit_decoding_config=speech_v2.ExplicitDecodingConfig(
encoding=encoding,
sample_rate_hertz=self.sample_rate_hertz,
audio_channel_count=1,
),
language_codes=self.language_codes,
model=model_name, # chirp_2
features=speech_v2.RecognitionFeatures(
enable_automatic_punctuation=self.enable_automatic_punctuation,
enable_word_time_offsets=self.enable_word_time_offsets,
enable_word_confidence=self.enable_word_confidence,
enable_spoken_punctuation=self.enable_spoken_punctuation,
enable_spoken_emojis=self.enable_spoken_emojis,
profanity_filter=False,
),
)
else:
# Use explicit decoding for standard models
config = speech_v2.RecognitionConfig(
explicit_decoding_config=speech_v2.ExplicitDecodingConfig(
encoding=encoding,
sample_rate_hertz=self.sample_rate_hertz,
audio_channel_count=1,
),
language_codes=self.language_codes,
model=model_name,
features=speech_v2.RecognitionFeatures(
enable_automatic_punctuation=self.enable_automatic_punctuation,
enable_word_time_offsets=self.enable_word_time_offsets,
enable_word_confidence=self.enable_word_confidence,
enable_spoken_punctuation=self.enable_spoken_punctuation,
enable_spoken_emojis=self.enable_spoken_emojis,
profanity_filter=False,
),
)
# Create recognition request
request = speech_v2.RecognizeRequest(
recognizer=self.recognizer_name,
config=config,
content=audio_content,
)
# Perform synchronous speech recognition
try:
response = self.client.recognize(request=request)
# Extract transcription from response
transcript = ""
confidence_scores = []
for result in response.results:
# Get the best alternative (highest confidence)
if result.alternatives:
best_alternative = result.alternatives[0]
transcript += best_alternative.transcript + " "
# Collect confidence scores if available
if hasattr(best_alternative, 'confidence'):
confidence_scores.append(best_alternative.confidence)
# Log word-level details if enabled
if self.enable_word_time_offsets and hasattr(best_alternative, 'words'):
for word_info in best_alternative.words:
logger.bind(tag=TAG).debug(
f"Word: {word_info.word}, "
f"Start: {word_info.start_offset}, "
f"End: {word_info.end_offset}"
)
transcript = transcript.strip()
# Calculate average confidence if available
avg_confidence = sum(confidence_scores) / len(confidence_scores) if confidence_scores else None
elapsed_time = time.time() - start_time
logger.bind(tag=TAG).info(
f"Google Speech v2 (Chirp 2) transcription completed in {elapsed_time:.2f}s"
f"{f', confidence: {avg_confidence:.2f}' if avg_confidence else ''}: {transcript}"
)
# Log the transcript for debugging/analysis
if transcript:
self.log_audio_transcript(audio_file_path, audio_length_seconds, transcript)
return transcript, audio_file_path
except exceptions.GoogleAPIError as e:
logger.bind(tag=TAG).error(f"Google Speech API error: {e}")
return "", audio_file_path
except Exception as e:
logger.bind(tag=TAG).error(
f"Speech-to-text error: {str(e)}, type: {type(e).__name__}"
)
import traceback
logger.bind(tag=TAG).debug(f"Traceback: {traceback.format_exc()}")
return "", audio_file_path
finally:
# Clean up audio file if configured
if self.delete_audio_file and audio_file_path and os.path.exists(audio_file_path):
try:
os.remove(audio_file_path)
logger.bind(tag=TAG).debug(f"Deleted audio file: {audio_file_path}")
except Exception as e:
logger.bind(tag=TAG).warning(
f"Failed to delete audio file {audio_file_path}: {e}"
)
async def start_streaming_session(self, conn, session_id: str) -> bool:
"""Start a streaming ASR session for real-time transcription.
Args:
conn: Connection object
session_id: Unique session identifier
Returns:
True if session started successfully, False otherwise
"""
try:
logger.bind(tag=TAG).info(f"[STREAM-START] Starting streaming session: {session_id}")
# Validate language codes
safe_language_codes = self.language_codes if self.language_codes else ["en-US"]
logger.bind(tag=TAG).debug(f"[STREAM-START] Using language_codes: {safe_language_codes}")
# Create simplified session data with direct audio buffer
session_data = {
'language_codes': safe_language_codes,
'model': self.model,
'audio_buffer': [], # Simple list to collect audio chunks
'stream_iterator': None,
'streaming_task': None,
'final_transcript': "",
'partial_transcript': "",
'session_active': True,
'audio_count': 0
}
# Store session
self.streaming_sessions[session_id] = session_data
logger.bind(tag=TAG).info(f"[STREAM-START] Session {session_id} created with simplified data structure")
# Start the streaming task
session_data['streaming_task'] = asyncio.create_task(
self._simplified_streaming_task(session_id, session_data)
)
logger.bind(tag=TAG).info(f"[STREAM-START] Streaming session {session_id} started successfully")
return True
except Exception as e:
logger.bind(tag=TAG).error(f"[STREAM-START] Failed to start streaming session {session_id}: {e}")
import traceback
logger.bind(tag=TAG).error(f"[STREAM-START] Traceback: {traceback.format_exc()}")
return False
async def _simplified_streaming_task(self, session_id: str, session_data: dict):
"""Simplified streaming task that processes audio directly without complex queues."""
logger.bind(tag=TAG).info(f"[STREAM-TASK] Starting simplified streaming task for session {session_id}")
try:
# Create streaming configuration with explicit decoding (matches non-streaming config)
config = speech_v2.StreamingRecognitionConfig(
config=speech_v2.RecognitionConfig(
explicit_decoding_config=speech_v2.ExplicitDecodingConfig(
encoding=self._get_audio_encoding(),
sample_rate_hertz=self.sample_rate_hertz,
audio_channel_count=1,
),
language_codes=session_data['language_codes'],
model=session_data['model'],
features=speech_v2.RecognitionFeatures(
enable_automatic_punctuation=self.enable_automatic_punctuation,
enable_word_time_offsets=self.enable_word_time_offsets,
enable_word_confidence=self.enable_word_confidence,
enable_spoken_punctuation=self.enable_spoken_punctuation,
enable_spoken_emojis=self.enable_spoken_emojis,
profanity_filter=False,
),
),
streaming_features=speech_v2.StreamingRecognitionFeatures(
interim_results=True,
enable_voice_activity_events=True,
)
)
logger.bind(tag=TAG).info(f"[STREAM-TASK] Created config for {session_id}:")
logger.bind(tag=TAG).info(f" - Language codes: {session_data['language_codes']}")
logger.bind(tag=TAG).info(f" - Model: {session_data['model']}")
logger.bind(tag=TAG).info(f" - Encoding: {self._get_audio_encoding()}")
logger.bind(tag=TAG).info(f" - Sample rate: {self.sample_rate_hertz} Hz")
logger.bind(tag=TAG).info(f" - Channels: 1 (mono)")
# Use a thread-safe queue to pass audio data to generator
import queue
import threading
audio_queue = queue.Queue()
def audio_generator():
"""Generator that yields audio requests to Google API."""
logger.bind(tag=TAG).debug(f"[AUDIO-GEN] Starting audio generator for {session_id}")
# First request: configuration
config_request = speech_v2.StreamingRecognizeRequest(
recognizer=self.recognizer_name,
streaming_config=config
)
logger.bind(tag=TAG).info(f"[AUDIO-GEN] Sending config request for {session_id}")
yield config_request
# Track audio chunks sent
chunks_sent = 0
# Process audio chunks from queue
while True:
try:
# Wait for audio data with timeout
audio_chunk = audio_queue.get(timeout=1.0)
if audio_chunk is None: # End signal
logger.bind(tag=TAG).info(f"[AUDIO-GEN] Received end signal for {session_id}")
break
chunks_sent += 1
logger.bind(tag=TAG).info(f"[AUDIO-GEN] Sending audio chunk #{chunks_sent} ({len(audio_chunk)} bytes) for {session_id}")
# Create and yield audio request
audio_request = speech_v2.StreamingRecognizeRequest(audio=audio_chunk)
yield audio_request
except queue.Empty:
# Timeout - check if session is still active
if not session_data['session_active']:
logger.bind(tag=TAG).info(f"[AUDIO-GEN] Session {session_id} no longer active, stopping generator")
break
continue
except Exception as e:
logger.bind(tag=TAG).error(f"[AUDIO-GEN] Error in generator for {session_id}: {e}")
break
logger.bind(tag=TAG).info(f"[AUDIO-GEN] Audio generator finished for {session_id} (sent {chunks_sent} chunks)")
# Function to feed audio data from buffer to queue
def audio_feeder():
"""Feed audio data from session buffer to generator queue."""
logger.bind(tag=TAG).debug(f"[AUDIO-FEEDER] Starting audio feeder for {session_id}")
try:
while session_data['session_active']:
# Check if we have audio data in buffer
if session_data['audio_buffer']:
audio_chunk = session_data['audio_buffer'].pop(0)
audio_queue.put(audio_chunk)
logger.bind(tag=TAG).debug(f"[AUDIO-FEEDER] Moved audio chunk to queue for {session_id}")
else:
# No audio data, sleep briefly
import time
time.sleep(0.01) # 10ms
# Send end signal when session ends
audio_queue.put(None)
logger.bind(tag=TAG).debug(f"[AUDIO-FEEDER] Sent end signal for {session_id}")
except Exception as e:
logger.bind(tag=TAG).error(f"[AUDIO-FEEDER] Error in feeder for {session_id}: {e}")
finally:
logger.bind(tag=TAG).debug(f"[AUDIO-FEEDER] Audio feeder finished for {session_id}")
# Start audio feeder in separate thread
feeder_thread = threading.Thread(target=audio_feeder, daemon=True)
feeder_thread.start()
# Start streaming recognition
logger.bind(tag=TAG).info(f"[STREAM-TASK] Starting Google API streaming for {session_id}")
responses = self.client.streaming_recognize(audio_generator())
# Process responses
response_count = 0
for response in responses:
if not session_data['session_active']:
logger.bind(tag=TAG).info(f"[STREAM-TASK] Session {session_id} no longer active, stopping")
break
response_count += 1
logger.bind(tag=TAG).debug(f"[STREAM-TASK] Processing response #{response_count} for {session_id}")
# Process recognition results
for result in response.results:
if result.alternatives:
transcript = result.alternatives[0].transcript
confidence = getattr(result.alternatives[0], 'confidence', 0.0)
if result.is_final:
session_data['final_transcript'] += transcript + " "
session_data['partial_transcript'] = ""
logger.bind(tag=TAG).info(f"[STREAM-TASK] FINAL transcript for {session_id}: '{transcript}' (confidence: {confidence:.2f})")
else:
session_data['partial_transcript'] = transcript
logger.bind(tag=TAG).debug(f"[STREAM-TASK] PARTIAL transcript for {session_id}: '{transcript}'")
logger.bind(tag=TAG).info(f"[STREAM-TASK] Completed streaming for {session_id} (processed {response_count} responses)")
except Exception as e:
logger.bind(tag=TAG).error(f"[STREAM-TASK] Error in streaming task for {session_id}: {e}")
import traceback
logger.bind(tag=TAG).error(f"[STREAM-TASK] Traceback: {traceback.format_exc()}")
finally:
logger.bind(tag=TAG).info(f"[STREAM-TASK] Streaming task ended for {session_id}")
async def stream_audio_chunk(self, conn, audio_chunk: bytes, session_id: str) -> Optional[str]:
"""Stream an audio chunk to the active ASR session.
Args:
conn: Connection object
audio_chunk: PCM audio data to stream
session_id: Session identifier
Returns:
Latest partial transcript if available, None otherwise
"""
logger.bind(tag=TAG).info(f"[STREAM-AUDIO] stream_audio_chunk called for {session_id} with {len(audio_chunk)} bytes")
try:
if session_id not in self.streaming_sessions:
logger.bind(tag=TAG).warning(f"[STREAM-AUDIO] No active streaming session for {session_id}")
return None
session_data = self.streaming_sessions[session_id]
session_data['audio_count'] += 1
# Add audio chunk directly to buffer
session_data['audio_buffer'].append(audio_chunk)
logger.bind(tag=TAG).info(f"[STREAM-AUDIO] Added audio chunk #{session_data['audio_count']} ({len(audio_chunk)} bytes) to session {session_id}. Buffer size: {len(session_data['audio_buffer'])}")
# Return latest partial transcript if available
partial = session_data.get('partial_transcript', '')
if partial:
logger.bind(tag=TAG).debug(f"[STREAM-AUDIO] Returning partial transcript for {session_id}: '{partial}'")
return partial
return None
except Exception as e:
logger.bind(tag=TAG).error(f"[STREAM-AUDIO] Error streaming audio chunk for {session_id}: {e}")
return None
async def end_streaming_session(self, conn, session_id: str) -> Tuple[str, Optional[str]]:
"""End the streaming ASR session and get final transcript.
Args:
conn: Connection object
session_id: Session identifier
Returns:
Tuple of (final_transcript, file_path)
"""
try:
if session_id not in self.streaming_sessions:
logger.bind(tag=TAG).warning(f"[STREAM-END] No active streaming session for {session_id}")
return "", None
session_data = self.streaming_sessions[session_id]
logger.bind(tag=TAG).info(f"[STREAM-END] Ending streaming session: {session_id}")
# Signal end of audio stream
session_data['session_active'] = False
logger.bind(tag=TAG).debug(f"[STREAM-END] Marked session {session_id} as inactive")
# Wait for streaming task to complete
if session_data['streaming_task']:
try:
logger.bind(tag=TAG).debug(f"[STREAM-END] Waiting for streaming task to complete for {session_id}")
await asyncio.wait_for(session_data['streaming_task'], timeout=3.0)
logger.bind(tag=TAG).debug(f"[STREAM-END] Streaming task completed for {session_id}")
except asyncio.TimeoutError:
logger.bind(tag=TAG).warning(f"[STREAM-END] Streaming task timeout for {session_id}, cancelling")
session_data['streaming_task'].cancel()
try:
await session_data['streaming_task']
except asyncio.CancelledError:
pass
# Get final transcript
final_transcript = session_data.get('final_transcript', '').strip()
audio_count = session_data.get('audio_count', 0)
logger.bind(tag=TAG).info(f"[STREAM-END] Session {session_id} processed {audio_count} audio chunks")
logger.bind(tag=TAG).info(f"[STREAM-END] Final transcript for {session_id}: '{final_transcript}'")
# Clean up session
del self.streaming_sessions[session_id]
return final_transcript, None
except Exception as e:
logger.bind(tag=TAG).error(f"[STREAM-END] Error ending streaming session {session_id}: {e}")
import traceback
logger.bind(tag=TAG).error(f"[STREAM-END] Traceback: {traceback.format_exc()}")
return "", None

View file

@ -0,0 +1,323 @@
# MQTT Gateway Communication Flow & Message Types
This document provides a comprehensive analysis of the MQTT gateway communication flow and all message types exchanged between the main server (xiaozhi-server), MQTT gateway, and clients.
## 🔄 Communication Architecture
```
┌─────────────────┐ WebSocket ┌─────────────────┐ MQTT ┌─────────────────┐
│ Main Server │ ◄──────────────► │ MQTT Gateway │ ◄─────────► │ Client │
│ (xiaozhi-server)│ │ (Node.js) │ │ (ESP32/Test) │
└─────────────────┘ └─────────────────┘ └─────────────────┘
│
▼
┌─────────────────┐
│ UDP Audio │
│ Streaming │
└─────────────────┘
```
### Key Components:
1. **Main Server (xiaozhi-server)**: Python-based AI server handling TTS/STT/LLM processing
2. **MQTT Gateway**: Node.js bridge converting between WebSocket (server) and MQTT (client)
3. **Client**: ESP32 device or test client connecting via MQTT
4. **UDP Audio Stream**: Encrypted real-time audio data transmission
## 📤 Message Flow Triggers
### 1. Client → MQTT Gateway → Server
Clients publish to the `"device-server"` topic, which the MQTT gateway forwards to the main server via WebSocket:
```javascript
// Client publishes to "device-server" topic
mqtt_client.publish("device-server", JSON.stringify({
"type": "hello",
"version": 3,
"transport": "mqtt",
"audio_params": {...},
"features": [...]
}))
```
### 2. Server → MQTT Gateway → Client
The server sends messages via WebSocket to the MQTT gateway, which publishes to the client's unique P2P topic:
```javascript
// Gateway publishes to client's P2P topic: "devices/p2p/{mac_address}"
connection.sendMqttMessage(JSON.stringify({
"type": "tts",
"state": "start",
"session_id": session_id
}))
```
### 3. Audio Streaming (Server ↔ Client)
Real-time audio data bypasses MQTT and flows directly via encrypted UDP packets for low latency.
## 📨 Complete MQTT Message Types
### 🔄 Connection & Session Management
#### 1. `hello` - Session Initiation
**Direction**: Client → Server, Server → Client
**Purpose**: Establish session and exchange capabilities
**Client Request:**
```json
{
"type": "hello",
"version": 3,
"transport": "mqtt",
"audio_params": {
"sample_rate": 16000,
"channels": 1,
"frame_duration": 20,
"format": "opus"
},
"features": ["tts", "asr", "vad"]
}
```
**Server Response:**
```json
{
"type": "hello",
"version": 3,
"session_id": "db4ead3e-c5e2-4dd4-bbf1-0295195e5058",
"transport": "udp",
"udp": {
"server": "64.227.170.31",
"port": 8884,
"encryption": "aes-128-ctr",
"key": "b6e228c4e0f5d0b93e6fac787786d303",
"nonce": "010000008e863dda0000000000000000"
},
"audio_params": {
"sample_rate": 16000,
"channels": 1,
"frame_duration": 20,
"format": "opus"
}
}
```
#### 2. `goodbye` - Session Termination
**Direction**: Client ↔ Server
**Purpose**: Clean session termination
```json
{
"type": "goodbye",
"session_id": "db4ead3e-c5e2-4dd4-bbf1-0295195e5058"
}
```
### 🎤 Speech Recognition Messages
#### 3. `stt` - Speech-to-Text Results
**Direction**: Server → Client
**Purpose**: Send transcribed speech back to client
```json
{
"type": "stt",
"text": "hello baby",
"session_id": "db4ead3e-c5e2-4dd4-bbf1-0295195e5058"
}
```
#### 4. `listen` - Request Speech Processing
**Direction**: Client → Server
**Purpose**: Request server to start listening/processing speech
```json
{
"type": "listen",
"session_id": "db4ead3e-c5e2-4dd4-bbf1-0295195e5058",
"state": "detect",
"text": "hello baby"
}
```
### 🔊 Text-to-Speech Control Messages
#### 5. `tts` - TTS Playback Control
**Direction**: Server → Client
**Purpose**: Control TTS playback states
**Available States**: `start`, `sentence_start`, `stop`
**TTS Start:**
```json
{
"type": "tts",
"state": "start",
"session_id": "db4ead3e-c5e2-4dd4-bbf1-0295195e5058"
}
```
**Sentence Start (with text preview):**
```json
{
"type": "tts",
"state": "sentence_start",
"session_id": "db4ead3e-c5e2-4dd4-bbf1-0295195e5058",
"text": "Hi there"
}
```
**TTS Stop:**
```json
{
"type": "tts",
"state": "stop",
"session_id": "db4ead3e-c5e2-4dd4-bbf1-0295195e5058"
}
```
**Note**: There is no `sentence_stop` or `sentence_end` state. Individual sentences are marked with `sentence_start`, and the entire TTS session ends with `stop`.
### 🤖 AI Response Messages
#### 6. `llm` - Large Language Model Response
**Direction**: Server → Client
**Purpose**: Send AI-generated response with emotion context
```json
{
"type": "llm",
"text": "😊",
"emotion": "happy",
"session_id": "db4ead3e-c5e2-4dd4-bbf1-0295195e5058"
}
```
### ⏹️ Control Messages
#### 7. `abort` - Abort Current Operation
**Direction**: Client → Server
**Purpose**: Stop current TTS playback or processing
```json
{
"type": "abort",
"session_id": "db4ead3e-c5e2-4dd4-bbf1-0295195e5058"
}
```
#### 8. `record_stop` - Stop Audio Recording
**Direction**: Server → Client
**Purpose**: Instruct client to stop recording audio
```json
{
"type": "record_stop",
"session_id": "db4ead3e-c5e2-4dd4-bbf1-0295195e5058"
}
```
## 🎯 Server Message Trigger Points
### In `core/handle/sendAudioHandle.py`:
- **`send_tts_message()`**: Triggers TTS state messages (`start`, `sentence_start`, `stop`)
- **`send_stt_message()`**: Triggers STT transcription messages
- **`sendAudioMessage()`**: Coordinates TTS playback with state messages
- Called during the audio processing pipeline
### In `core/handle/helloHandle.py`:
- **`handleHelloMessage()`**: Triggers the initial hello response with session details
- **`checkWakeupWords()`**: Can trigger STT and TTS messages for wake word responses
- **`wakeupWordsResponse()`**: Generates dynamic wake word responses
### In MQTT Gateway (`mqtt-gateway/app.js`):
- **`parseHelloMessage()`**: Processes hello messages and sends session details
- **`parseOtherMessage()`**: Forwards messages between server and client
- **`sendMqttMessage()`**: Publishes messages to client's P2P topic
- **`sendUdpMessage()`**: Handles encrypted audio streaming via UDP
## 📊 Typical Message Flow Sequence
### 1. Session Establishment
```
Client → MQTT Gateway: hello (with capabilities)
MQTT Gateway → Server: hello (forwarded via WebSocket)
Server → MQTT Gateway: hello (with session_id and UDP details)
MQTT Gateway → Client: hello (published to P2P topic)
```
### 2. Audio Setup
```
Client: Establishes UDP connection using provided encryption keys
Client: Sends UDP ping to confirm connection
```
### 3. Conversation Flow
```
Client → Server: listen (request to start conversation)
Server → Client: stt (transcription of client speech)
Server → Client: tts (state: "start")
Server → Client: tts (state: "sentence_start", text: preview)
Server → Client: llm (AI response with emotion)
Server ⟶ Client: [UDP Audio Stream] (actual TTS audio)
Server → Client: tts (state: "stop")
```
### 4. Session Termination
```
Client → Server: goodbye
Server → Client: goodbye (acknowledgment)
```
## 🔧 Implementation Details
### MQTT Topics
- **Uplink**: `device-server` (client to server messages)
- **Downlink**: `devices/p2p/{mac_address}` (server to specific client)
### Audio Streaming
- **Protocol**: UDP with AES-128-CTR encryption
- **Format**: Opus codec, 16kHz, mono
- **Frame Duration**: 20ms per packet
- **Encryption**: Header used as nonce, payload encrypted
### Session Management
- **Session ID**: UUID generated for each connection
- **Authentication**: HMAC-SHA256 signed client credentials
- **Keep-alive**: MQTT ping/pong mechanism
### Error Handling
- **Timeout**: Automatic retry for failed messages
- **Connection Loss**: Graceful degradation and reconnection
- **Audio Issues**: Buffer management for packet loss
## 🚨 Key Observations
- **Hybrid Protocol**: MQTT for control messages, UDP for real-time audio streaming
- **Session-based**: All messages include `session_id` for correlation
- **Bidirectional**: Both client and server can initiate certain message types
- **State Machine**: TTS has multiple states for precise playback control
- **Real-time Audio**: Audio packets bypass MQTT for optimal latency
- **P2P Topics**: Each client has a unique MQTT topic for targeted messaging
- **Encryption**: End-to-end encryption for audio data
- **Scalable**: Architecture supports multiple concurrent clients
## 📚 Related Files
### Server-side:
- `core/handle/sendAudioHandle.py` - TTS/STT message handling
- `core/handle/helloHandle.py` - Session establishment
- `core/websocket_server.py` - WebSocket connection management
### MQTT Gateway:
- `mqtt-gateway/app.js` - Main gateway implementation
- `mqtt-gateway/mqtt-protocol.js` - MQTT protocol handling
- `mqtt-gateway/utils/mqtt_config_v2.js` - Client authentication
### Client:
- `client.py` - Test client implementation
- Client logs show actual message flow in practice
---
*Generated on: 2025-09-12*
*Analysis based on xiaozhi-esp32-server codebase and client logs*

View file

@ -1,194 +1,376 @@
{
"Baa Baa Black Sheep": {
"romanized": "Baa Baa Black Sheep",
"filename": "Baa Baa Black Sheep.mp3",
"alternatives": [
"Baa Baa Black Sheep",
"baa baa black sheep",
"black sheep song",
"sheep song",
"nursery rhyme sheep",
"wool song",
"classic nursery rhyme",
"baa baa"
]
},
"Baby Shark Dance": {
"romanized": "Baby Shark Dance",
"filename": "Baby Shark Dance.mp3",
"alternatives": [
"Baby Shark Dance",
"baby shark",
"shark song",
"doo doo doo",
"baby shark family",
"shark dance",
"kids shark song",
"popular kids song",
"viral kids song"
]
},
"Five Little Animals": {
"romanized": "Five Little Animals",
"filename": "Five Little Animals.mp3",
"alternatives": [
"Five Little Animals",
"five animals",
"little animals",
"counting animals",
"animal counting song",
"5 little animals",
"animals song",
"counting song"
]
},
"Five Little Ducks": {
"romanized": "Five Little Ducks",
"filename": "Five Little Ducks.mp3",
"alternatives": [
"Five Little Ducks",
"five ducks",
"little ducks",
"duck song",
"counting ducks",
"5 little ducks",
"ducks went swimming",
"mother duck song",
"quack quack song"
]
},
"Once I Caught A Fish Alive": {
"romanized": "Once I Caught A Fish Alive",
"filename": "Once I Caught A Fish Alive.mp3",
"alternatives": [
"Once I Caught A Fish Alive",
"fish alive",
"caught a fish",
"fishing song",
"fish counting song",
"1 2 3 4 5 fish",
"counting fish",
"fish nursery rhyme"
]
},
"Ten Little Dinos": {
"romanized": "Ten Little Dinos",
"filename": "Ten Little Dinos.mp3",
"alternatives": [
"Ten Little Dinos",
"ten dinos",
"little dinosaurs",
"dinosaur song",
"counting dinosaurs",
"10 little dinos",
"dino counting song",
"prehistoric song",
"kids dinosaur song"
]
},
"The Wheels on the Bus": {
"romanized": "The Wheels on the Bus",
"filename": "The Wheels on the Bus.mp3",
"alternatives": [
"The Wheels on the Bus",
"wheels on the bus",
"bus song",
"wheels go round and round",
"children's bus song",
"classic kids song",
"nursery rhyme bus",
"preschool bus song",
"traditional children's song",
"kids transport song",
"bus wheels song",
"go round and round"
]
"Baa Baa Black Sheep": {
"romanized": "Baa Baa Black Sheep",
"filename": "Baa Baa Black Sheep.mp3",
"alternatives": [
"Baa Baa Black Sheep",
"baa baa black sheep",
"black sheep song",
"sheep song",
"nursery rhyme sheep",
"wool song",
"classic nursery rhyme",
"baa baa"
]
},
"Head Shoulders Knees and Toes": {
"romanized": "Head Shoulders Knees and Toes",
"filename": "Head, Shoulders, Knees and Toes.mp3",
"alternatives": [
"head shoulders knees and toes",
"body parts song",
"action song",
"exercise song",
"kids body song",
"nursery action song",
"movement song",
"body song"
]
},
"Hot Cross Buns": {
"romanized": "Hot Cross Buns",
"filename": "Hot Cross Buns.mp3",
"alternatives": [
"hot cross buns",
"easter song",
"buns song",
"one a penny",
"two a penny",
"traditional nursery rhyme",
"food song",
"classic rhyme"
]
},
"I'm A Little Teapot": {
"romanized": "I'm A Little Teapot",
"filename": "I'm A Little Teapot.mp3",
"alternatives": [
"i'm a little teapot",
"little teapot",
"teapot song",
"short and stout",
"tip me over",
"pour me out",
"action nursery rhyme",
"tea song"
]
},
"Johny Johny Yes Papa": {
"romanized": "Johny Johny Yes Papa",
"filename": "Johny Johny Yes Papa.mp3",
"alternatives": [
"johny johny yes papa",
"johnny johnny",
"yes papa",
"eating sugar",
"no papa",
"telling lies",
"open your mouth",
"ha ha ha",
"popular kids song"
]
},
"Rain Rain Go Away": {
"romanized": "Rain Rain Go Away",
"filename": "Rain rain go away.mp3",
"alternatives": [
"rain rain go away",
"come again another day",
"rain song",
"weather song",
"little johnny wants to play",
"rainy day song",
"nursery weather song",
"rain rhyme"
]
},
"Twinkle Twinkle Little Star": {
"romanized": "Twinkle Twinkle Little Star",
"filename": "Twinkle Twinkle Little Star.mp3",
"alternatives": [
"twinkle twinkle little star",
"twinkle twinkle",
"little star",
"how i wonder what you are",
"star song",
"night song",
"lullaby",
"classic nursery rhyme",
"bedtime song",
"diamond in the sky"
]
}
}
"Baby Shark Dance": {
"romanized": "Baby Shark Dance",
"filename": "Baby Shark Dance.mp3",
"alternatives": [
"Baby Shark Dance",
"baby shark",
"shark song",
"doo doo doo",
"baby shark family",
"shark dance",
"kids shark song",
"popular kids song",
"viral kids song"
]
},
"Five Little Animals": {
"romanized": "Five Little Animals",
"filename": "Five Little Animals.mp3",
"alternatives": [
"Five Little Animals",
"five animals",
"little animals",
"counting animals",
"animal counting song",
"5 little animals",
"animals song",
"counting song"
]
},
"Five Little Ducks": {
"romanized": "Five Little Ducks",
"filename": "Five Little Ducks.mp3",
"alternatives": [
"Five Little Ducks",
"five ducks",
"little ducks",
"duck song",
"counting ducks",
"5 little ducks",
"ducks went swimming",
"mother duck song",
"quack quack song"
]
},
"Once I Caught A Fish Alive": {
"romanized": "Once I Caught A Fish Alive",
"filename": "Once I Caught A Fish Alive.mp3",
"alternatives": [
"Once I Caught A Fish Alive",
"fish alive",
"caught a fish",
"fishing song",
"fish counting song",
"1 2 3 4 5 fish",
"counting fish",
"fish nursery rhyme"
]
},
"Ten Little Dinos": {
"romanized": "Ten Little Dinos",
"filename": "Ten Little Dinos.mp3",
"alternatives": [
"Ten Little Dinos",
"ten dinos",
"little dinosaurs",
"dinosaur song",
"counting dinosaurs",
"10 little dinos",
"dino counting song",
"prehistoric song",
"kids dinosaur song"
]
},
"The Wheels on the Bus": {
"romanized": "The Wheels on the Bus",
"filename": "The Wheels on the Bus.mp3",
"alternatives": [
"The Wheels on the Bus",
"wheels on the bus",
"bus song",
"wheels go round and round",
"children's bus song",
"classic kids song",
"nursery rhyme bus",
"preschool bus song",
"traditional children's song",
"kids transport song",
"bus wheels song",
"go round and round"
]
},
"Head Shoulders Knees and Toes": {
"romanized": "Head Shoulders Knees and Toes",
"filename": "Head, Shoulders, Knees and Toes.mp3",
"alternatives": [
"head shoulders knees and toes",
"body parts song",
"action song",
"exercise song",
"kids body song",
"nursery action song",
"movement song",
"body song"
]
},
"Hot Cross Buns": {
"romanized": "Hot Cross Buns",
"filename": "Hot Cross Buns.mp3",
"alternatives": [
"hot cross buns",
"easter song",
"buns song",
"one a penny",
"two a penny",
"traditional nursery rhyme",
"food song",
"classic rhyme"
]
},
"I'm A Little Teapot": {
"romanized": "I'm A Little Teapot",
"filename": "I'm A Little Teapot.mp3",
"alternatives": [
"i'm a little teapot",
"little teapot",
"teapot song",
"short and stout",
"tip me over",
"pour me out",
"action nursery rhyme",
"tea song"
]
},
"Johny Johny Yes Papa": {
"romanized": "Johny Johny Yes Papa",
"filename": "Johny Johny Yes Papa.mp3",
"alternatives": [
"johny johny yes papa",
"johnny johnny",
"yes papa",
"eating sugar",
"no papa",
"telling lies",
"open your mouth",
"ha ha ha",
"popular kids song"
]
},
"Rain Rain Go Away": {
"romanized": "Rain Rain Go Away",
"filename": "Rain rain go away.mp3",
"alternatives": [
"rain rain go away",
"come again another day",
"rain song",
"weather song",
"little johnny wants to play",
"rainy day song",
"nursery weather song",
"rain rhyme"
]
},
"Twinkle Twinkle Little Star": {
"romanized": "Twinkle Twinkle Little Star",
"filename": "Twinkle Twinkle Little Star.mp3",
"alternatives": [
"twinkle twinkle little star",
"twinkle twinkle",
"little star",
"how i wonder what you are",
"star song",
"night song",
"lullaby",
"classic nursery rhyme",
"bedtime song",
"diamond in the sky"
]
},
"River Woods": {
"romanized": "River Woods",
"filename": "River Woods.mp3",
"alternatives": [
"river woods",
"nature song",
"forest song",
"woodland song",
"river song",
"outdoor song",
"kids nature song"
]
},
"Hickory": {
"romanized": "Hickory",
"filename": "Hickory.mp3",
"alternatives": [
"hickory",
"hickory dickory dock",
"mouse ran up the clock",
"clock song",
"time song",
"mouse song",
"classic nursery rhyme"
]
},
"Mary Lamb": {
"romanized": "Mary Lamb",
"filename": "Mary Lamb.mp3",
"alternatives": [
"mary had a little lamb",
"little lamb",
"lamb song",
"mary lamb",
"fleece was white as snow",
"school song",
"classic nursery rhyme"
]
},
"One Two": {
"romanized": "One Two",
"filename": "One Two.mp3",
"alternatives": [
"one two",
"buckle my shoe",
"counting song",
"number song",
"1 2 buckle my shoe",
"learning numbers",
"counting rhyme"
]
},
"Bingo": {
"romanized": "Bingo",
"filename": "Bingo.mp3",
"alternatives": [
"bingo",
"b-i-n-g-o",
"farmer had a dog",
"dog song",
"spelling song",
"letter song",
"classic nursery rhyme"
]
},
"Hush Baby": {
"romanized": "Hush Baby",
"filename": "Hush Baby.mp3",
"alternatives": [
"hush baby",
"hush little baby",
"don't say a word",
"mockingbird",
"lullaby",
"bedtime song",
"sleep song"
]
},
"Happy": {
"romanized": "Happy",
"filename": "Happy.mp3",
"alternatives": [
"happy",
"if you're happy and you know it",
"clap your hands",
"action song",
"movement song",
"kids activity song"
]
},
"Sleeping": {
"romanized": "Sleeping",
"filename": "Sleeping.mp3",
"alternatives": [
"sleeping",
"are you sleeping",
"brother john",
"frere jacques",
"morning bells",
"wake up song",
"lullaby"
]
},
"Hokey": {
"romanized": "Hokey",
"filename": "Hokey.mp3",
"alternatives": [
"hokey",
"hokey pokey",
"put your right hand in",
"shake it all about",
"action song",
"dance song",
"movement song"
]
},
"ABC Song": {
"romanized": "ABC Song",
"filename": "ABC Song.mp3",
"alternatives": [
"abc song",
"alphabet song",
"a b c d e f g",
"learning letters",
"alphabet",
"letter song",
"educational song"
]
},
"Splashing In The Sea Numbers": {
"romanized": "Splashing In The Sea Numbers",
"filename": "Splashing In The Sea Numbers.mp3",
"alternatives": [
"splashing in the sea",
"sea numbers",
"ocean counting",
"water song",
"beach song",
"counting song",
"sea creatures"
]
},
"Five Little Monkeys Jumping On The Bed": {
"romanized": "Five Little Monkeys Jumping On The Bed",
"filename": "Five Little Monkeys Jumping On The Bed.mp3",
"alternatives": [
"five little monkeys",
"jumping on the bed",
"monkeys jumping",
"one fell off",
"no more monkeys",
"counting monkeys",
"bedtime story song"
]
},
"Five Little Piggies Jumping On The Bed": {
"romanized": "Five Little Piggies Jumping On The Bed",
"filename": "Five Little Piggies Jumping On The Bed.mp3",
"alternatives": [
"five little piggies",
"piggies jumping on bed",
"little pigs jumping",
"pig song",
"counting pigs",
"farm animals",
"bedtime song"
]
},
"Old MacDonald": {
"romanized": "Old MacDonald",
"filename": "Old MacDonald.mp3",
"alternatives": [
"old macdonald",
"had a farm",
"e-i-e-i-o",
"farm song",
"animal sounds",
"cow goes moo",
"farm animals",
"classic nursery rhyme"
]
}
}

View file

@ -449,7 +449,9 @@ def initialize_multilingual_music_system(conn):
if SEMANTIC_SEARCH is None:
try:
semantic_config = conn.config.get('semantic_search', {})
if semantic_config.get('enabled', True):
SEMANTIC_SEARCH = SemanticMusicSearch(semantic_config)
if SEMANTIC_SEARCH.initialize():
conn.logger.bind(tag=TAG).info("Semantic music search initialized successfully")

View file

@ -1,839 +1,3 @@
# import os
# import re
# import time
# import random
# import difflib
# import traceback
# from pathlib import Path
# from core.handle.sendAudioHandle import send_stt_message
# from plugins_func.register import register_function, ToolType, ActionResponse, Action
# from core.utils.dialogue import Message
# from core.providers.tts.dto.dto import TTSMessageDTO, SentenceType, ContentType
# from plugins_func.utils.multilingual_matcher import MultilingualMatcher
# # S3 Streaming imports
# import boto3
# from botocore.exceptions import ClientError
# import logging
# # CDN Download imports
# from core.utils.cdn_manager import download_cdn_file
# TAG = __name__
# STORY_CACHE = {}
# STORY_MULTILINGUAL_MATCHER = None
# # S3 Configuration
# S3_CLIENT = None
# S3_BUCKET_NAME = "cheeko-audio-files"
# # Story categories mapping for better recognition
# STORY_CATEGORIES = {
# "bedtime": ["Bedtime", "bedtime story", "sleep story", "night story"],
# "fantasy": ["Fantasy", "fantasy story", "magical story", "magic story"],
# "fairy tales": ["Fairy Tales", "fairy tale", "fairytale"],
# "educational": ["Educational", "educational story", "learning story", "education"],
# "adventure": ["Adventure", "adventure story", "exciting story"]
# }
# play_story_function_desc = {
# "type": "function",
# "function": {
# "name": "play_story",
# "description": (
# "CRITICAL: This function ONLY plays pre-recorded story audio files from the stories folder. "
# "NEVER generate, create, or tell stories using text. ALWAYS call this function for ANY story request. "
# "This plays actual audio story files, not generated text stories. "
# "MANDATORY: Use this function for ALL story requests including: 'tell me a story', 'story please', "
# "'I want to hear a story', 'play a bedtime story', 'tell me The Boy Who Cried Wolf', etc. "
# "DO NOT create stories with text - only play pre-recorded audio story files. "
# "Examples: 'tell me a story' → play random story file, 'bedtime story' → play bedtime category file, "
# "'कहानी सुनाओ' (Hindi) → play story file, 'ಕಥೆ ಹೇಳಿ' (Kannada) → play story file"
# ),
# "parameters": {
# "type": "object",
# "properties": {
# "user_request": {
# "type": "string",
# "description": "Complete user request for story. Examples: 'tell me a story', 'tell me The Boy Who Cried Wolf story', 'play a bedtime story', 'I want to hear a fantasy story', 'story please', 'कहानी सुनाओ', 'ಕಥೆ ಹೇಳಿ'",
# },
# "story_type": {
# "type": "string",
# "enum": ["specific", "category", "random"],
# "description": "Use 'specific' for ANY story title, name, or specific story request (e.g., 'golden gift story', 'The Boy Who Cried Wolf', 'Cinderella', 'three little pigs'). Use 'category' for category requests like 'bedtime story', 'fantasy story'. Use 'random' ONLY for very general requests like 'tell me any story', 'play a story'."
# },
# "category_preference": {
# "type": "string",
# "description": "Story category if mentioned: 'bedtime', 'fantasy', 'fairy tales', 'educational', 'adventure'. Only set if explicitly mentioned.",
# },
# "requested_language": {
# "type": "string",
# "description": "Language user requested the story in (e.g., 'hindi', 'english', 'kannada'). Note: Stories may be available in multiple languages depending on metadata.",
# }
# },
# "required": ["user_request", "story_type"],
# },
# },
# }
# @register_function("play_story", play_story_function_desc, ToolType.SYSTEM_CTL)
# def play_story(conn, user_request: str, story_type: str = "random", category_preference: str = None, requested_language: str = None):
# try:
# # Initialize multilingual story system
# initialize_multilingual_story_system(conn)
# # Log the request for debugging
# conn.logger.bind(tag=TAG).info(f"Story request: '{user_request}', type: {story_type}, category: {category_preference}, language: {requested_language}")
# # Check event loop status
# if not conn.loop.is_running():
# conn.logger.bind(tag=TAG).error("Event loop not running, cannot submit task")
# return ActionResponse(
# action=Action.RESPONSE, result="System busy", response="Please try again later"
# )
# # Submit async task with enhanced parameters
# task = conn.loop.create_task(
# handle_multilingual_story_command(conn, user_request, story_type, category_preference, requested_language)
# )
# # Non-blocking callback handling
# def handle_done(f):
# try:
# f.result()
# conn.logger.bind(tag=TAG).info("Multilingual story playback completed")
# except Exception as e:
# conn.logger.bind(tag=TAG).error(f"Multilingual story playback failed: {e}")
# task.add_done_callback(handle_done)
# return ActionResponse(
# action=Action.NONE,
# result="Multilingual story command received",
# response="Let me find a wonderful story for you!"
# )
# except Exception as e:
# conn.logger.bind(tag=TAG).error(f"Error handling multilingual story request: {e}")
# return ActionResponse(
# action=Action.RESPONSE, result=str(e), response="Error occurred while processing your story request"
# )
# def normalize_category_name(category_input):
# """Normalize story category name to match folder names"""
# if not category_input:
# return None
# category_lower = category_input.lower().strip()
# # Direct mapping for exact matches from LLM
# direct_mappings = {
# "bedtime": "Bedtime",
# "fantasy": "Fantasy",
# "fairy tales": "Fairy Tales",
# "educational": "Educational",
# "adventure": "Adventure",
# "random": None # None means select random category
# }
# # Check direct mappings first
# if category_lower in direct_mappings:
# return direct_mappings[category_lower]
# # Check against category variations
# for key, variations in STORY_CATEGORIES.items():
# for variation in variations:
# if variation.lower() in category_lower or category_lower in variation.lower():
# # Return the actual folder name
# if key == "bedtime":
# return "Bedtime"
# elif key == "fantasy":
# return "Fantasy"
# elif key == "fairy tales":
# return "Fairy Tales"
# elif key == "educational":
# return "Educational"
# elif key == "adventure":
# return "Adventure"
# # If no match, return None to trigger random selection
# return None
# def get_story_files(story_dir, story_ext):
# """Get all story files organized by category - S3 MODE: Read from metadata.json"""
# import json
# story_dir = Path(story_dir)
# story_files_by_category = {}
# all_story_files = []
# # Check if stories directory exists
# if not story_dir.exists():
# return {}, []
# # Iterate through category folders
# for category_folder in story_dir.iterdir():
# if category_folder.is_dir():
# category_name = category_folder.name
# story_files_by_category[category_name] = []
# # Check for metadata.json file first (S3 mode)
# metadata_file = category_folder / "metadata.json"
# if metadata_file.exists():
# try:
# with open(metadata_file, 'r', encoding='utf-8') as f:
# metadata = json.load(f)
# # Add stories from metadata
# for story_title, story_info in metadata.items():
# filename = story_info.get('filename', f"{story_title}.mp3")
# relative_path = f"{category_name}/{filename}"
# story_files_by_category[category_name].append(relative_path)
# all_story_files.append(relative_path)
# logging.info(f"Loaded {len(metadata)} stories from {category_name} metadata")
# continue
# except Exception as e:
# logging.error(f"Error reading metadata from {metadata_file}: {e}")
# # Fallback: scan for actual audio files (legacy mode)
# for file in category_folder.rglob("*"):
# if file.is_file():
# ext = file.suffix.lower()
# if ext in story_ext:
# relative_path = str(file.relative_to(story_dir))
# story_files_by_category[category_name].append(relative_path)
# all_story_files.append(relative_path)
# return story_files_by_category, all_story_files
# def initialize_s3_client():
# """Initialize S3 client for streaming with SigV4"""
# global S3_CLIENT
# if S3_CLIENT is None:
# try:
# from botocore.config import Config
# aws_access_key = os.getenv('AWS_ACCESS_KEY_ID')
# aws_secret_key = os.getenv('AWS_SECRET_ACCESS_KEY')
# aws_region = os.getenv('AWS_DEFAULT_REGION', 'us-east-1')
# if aws_access_key and aws_secret_key:
# S3_CLIENT = boto3.client(
# 's3',
# aws_access_key_id=aws_access_key,
# aws_secret_access_key=aws_secret_key,
# region_name=aws_region,
# config=Config(signature_version="s3v4")
# )
# logging.info(f"S3 client initialized for story streaming (region: {aws_region})")
# else:
# logging.warning("AWS credentials not found, S3 streaming disabled")
# except Exception as e:
# logging.error(f"Failed to initialize S3 client: {e}")
# S3_CLIENT = None
# def generate_cdn_story_url(category, filename):
# """Generate CDN streaming URL for story file"""
# try:
# # Import CDN helper
# from utils.cdn_helper import get_audio_url
# # Ensure proper capitalization for S3 key (S3 folders are capitalized)
# # Handle special cases like "Fairy Tales"
# if category.lower() == "fairy tales":
# category_capitalized = "Fairy Tales"
# else:
# category_capitalized = category.capitalize()
# audio_path = f"stories/{category_capitalized}/{filename}"
# # Use CDN helper to generate URL with automatic encoding
# cdn_url = get_audio_url(audio_path)
# logging.info(f"Generated CDN URL for story: {audio_path} -> {cdn_url}")
# return cdn_url
# except Exception as e:
# logging.error(f"Error generating CDN URL for story: {e}")
# # Fallback to S3 presigned URL if CDN fails
# return generate_s3_story_url_fallback(category, filename)
# def generate_s3_story_url_fallback(category, filename):
# """Fallback S3 streaming URL for story file"""
# global S3_CLIENT, S3_BUCKET_NAME
# if not S3_CLIENT:
# return None
# try:
# # Ensure proper capitalization for S3 key (S3 folders are capitalized)
# # Handle special cases like "Fairy Tales"
# if category.lower() == "fairy tales":
# category_capitalized = "Fairy Tales"
# else:
# category_capitalized = category.capitalize()
# s3_key = f"stories/{category_capitalized}/{filename}"
# url = S3_CLIENT.generate_presigned_url(
# 'get_object',
# Params={'Bucket': S3_BUCKET_NAME, 'Key': s3_key},
# ExpiresIn=7200 # 2 hours for streaming
# )
# logging.info(f"Generated fallback S3 URL for story: {s3_key}")
# return url
# except ClientError as e:
# logging.error(f"Error generating fallback S3 URL for story: {e}")
# return None
# def initialize_story_handler(conn):
# """Initialize story handler with configuration"""
# global STORY_CACHE
# # Initialize S3 client
# initialize_s3_client()
# if STORY_CACHE == {}:
# if "play_story" in conn.config["plugins"]:
# STORY_CACHE["story_config"] = conn.config["plugins"]["play_story"]
# STORY_CACHE["story_dir"] = os.path.abspath(
# STORY_CACHE["story_config"].get("story_dir", "./stories")
# )
# STORY_CACHE["story_ext"] = STORY_CACHE["story_config"].get(
# "story_ext", (".mp3", ".wav", ".p3")
# )
# STORY_CACHE["refresh_time"] = STORY_CACHE["story_config"].get(
# "refresh_time", 300 # Refresh every 5 minutes
# )
# else:
# STORY_CACHE["story_dir"] = os.path.abspath("./stories")
# STORY_CACHE["story_ext"] = (".mp3", ".wav", ".p3")
# STORY_CACHE["refresh_time"] = 300
# # Get story files organized by category
# STORY_CACHE["story_files_by_category"], STORY_CACHE["all_story_files"] = get_story_files(
# STORY_CACHE["story_dir"], STORY_CACHE["story_ext"]
# )
# STORY_CACHE["scan_time"] = time.time()
# # Log available categories
# if STORY_CACHE["story_files_by_category"]:
# conn.logger.bind(tag=TAG).info(
# f"Found story categories: {list(STORY_CACHE['story_files_by_category'].keys())}"
# )
# for category, files in STORY_CACHE["story_files_by_category"].items():
# conn.logger.bind(tag=TAG).info(f" {category}: {len(files)} stories")
# return STORY_CACHE
# def initialize_multilingual_story_system(conn):
# """Initialize the multilingual story matching system"""
# global STORY_MULTILINGUAL_MATCHER, STORY_CACHE
# # Initialize basic story cache first
# initialize_story_handler(conn)
# # Initialize multilingual matcher if not already done
# if STORY_MULTILINGUAL_MATCHER is None:
# try:
# STORY_MULTILINGUAL_MATCHER = MultilingualMatcher(
# STORY_CACHE["story_dir"],
# STORY_CACHE["story_ext"]
# )
# if STORY_MULTILINGUAL_MATCHER.language_folders:
# conn.logger.bind(tag=TAG).info(f"Multilingual story matcher initialized with languages: {STORY_MULTILINGUAL_MATCHER.language_folders}")
# else:
# conn.logger.bind(tag=TAG).info("Multilingual story matcher initialized (no metadata.json found, using filesystem fallback)")
# except Exception as e:
# conn.logger.bind(tag=TAG).error(f"Failed to initialize multilingual story matcher: {e}")
# STORY_MULTILINGUAL_MATCHER = None
# async def handle_multilingual_story_command(conn, user_request: str, story_type: str, category_preference: str = None, requested_language: str = None):
# """Enhanced story command handler with multilingual AI matching"""
# global STORY_MULTILINGUAL_MATCHER, STORY_CACHE
# conn.logger.bind(tag=TAG).debug(f"Processing multilingual story request: '{user_request}'")
# # Check if stories directory exists
# if not os.path.exists(STORY_CACHE["story_dir"]):
# conn.logger.bind(tag=TAG).error(f"Story directory does not exist: {STORY_CACHE['story_dir']}")
# await send_stt_message(conn, "Sorry, I couldn't find the story collection.")
# return
# # Refresh cache if needed
# if time.time() - STORY_CACHE["scan_time"] > STORY_CACHE["refresh_time"]:
# STORY_CACHE["story_files_by_category"], STORY_CACHE["all_story_files"] = get_story_files(
# STORY_CACHE["story_dir"], STORY_CACHE["story_ext"]
# )
# STORY_CACHE["scan_time"] = time.time()
# selected_story = None
# match_info = None
# # Try multilingual AI matching for specific stories
# if STORY_MULTILINGUAL_MATCHER and story_type == "specific":
# try:
# match_result = STORY_MULTILINGUAL_MATCHER.find_content_match(user_request, requested_language)
# if match_result:
# selected_story, detected_language, metadata_entry = match_result
# match_info = {
# 'method': 'ai_multilingual',
# 'language': detected_language,
# 'title': metadata_entry.get('romanized', 'Unknown'),
# 'original_title': list(STORY_MULTILINGUAL_MATCHER.metadata_cache[detected_language]['metadata'].keys())[
# list(STORY_MULTILINGUAL_MATCHER.metadata_cache[detected_language]['metadata'].values()).index(metadata_entry)
# ] if detected_language in STORY_MULTILINGUAL_MATCHER.metadata_cache else 'Unknown',
# 'category': 'unknown'
# }
# conn.logger.bind(tag=TAG).info(f"AI story match found: {selected_story} ({detected_language})")
# except Exception as e:
# conn.logger.bind(tag=TAG).error(f"Error in AI story matching: {e}")
# # Try language-specific selection if no AI match and language is specified
# if not selected_story and requested_language and STORY_MULTILINGUAL_MATCHER:
# try:
# language_content = STORY_MULTILINGUAL_MATCHER.get_language_specific_content(requested_language)
# if language_content:
# selected_path, metadata_entry = random.choice(language_content)
# selected_story = selected_path
# match_info = {
# 'method': 'language_random',
# 'language': requested_language,
# 'title': metadata_entry.get('romanized', 'Unknown'),
# 'category': 'unknown'
# }
# conn.logger.bind(tag=TAG).info(f"Language-specific story selection: {selected_story}")
# except Exception as e:
# conn.logger.bind(tag=TAG).error(f"Error in language-specific story selection: {e}")
# # Fallback to legacy category-based selection
# if not selected_story and category_preference:
# normalized_category = normalize_category_name(category_preference)
# if normalized_category and normalized_category in STORY_CACHE["story_files_by_category"]:
# if STORY_CACHE["story_files_by_category"][normalized_category]:
# selected_story = random.choice(STORY_CACHE["story_files_by_category"][normalized_category])
# match_info = {
# 'method': 'category_selection',
# 'language': 'english', # Default assumption
# 'title': os.path.splitext(os.path.basename(selected_story))[0],
# 'category': normalized_category
# }
# conn.logger.bind(tag=TAG).info(f"Category-based story selection: {selected_story}")
# # Try legacy specific story matching (for explicit specific requests)
# if not selected_story and story_type == "specific":
# # Extract story name and try fuzzy matching
# story_name_match = find_best_story_match(user_request, STORY_CACHE["all_story_files"])
# if story_name_match:
# selected_story = story_name_match
# match_info = {
# 'method': 'legacy_fuzzy',
# 'language': 'english',
# 'title': os.path.splitext(os.path.basename(selected_story))[0],
# 'category': selected_story.split(os.sep)[0] if os.sep in selected_story else 'unknown'
# }
# conn.logger.bind(tag=TAG).info(f"Legacy fuzzy story match: {selected_story}")
# # SMART FALLBACK: Try specific story matching even for "random" requests that might contain story names
# # This handles cases where LLM misclassifies specific story requests as random
# if not selected_story and story_type != "specific":
# # Check if the request might contain a specific story name by trying fuzzy matching
# story_name_match = find_best_story_match(user_request, STORY_CACHE["all_story_files"])
# if story_name_match:
# selected_story = story_name_match
# match_info = {
# 'method': 'smart_fallback_fuzzy',
# 'language': 'english',
# 'title': os.path.splitext(os.path.basename(selected_story))[0],
# 'category': selected_story.split(os.sep)[0] if os.sep in selected_story else 'unknown'
# }
# conn.logger.bind(tag=TAG).info(f"Smart fallback story match (LLM misclassified): {selected_story}")
# # Final fallback to random selection
# if not selected_story and STORY_CACHE["all_story_files"]:
# selected_story = random.choice(STORY_CACHE["all_story_files"])
# match_info = {
# 'method': 'random_fallback',
# 'language': 'english',
# 'title': os.path.splitext(os.path.basename(selected_story))[0],
# 'category': selected_story.split(os.sep)[0] if os.sep in selected_story else 'unknown'
# }
# conn.logger.bind(tag=TAG).info(f"Random story fallback: {selected_story}")
# # Play the selected story
# if selected_story:
# await play_multilingual_story(conn, selected_story, match_info, user_request)
# else:
# conn.logger.bind(tag=TAG).error("No stories found to play")
# await send_stt_message(conn, "Sorry, I couldn't find any stories to play.")
# async def play_multilingual_story(conn, selected_story: str, match_info: dict, original_request: str):
# """Play selected story with contextual introduction - CDN STREAMING VERSION"""
# global STORY_CACHE
# try:
# # Extract category and filename from selected_story path
# # selected_story format: "Fantasy/story.mp3" or "Adventure/story.mp3"
# path_parts = selected_story.split('/')
# if len(path_parts) >= 2:
# category = path_parts[0]
# filename = path_parts[1]
# else:
# # Fallback: try to get from match_info
# category = match_info.get('category', 'Fantasy')
# filename = os.path.basename(selected_story)
# # Generate CDN streaming URL
# cdn_url = generate_cdn_story_url(category, filename)
# if not cdn_url:
# conn.logger.bind(tag=TAG).error(f"Failed to generate CDN URL for: {category}/{filename}")
# await send_stt_message(conn, "Sorry, I couldn't access the story file.")
# return
# # CRITICAL CHANGE: Download from CDN to local file first
# local_file_path = await download_cdn_file(cdn_url, conn)
# if not local_file_path:
# conn.logger.bind(tag=TAG).error(f"Failed to download CDN file: {cdn_url}")
# await send_stt_message(conn, "Sorry, I couldn't download the story file.")
# return
# # Generate contextual introduction based on match info
# intro_text = generate_multilingual_story_intro(match_info, original_request)
# await send_stt_message(conn, intro_text)
# conn.dialogue.put(Message(role="assistant", content=intro_text))
# # Queue TTS messages with S3 URL
# if conn.intent_type == "intent_llm":
# conn.tts.tts_text_queue.put(
# TTSMessageDTO(
# sentence_id=conn.sentence_id,
# sentence_type=SentenceType.FIRST,
# content_type=ContentType.ACTION,
# )
# )
# conn.tts.tts_text_queue.put(
# TTSMessageDTO(
# sentence_id=conn.sentence_id,
# sentence_type=SentenceType.MIDDLE,
# content_type=ContentType.TEXT,
# content_detail=intro_text,
# )
# )
# # Use CDN URL instead of local file path
# conn.tts.tts_text_queue.put(
# TTSMessageDTO(
# sentence_id=conn.sentence_id,
# sentence_type=SentenceType.MIDDLE,
# content_type=ContentType.FILE,
# content_file=local_file_path, # LOCAL FILE, NOT CDN URL!
# )
# )
# if conn.intent_type == "intent_llm":
# conn.tts.tts_text_queue.put(
# TTSMessageDTO(
# sentence_id=conn.sentence_id,
# sentence_type=SentenceType.LAST,
# content_type=ContentType.ACTION,
# )
# )
# # CRITICAL FIX: Set llm_finish_task to True so stop signal is sent after story completes
# conn.llm_finish_task = True
# conn.logger.bind(tag=TAG).info(f"Streaming story from local cache: {local_file_path}")
# except Exception as e:
# conn.logger.bind(tag=TAG).error(f"Failed to stream story from CDN: {str(e)}")
# conn.logger.bind(tag=TAG).error(f"Detailed error: {traceback.format_exc()}")
# def generate_multilingual_story_intro(match_info: dict, original_request: str) -> str:
# """Generate contextual introduction based on matching method and info"""
# method = match_info.get('method', 'unknown')
# language = match_info.get('language', 'english')
# title = match_info.get('title', 'Unknown Story')
# category = match_info.get('category', 'story')
# original_title = match_info.get('original_title', title)
# # Clean up the title (remove underscores, etc.)
# clean_title = title.replace("_", " ").replace("-", " ")
# if method == 'ai_multilingual':
# if language != 'english':
# intros = [
# f"Perfect! I found '{clean_title}' for you!",
# f"Great choice! Here's the story '{clean_title}'!",
# f"I found exactly what you wanted: '{clean_title}'!",
# f"Let me tell you '{clean_title}' - this should be perfect!"
# ]
# else:
# intros = [
# f"I found '{clean_title}' which matches your request perfectly!",
# f"Here's '{clean_title}' - I think you'll love this story!",
# f"Playing '{clean_title}' based on your request!"
# ]
# elif method == 'language_random':
# intros = [
# f"Here's a wonderful story for you: '{clean_title}'!",
# f"Let me tell you '{clean_title}' - a beautiful story!",
# f"I picked '{clean_title}' from our collection!"
# ]
# elif method == 'category_selection':
# if category != 'unknown':
# intros = [
# f"Here's a lovely {category.lower()} story: '{clean_title}'!",
# f"Perfect! I have a {category.lower()} story for you: '{clean_title}'!",
# f"Let me tell you this {category.lower()} story called '{clean_title}'!"
# ]
# else:
# intros = [
# f"Here's a wonderful story: '{clean_title}'!",
# f"Let me tell you '{clean_title}'!",
# f"I have a great story for you: '{clean_title}'!"
# ]
# elif method == 'legacy_fuzzy':
# intros = [
# f"I think you'll love '{clean_title}'!",
# f"Here's '{clean_title}' - hope this is what you wanted!",
# f"Let me tell you the story of '{clean_title}'!"
# ]
# else: # random_fallback
# intros = [
# f"Let me tell you a wonderful story: '{clean_title}'!",
# f"Here's a great story for you: '{clean_title}'!",
# f"I have a special story called '{clean_title}'!"
# ]
# return random.choice(intros)
# def find_best_story_match(story_name, story_files):
# """Find the best matching story from available files with enhanced matching"""
# best_match = None
# highest_score = 0
# # Clean and normalize the input story name
# clean_story_name = story_name.lower().strip()
# # Remove common story words that don't help with matching
# story_words_to_remove = ['story', 'tale', 'a', 'the', 'play', 'tell', 'me']
# story_name_words = [word for word in clean_story_name.split() if word not in story_words_to_remove]
# for story_file in story_files:
# # Extract just the filename without path and extension
# file_name = os.path.splitext(os.path.basename(story_file))[0].lower()
# file_name_words = file_name.split()
# # Method 1: Direct sequence matching (existing approach)
# sequence_ratio = difflib.SequenceMatcher(None, clean_story_name, file_name).ratio()
# # Method 2: Word-based matching - check how many words match
# word_match_score = 0
# if story_name_words:
# matching_words = 0
# for word in story_name_words:
# if any(word in file_word for file_word in file_name_words):
# matching_words += 1
# word_match_score = matching_words / len(story_name_words)
# # Method 3: Partial string matching - check if story name is contained in filename
# containment_score = 0
# if clean_story_name in file_name or file_name in clean_story_name:
# containment_score = 0.8
# # Combine scores with weights
# combined_score = (sequence_ratio * 0.4) + (word_match_score * 0.4) + (containment_score * 0.2)
# # Lower threshold but use combined scoring for better matches
# if combined_score > highest_score and combined_score > 0.3:
# highest_score = combined_score
# best_match = story_file
# return best_match
# async def handle_story_command(conn, category, specific_story=None, requested_language=None):
# """Handle story playback command"""
# initialize_story_handler(conn)
# global STORY_CACHE
# conn.logger.bind(tag=TAG).debug(f"Handling story command - Category: {category}, Story: {specific_story}, Language: {requested_language}")
# # Check if stories directory exists
# if not os.path.exists(STORY_CACHE["story_dir"]):
# conn.logger.bind(tag=TAG).error(f"Story directory does not exist: {STORY_CACHE['story_dir']}")
# await send_stt_message(conn, "Sorry, I couldn't find the story collection.")
# return
# # Refresh cache if needed
# if time.time() - STORY_CACHE["scan_time"] > STORY_CACHE["refresh_time"]:
# STORY_CACHE["story_files_by_category"], STORY_CACHE["all_story_files"] = get_story_files(
# STORY_CACHE["story_dir"], STORY_CACHE["story_ext"]
# )
# STORY_CACHE["scan_time"] = time.time()
# selected_story = None
# # If specific story name is provided, try to find it
# if specific_story:
# selected_story = find_best_story_match(specific_story, STORY_CACHE["all_story_files"])
# if selected_story:
# conn.logger.bind(tag=TAG).info(f"Found matching story: {selected_story}")
# # If no specific story found, select based on category
# if not selected_story:
# if category and category.lower() != "random":
# # Normalize category name
# normalized_category = normalize_category_name(category)
# # Try to find the category
# matching_category = None
# for cat_name in STORY_CACHE["story_files_by_category"].keys():
# if cat_name.lower() == normalized_category.lower():
# matching_category = cat_name
# break
# if matching_category and STORY_CACHE["story_files_by_category"][matching_category]:
# selected_story = random.choice(STORY_CACHE["story_files_by_category"][matching_category])
# conn.logger.bind(tag=TAG).info(f"Selected {matching_category} story: {selected_story}")
# else:
# conn.logger.bind(tag=TAG).warning(f"Category '{category}' not found or empty, selecting random story")
# if STORY_CACHE["all_story_files"]:
# selected_story = random.choice(STORY_CACHE["all_story_files"])
# else:
# # Select random story from all available
# if STORY_CACHE["all_story_files"]:
# selected_story = random.choice(STORY_CACHE["all_story_files"])
# conn.logger.bind(tag=TAG).info(f"Selected random story: {selected_story}")
# if selected_story:
# await play_story_file(conn, selected_story, requested_language)
# else:
# conn.logger.bind(tag=TAG).error("No stories found in the collection")
# await send_stt_message(conn, "I'm sorry, I couldn't find any stories to play.")
# def get_story_intro(story_file, requested_language=None):
# """Generate an introduction for the story"""
# # Extract story name and category
# parts = story_file.split(os.sep)
# if len(parts) > 1:
# category = parts[0]
# story_name = os.path.splitext(parts[-1])[0]
# else:
# category = "story"
# story_name = os.path.splitext(story_file)[0]
# # Clean up the story name (remove underscores, etc.)
# story_name = story_name.replace("_", " ").replace("-", " ")
# # Always use English intros since stories are in English
# intros = [
# f"Let me tell you a wonderful {category.lower()} story called '{story_name}'",
# f"Here's a {category.lower()} story for you: '{story_name}'",
# f"Get comfortable and enjoy this {category.lower()} story: '{story_name}'",
# f"I have a special {category.lower()} story for you called '{story_name}'",
# f"Listen carefully to this amazing story: '{story_name}'",
# f" Let's begin '{story_name}'",
# ]
# intro = random.choice(intros)
# # Add note if requested in another language
# if requested_language and requested_language != "english":
# intro = f"Playing English story. {intro}"
# return intro
# async def play_story_file(conn, story_file, requested_language=None):
# """Play the selected story file - CDN STREAMING VERSION"""
# try:
# # Extract category and filename from story_file path
# path_parts = story_file.split('/')
# if len(path_parts) >= 2:
# category = path_parts[0]
# filename = path_parts[1]
# else:
# # Fallback
# category = "Fantasy"
# filename = os.path.basename(story_file)
# # Generate CDN streaming URL
# cdn_url = generate_cdn_story_url(category, filename)
# if not cdn_url:
# conn.logger.bind(tag=TAG).error(f"Failed to generate CDN URL for: {category}/{filename}")
# await send_stt_message(conn, "Sorry, I couldn't access the story file.")
# return
# # CRITICAL CHANGE: Download from CDN to local file first
# local_file_path = await download_cdn_file(cdn_url, conn)
# if not local_file_path:
# conn.logger.bind(tag=TAG).error(f"Failed to download CDN file: {cdn_url}")
# await send_stt_message(conn, "Sorry, I couldn't download the story file.")
# return
# # Generate and send introduction (always in English)
# intro_text = get_story_intro(story_file, requested_language)
# await send_stt_message(conn, intro_text)
# conn.dialogue.put(Message(role="assistant", content=intro_text))
# # Send TTS messages to play the story from CDN
# if conn.intent_type == "intent_llm":
# conn.tts.tts_text_queue.put(
# TTSMessageDTO(
# sentence_id=conn.sentence_id,
# sentence_type=SentenceType.FIRST,
# content_type=ContentType.ACTION,
# )
# )
# conn.tts.tts_text_queue.put(
# TTSMessageDTO(
# sentence_id=conn.sentence_id,
# sentence_type=SentenceType.MIDDLE,
# content_type=ContentType.TEXT,
# content_detail=intro_text,
# )
# )
# # Use CDN URL instead of local file path
# conn.tts.tts_text_queue.put(
# TTSMessageDTO(
# sentence_id=conn.sentence_id,
# sentence_type=SentenceType.MIDDLE,
# content_type=ContentType.FILE,
# content_file=local_file_path, # LOCAL FILE, NOT CDN URL!
# )
# )
# if conn.intent_type == "intent_llm":
# conn.tts.tts_text_queue.put(
# TTSMessageDTO(
# sentence_id=conn.sentence_id,
# sentence_type=SentenceType.LAST,
# content_type=ContentType.ACTION,
# )
# )
# # CRITICAL FIX: Set llm_finish_task to True so stop signal is sent after story completes
# conn.llm_finish_task = True
# conn.logger.bind(tag=TAG).info(f"Streaming story from local cache: {local_file_path}")
# except Exception as e:
# conn.logger.bind(tag=TAG).error(f"Failed to stream story from CDN: {str(e)}")
# conn.logger.bind(tag=TAG).error(f"Detailed error: {traceback.format_exc()}")
import os
import re
import time

View file

@ -53,8 +53,10 @@ class SemanticMusicSearch:
self.is_available = True
# Qdrant configuration
self.qdrant_url = self.config.get("qdrant_url", "https://a2482b9f-2c29-476e-9ff0-741aaaaf632e.eu-west-1-0.aws.cloud.qdrant.io")
self.qdrant_api_key = self.config.get("qdrant_api_key", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2Nlc3MiOiJtIn0.zPBGAqVGy-edbbgfNOJsPWV496BsnQ4ELOFvsLNyjsk")
self.collection_name = self.config.get("collection_name", "xiaozhi_music")
# Embedding model configuration

View file

@ -43,4 +43,10 @@ amazon_transcribe
# Semantic search dependencies
qdrant-client>=1.7.0
sentence-transformers>=2.2.0
pyspellchecker>=0.7.0
pyspellchecker>=0.7.0
# Google Cloud Speech v2 dependencies
google-cloud-speech>=2.26.0
pyspellchecker>=0.7.0

View file

@ -0,0 +1,234 @@
#!/usr/bin/env python3
"""
Test script for Google Cloud Speech-to-Text v2 ASR Provider
This script validates the provider implementation without requiring actual credentials
"""
import sys
import os
import asyncio
from unittest.mock import Mock, patch, MagicMock
# Add the project root to Python path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
# Mock the Google Cloud Speech v2 imports before importing our provider
sys.modules['google.cloud.speech_v2'] = Mock()
sys.modules['google.api_core.exceptions'] = Mock()
from core.providers.asr.google_speech_v2 import ASRProvider
def test_provider_initialization():
"""Test that the provider initializes correctly with valid configuration"""
config = {
"project_id": "test-project-123",
"location": "global",
"credentials_path": "/path/to/credentials.json",
"model": "chirp_2",
"language_codes": ["en-US"],
"sample_rate_hertz": 16000,
"encoding": "LINEAR16",
"enable_automatic_punctuation": True,
"enable_word_time_offsets": False,
"enable_word_confidence": False,
"output_dir": "./tmp/"
}
print("Testing provider initialization...")
# Mock the Google Cloud client
with patch('core.providers.asr.google_speech_v2.speech_v2.SpeechClient') as mock_client:
mock_instance = Mock()
mock_client.return_value = mock_instance
try:
provider = ASRProvider(config, delete_audio_file=True)
print("[PASS] Provider initialized successfully")
# Verify configuration
assert provider.project_id == "test-project-123"
assert provider.model == "chirp_2"
assert provider.language_codes == ["en-US"]
assert provider.sample_rate_hertz == 16000
print("[PASS] Configuration validated")
# Verify recognizer name format
expected_recognizer = f"projects/{config['project_id']}/locations/{config['location']}/recognizers/_"
assert provider.recognizer_name == expected_recognizer
print("[PASS] Recognizer name format correct")
except Exception as e:
print(f"[FAIL] Provider initialization failed: {e}")
return False
return True
def test_audio_encoding_mapping():
"""Test the audio encoding mapping function"""
config = {
"project_id": "test-project",
"encoding": "LINEAR16"
}
print("Testing audio encoding mapping...")
with patch('core.providers.asr.google_speech_v2.speech_v2.SpeechClient'):
provider = ASRProvider(config, delete_audio_file=True)
# Test various encoding mappings
test_cases = [
("LINEAR16", "LINEAR16"),
("FLAC", "FLAC"),
("MP3", "MP3"),
("OGG_OPUS", "OGG_OPUS"),
]
for input_encoding, expected in test_cases:
provider.encoding = input_encoding
result = provider._get_audio_encoding()
print(f"[PASS] {input_encoding} -> {result}")
return True
async def test_speech_to_text_mock():
"""Test the speech_to_text method with mocked Google Cloud API response"""
config = {
"project_id": "test-project",
"location": "global",
"model": "chirp_2",
"language_codes": ["en-US"],
"sample_rate_hertz": 16000,
"encoding": "LINEAR16",
"output_dir": "./tmp/"
}
print("Testing speech_to_text method...")
# Create mock audio data (simulating Opus packets)
mock_opus_data = [b"fake_opus_packet_1", b"fake_opus_packet_2"]
# Mock the Google Cloud response
mock_alternative = Mock()
mock_alternative.transcript = "Hello, this is a test transcript"
mock_alternative.confidence = 0.95
mock_result = Mock()
mock_result.alternatives = [mock_alternative]
mock_channel = Mock()
mock_channel.alternatives = [mock_alternative]
mock_response = Mock()
mock_response.results = [mock_result]
with patch('core.providers.asr.google_speech_v2.speech_v2.SpeechClient') as mock_client_class:
mock_client = Mock()
mock_client_class.return_value = mock_client
mock_client.recognize.return_value = mock_response
# Mock other dependencies
with patch('core.providers.asr.google_speech_v2.ASRProviderBase.decode_opus') as mock_decode, \
patch('core.providers.asr.google_speech_v2.ASRProviderBase.save_audio_to_file') as mock_save, \
patch('core.providers.asr.google_speech_v2.ASRProviderBase.log_audio_transcript') as mock_log, \
patch('os.makedirs'):
# Configure mocks
mock_decode.return_value = [b"pcm_data_1", b"pcm_data_2"]
mock_save.return_value = "/tmp/test_audio.wav"
provider = ASRProvider(config, delete_audio_file=False)
# Test the speech_to_text method
try:
result_text, file_path = await provider.speech_to_text(
mock_opus_data,
session_id="test_session_123",
audio_format="opus"
)
print(f"[PASS] Speech-to-text completed")
print(f" Result: '{result_text}'")
print(f" File path: {file_path}")
# Verify the result
assert result_text == "Hello, this is a test transcript"
assert file_path == "/tmp/test_audio.wav"
# Verify Google Cloud API was called correctly
mock_client.recognize.assert_called_once()
print("[PASS] Google Cloud API called with correct parameters")
except Exception as e:
print(f"[FAIL] Speech-to-text test failed: {e}")
import traceback
traceback.print_exc()
return False
return True
def test_configuration_validation():
"""Test configuration validation and edge cases"""
print("Testing configuration validation...")
# Test minimal configuration
minimal_config = {
"project_id": "test-project"
}
with patch('core.providers.asr.google_speech_v2.speech_v2.SpeechClient'), \
patch('os.makedirs'):
provider = ASRProvider(minimal_config, delete_audio_file=True)
# Verify defaults
assert provider.location == "global"
assert provider.model == "chirp_2"
assert provider.language_codes == ["en-US"]
assert provider.sample_rate_hertz == 16000
assert provider.encoding == "LINEAR16"
print("[PASS] Default values applied correctly")
return True
def main():
"""Run all tests"""
print("Testing Google Cloud Speech-to-Text v2 ASR Provider")
print("=" * 60)
tests = [
("Provider Initialization", test_provider_initialization),
("Audio Encoding Mapping", test_audio_encoding_mapping),
("Configuration Validation", test_configuration_validation),
("Speech-to-Text (Mocked)", lambda: asyncio.run(test_speech_to_text_mock())),
]
passed = 0
total = len(tests)
for test_name, test_func in tests:
print(f"\nRunning: {test_name}")
try:
if test_func():
print(f"[PASS] {test_name}: PASSED")
passed += 1
else:
print(f"[FAIL] {test_name}: FAILED")
except Exception as e:
print(f"[ERROR] {test_name}: ERROR - {e}")
print("\n" + "=" * 60)
print(f"Test Results: {passed}/{total} tests passed")
if passed == total:
print("All tests passed! Google Speech v2 provider is ready to use.")
print("\nNext steps:")
print("1. Install dependencies: pip install google-cloud-speech>=2.26.0")
print("2. Set up Google Cloud credentials")
print("3. Update selected_module.ASR in config.yaml to: GoogleSpeechV2")
print("4. Configure your Google Cloud project settings")
else:
print("Some tests failed. Please check the implementation.")
sys.exit(1)
if __name__ == "__main__":
main()

View file

@ -1,213 +0,0 @@
#!/usr/bin/env python3
"""
Simple script to fix Story Playback function placement in agent templates
"""
import mysql.connector
from mysql.connector import Error
import json
def connect_to_database():
"""Connect to the Railway MySQL database"""
try:
connection = mysql.connector.connect(
host='nozomi.proxy.rlwy.net',
port=25037,
database='railway',
user='root',
password='OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm',
charset='utf8mb4',
use_unicode=True,
ssl_disabled=True
)
if connection.is_connected():
print("Successfully connected to Railway MySQL database")
return connection
except Error as e:
print(f"Error connecting to MySQL: {e}")
return None
def check_current_mappings(connection):
"""Check current plugin mappings"""
cursor = connection.cursor()
try:
print("\nChecking current plugin mappings...")
# Check if ai_agent_plugin_mapping has the right structure
cursor.execute("DESCRIBE ai_agent_plugin_mapping")
columns = cursor.fetchall()
column_names = [col[0] for col in columns]
print(f"ai_agent_plugin_mapping columns: {column_names}")
# Check if we should use template_id or agent_id
if 'template_id' in column_names:
id_column = 'template_id'
elif 'agent_id' in column_names:
id_column = 'agent_id'
else:
print("ERROR: Neither template_id nor agent_id found in ai_agent_plugin_mapping table")
return None, None
# Get all current mappings
cursor.execute(f"SELECT * FROM ai_agent_plugin_mapping")
mappings = cursor.fetchall()
print(f"\nFound {len(mappings)} existing plugin mappings")
for mapping in mappings:
mapping_dict = dict(zip(column_names, mapping))
print(f"ID: {mapping_dict.get('id')}, {id_column}: {mapping_dict.get(id_column)}, plugin_id: {mapping_dict.get('plugin_id')}")
return mappings, id_column
except Error as e:
print(f"Error checking current mappings: {e}")
return None, None
finally:
cursor.close()
def get_all_agent_templates(connection):
"""Get all agent template IDs"""
cursor = connection.cursor()
try:
cursor.execute("SELECT id, agent_name FROM ai_agent_template")
templates = cursor.fetchall()
print(f"\nFound {len(templates)} agent templates:")
for template in templates:
print(f" ID: {template[0]}, Name: {template[1]}")
return templates
except Error as e:
print(f"Error getting agent templates: {e}")
return []
finally:
cursor.close()
def add_story_playback_to_all_templates(connection, templates, id_column):
"""Add Story Playback plugin to all templates"""
cursor = connection.cursor()
try:
story_playback_plugin_id = "SYSTEM_PLUGIN_STORY"
updates_made = 0
print(f"\nAdding Story Playback plugin to all templates...")
for template_id, template_name in templates:
print(f"\nProcessing template: {template_name} (ID: {template_id})")
# Check if mapping already exists
cursor.execute(f"""
SELECT * FROM ai_agent_plugin_mapping
WHERE {id_column} = %s AND plugin_id = %s
""", (template_id, story_playback_plugin_id))
existing = cursor.fetchone()
if existing:
print(f" Already has Story Playback mapping")
else:
# Insert new mapping
# Create a basic param_info for the story plugin
param_info = {
"story_dir": "./stories",
"story_ext": ".mp3;.wav;.m4a",
"refresh_time": "300"
}
cursor.execute(f"""
INSERT INTO ai_agent_plugin_mapping
({id_column}, plugin_id, param_info)
VALUES (%s, %s, %s)
""", (template_id, story_playback_plugin_id, json.dumps(param_info)))
print(f" Added Story Playback mapping")
updates_made += 1
connection.commit()
print(f"\nCompleted! Added Story Playback to {updates_made} templates.")
except Error as e:
print(f"Error adding Story Playback mappings: {e}")
connection.rollback()
finally:
cursor.close()
def verify_mappings(connection, id_column):
"""Verify all templates now have Story Playback"""
cursor = connection.cursor()
try:
print(f"\nVerifying Story Playback mappings...")
cursor.execute(f"""
SELECT
at.id,
at.agent_name,
CASE WHEN apm.plugin_id IS NOT NULL THEN 'YES' ELSE 'NO' END as has_story_playback
FROM ai_agent_template at
LEFT JOIN ai_agent_plugin_mapping apm
ON at.id = apm.{id_column} AND apm.plugin_id = 'SYSTEM_PLUGIN_STORY'
ORDER BY at.agent_name
""")
results = cursor.fetchall()
total_templates = len(results)
with_story_playback = sum(1 for result in results if result[2] == 'YES')
print(f"\nStory Playback status:")
for result in results:
template_id, agent_name, has_playback = result
status = "✓" if has_playback == 'YES' else "✗"
print(f" {status} {agent_name} (ID: {template_id})")
print(f"\nSummary:")
print(f"Total templates: {total_templates}")
print(f"With Story Playback: {with_story_playback}")
if with_story_playback == total_templates:
print(" SUCCESS: All templates now have Story Playback!")
else:
print(f" {total_templates - with_story_playback} templates still missing Story Playback")
except Error as e:
print(f"Error verifying mappings: {e}")
finally:
cursor.close()
def main():
print("Fixing Story Playback function for all agent templates")
print("=" * 60)
connection = connect_to_database()
if not connection:
return
try:
# Check current state
mappings, id_column = check_current_mappings(connection)
if not id_column:
return
# Get all templates
templates = get_all_agent_templates(connection)
if not templates:
print("No agent templates found!")
return
# Add Story Playback to all templates
add_story_playback_to_all_templates(connection, templates, id_column)
# Verify the fix
verify_mappings(connection, id_column)
finally:
if connection.is_connected():
connection.close()
print(f"\nMySQL connection closed")
if __name__ == "__main__":
main()

View file

@ -1,243 +0,0 @@
#!/usr/bin/env python3
"""
Simple script to check and fix Story Playback function mapping
"""
import mysql.connector
from mysql.connector import Error
import json
def connect_to_database():
"""Connect to the Railway MySQL database"""
try:
connection = mysql.connector.connect(
host='nozomi.proxy.rlwy.net',
port=25037,
database='railway',
user='root',
password='OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm',
charset='utf8mb4',
use_unicode=True,
ssl_disabled=True
)
if connection.is_connected():
print("Successfully connected to Railway MySQL database")
return connection
except Error as e:
print(f"Error connecting to MySQL: {e}")
return None
def check_story_plugin_exists(connection):
"""Check if Story Playback plugin exists"""
cursor = connection.cursor()
try:
cursor.execute("""
SELECT id, provider_code, name
FROM ai_model_provider
WHERE id = 'SYSTEM_PLUGIN_STORY'
""")
result = cursor.fetchone()
if result:
plugin_id, provider_code, name = result
print(f"[OK] Story Playback plugin exists: {plugin_id}")
print(f" Provider code: {provider_code}")
return True
else:
print(f"[ERROR] Story Playback plugin not found!")
return False
except Error as e:
print(f"Error checking story plugin: {e}")
return False
finally:
cursor.close()
def check_intent_function_configuration(connection):
"""Check Intent function call configuration"""
cursor = connection.cursor()
try:
cursor.execute("""
SELECT id, fields
FROM ai_model_provider
WHERE model_type = 'Intent' AND provider_code = 'function_call'
LIMIT 1
""")
result = cursor.fetchone()
if result:
config_id, fields = result
print(f"[OK] Intent function call config found: {config_id}")
try:
fields_json = json.loads(fields)
# Find functions field
functions_value = None
for field in fields_json:
if field.get('key') == 'functions':
functions_value = field.get('default', '')
break
if functions_value:
print(f"Current functions: {functions_value}")
if 'play_story' in functions_value.lower():
print("[OK] play_story found in Intent functions!")
return True, config_id, fields_json
else:
print("[MISSING] play_story NOT found in Intent functions!")
return False, config_id, fields_json
else:
print("[ERROR] No functions field found in Intent config!")
return False, config_id, None
except json.JSONDecodeError:
print("[ERROR] Could not parse Intent configuration JSON")
return False, config_id, None
else:
print("[ERROR] Intent function call configuration not found!")
return False, None, None
except Error as e:
print(f"Error checking Intent config: {e}")
return False, None, None
finally:
cursor.close()
def fix_intent_functions(connection, config_id, fields_json):
"""Add play_story to Intent functions if missing"""
cursor = connection.cursor()
try:
# Find and update the functions field
for i, field in enumerate(fields_json):
if field.get('key') == 'functions':
current_functions = field.get('default', '')
# Add play_story if not present
if current_functions and not current_functions.endswith(';'):
updated_functions = current_functions + ';play_story'
elif current_functions:
updated_functions = current_functions + 'play_story'
else:
updated_functions = 'play_story'
fields_json[i]['default'] = updated_functions
break
# Update database
cursor.execute("""
UPDATE ai_model_provider
SET fields = %s
WHERE id = %s
""", (json.dumps(fields_json), config_id))
connection.commit()
print(f"[FIXED] Added play_story to Intent functions!")
print(f"Updated functions: {updated_functions}")
return True
except Error as e:
print(f"Error fixing Intent functions: {e}")
connection.rollback()
return False
finally:
cursor.close()
def check_agent_story_mappings(connection):
"""Check which agents have Story Playback"""
cursor = connection.cursor()
try:
cursor.execute("""
SELECT
a.id,
a.agent_name,
CASE WHEN apm.plugin_id IS NOT NULL THEN 'YES' ELSE 'NO' END as has_story
FROM ai_agent a
LEFT JOIN ai_agent_plugin_mapping apm
ON a.id = apm.agent_id AND apm.plugin_id = 'SYSTEM_PLUGIN_STORY'
ORDER BY a.agent_name
""")
results = cursor.fetchall()
total = len(results)
with_story = len([r for r in results if r[2] == 'YES'])
print(f"\nAgent Story Playback Status:")
print(f"Total agents: {total}")
print(f"With Story Playback: {with_story}")
if with_story < total:
print(f"Missing Story Playback:")
for agent_id, agent_name, has_story in results:
if has_story == 'NO':
print(f" - {agent_name} (ID: {agent_id})")
else:
print("[OK] All agents have Story Playback!")
return with_story == total
except Error as e:
print(f"Error checking agent mappings: {e}")
return False
finally:
cursor.close()
def main():
print("Story Playback Function Check")
print("=" * 50)
connection = connect_to_database()
if not connection:
return
try:
# 1. Check if Story plugin exists
print("\n1. Checking Story Playback Plugin...")
story_exists = check_story_plugin_exists(connection)
# 2. Check Intent function configuration
print("\n2. Checking Intent Function Configuration...")
has_play_story, config_id, fields_json = check_intent_function_configuration(connection)
# 3. Fix Intent functions if needed
if not has_play_story and config_id and fields_json:
print("\n3. Fixing Intent Function Configuration...")
fix_intent_functions(connection, config_id, fields_json)
elif has_play_story:
print("\n3. Intent Configuration - OK, no fix needed")
# 4. Check agent mappings
print("\n4. Checking Agent Story Playback Mappings...")
all_agents_have_story = check_agent_story_mappings(connection)
# Summary
print(f"\n{'='*50}")
print("SUMMARY")
print('='*50)
if story_exists:
print("[✓] Story Playback plugin exists in database")
else:
print("[✗] Story Playback plugin missing")
if has_play_story:
print("[✓] play_story configured in Intent functions")
else:
print("[✗] play_story missing from Intent functions")
if all_agents_have_story:
print("[✓] All agents have Story Playback mapped")
else:
print("[✗] Some agents missing Story Playback")
finally:
connection.close()
if __name__ == "__main__":
main()

View file

@ -1,70 +0,0 @@
name: Test Platform Detection
on: [push, pull_request]
jobs:
test-platforms:
strategy:
matrix:
include:
- os: ubuntu-latest
platform: Linux
python-version: '3.9'
- os: ubuntu-latest
platform: Linux
python-version: '3.10'
- os: ubuntu-latest
platform: Linux
python-version: '3.11'
- os: ubuntu-latest
platform: Linux
python-version: '3.12'
- os: macos-latest
platform: macOS
python-version: '3.9'
- os: macos-latest
platform: macOS
python-version: '3.10'
- os: macos-latest
platform: macOS
python-version: '3.11'
- os: macos-latest
platform: macOS
python-version: '3.12'
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}
- name: Install system dependencies (Ubuntu)
if: runner.os == 'Linux'
run: |
sudo apt-get update
sudo apt-get install -y libc++1 libc++abi1
- name: Install dependencies for git clone scenario
run: |
pip install -r requirements.txt
pip install -r examples/requirements.txt
- name: Test git clone scenario
run: |
cd examples
python test.py s0724-s0730.wav output_git_clone.txt
echo "✅ ${{ matrix.platform }} Python ${{ matrix.python-version }} git clone scenario successful"
- name: Install package
run: pip install .
- name: Test pip install scenario
run: |
python -c "from ten_vad import TenVad; print('✅ ${{ matrix.platform }} Python ${{ matrix.python-version }} pip install import successful')"
cd examples
python test.py s0724-s0730.wav output_pip_install.txt
echo "✅ ${{ matrix.platform }} Python ${{ matrix.python-version }} pip install scenario successful"

View file

@ -1,18 +0,0 @@
examples/build-mac/
examples/build-ios/
examples/build-android/
examples/build-linux/
examples/build-windows/
examples/build-web/
examples_onnx/build-linux
include/.DS_Store
lib/.DS_Store
examples/.DS_Store
.vscode/
include/__pycache__/
__pycache__/
examples/out.txt
.DS_Store

View file

@ -1,47 +0,0 @@
Open Source License
The ten-vad is licensed pursuant to the Apache License v2.0, with the
following additional conditions. You may reproduce, prepare Derivative Works
of, publicly display, publicly perform, sublicense, distribute, or otherwise
make available (together, "Deploy") the ten-vad, for commercial or
non-commercial purposes, provided that you agree to abide by the terms below:
1. You may not Deploy the ten-vad in a way that competes with Agora's
offerings and/or that allows others to compete with Agora's offerings,
including without limitation enabling any third party to develop or
deploy Applications.
2. You may Deploy the ten-vad solely to create and enable deployment
of your Application(s) solely for your benefit and the benefit of your
direct End Users. If you prefer, you may include the following notice in
the documentation of your Application(s): "Powered by ten-vad".
3. Derivative Works of the ten-vad remain subject to this Open Source
License.
4. "End Users" shall mean the end-users of your Application(s) who access
the ten-vad solely to the extent necessary to access and use the
Application(s) you create or deploy using ten-vad.
5. "Application(s)" shall mean your software programs designed or developed
by using the ten-vad or where deployment is enabled by the ten-vad.
Copyright © 2025 Agora
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=======================================================================================
Note that the project contains derived code from other open source project
with BSD-3-Clause and BSD-2-Clause license, refer to the "NOTICES"
file in the root directory for detailed information.

View file

@ -1,68 +0,0 @@
This project includes modified code from the following third-party component:
1. File: lpcnet_enc.c
- Source: LPCNet (https:github.com/xiph/LPCNet)
- License: BSD-2-Clause
- Copyright: 2017-2019, Mozilla
- Original License Text:
Copyright (c) 2017-2019 Mozilla
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2. Project: LPCNet
- Source: LPCNet (https:github.com/xiph/LPCNet)
- License: BSD-3-Clause
- Copyright: 2017-2018, Mozilla, 2007-2017, Jean-Marc Valin, 2005-2017, Xiph.Org Foundation, 2003-2004, Mark Borgerding
- Original License Text of LPCNet open source project:
Copyright (c) 2017-2018, Mozilla
Copyright (c) 2007-2017, Jean-Marc Valin
Copyright (c) 2005-2017, Xiph.Org Foundation
Copyright (c) 2003-2004, Mark Borgerding
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.Org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View file

@ -1,637 +0,0 @@
![TEN VAD banner][ten-vad-banner]
[![Discussion posts](https://img.shields.io/github/discussions/TEN-framework/ten-vad?labelColor=gray&color=%20%23f79009)](https://github.com/TEN-framework/ten-vad/discussions/)
[![Commits](https://img.shields.io/github/commit-activity/m/TEN-framework/ten-vad?labelColor=gray&color=pink)](https://github.com/TEN-framework/ten-vad/graphs/commit-activity)
[![Issues closed](https://img.shields.io/github/issues-search?query=repo%3ATEN-framework%2Ften-vad%20is%3Aclosed&label=issues%20closed&labelColor=gray&color=green)](https://github.com/TEN-framework/ten-vad/issues)
![](https://img.shields.io/github/contributors/ten-framework/ten-vad?color=c4f042&labelColor=gray&style=flat-square)
[![PRs Welcome](https://img.shields.io/badge/PRs-welcome!-brightgreen.svg?style=flat-square)](https://github.com/TEN-framework/ten-vad/pulls)
[![GitHub license](https://img.shields.io/badge/License-Apache_2.0_with_certain_conditions-blue.svg?labelColor=%20%23155EEF&color=%20%23528bff)](https://github.com/TEN-framework/ten-vad/blob/main/LICENSE)
[![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/TEN-framework/TEN-vad)
[![GitHub watchers](https://img.shields.io/github/watchers/TEN-framework/ten-vad?style=social&label=Watch)](https://GitHub.com/TEN-framework/ten-vad/watchers/?WT.mc_id=academic-105485-koreyst)
[![GitHub forks](https://img.shields.io/github/forks/TEN-framework/ten-vad?style=social&label=Fork)](https://GitHub.com/TEN-framework/ten-vad/network/?WT.mc_id=academic-105485-koreyst)
[![GitHub stars](https://img.shields.io/github/stars/TEN-framework/ten-vad?style=social&label=Star)](https://GitHub.com/TEN-framework/ten-vad/stargazers/?WT.mc_id=academic-105485-koreyst)
<br>
## Latest News 🔥
- [2025/07] We support **Python inference** on **macOS** and **Windows** with usage of the prebuilt-lib!
- [2025/06] We **finally** released and **open-sourced** the **ONNX** model and the corresponding **preprocessing code**! Now you can deploy **TEN VAD** on **any platform** and **any hardware architecture**!
- [2025/06] We are excited to announce the release of **WASM+JS** for Web WASM Support.
<br>
## Table of Contents
- [Welcome to TEN](#welcome-to-ten)
- [TEN Hugging Face Space](#ten-hugging-face-space)
- [Introduction](#introduction)
- [Key Features](#key-features)
- [High-Performance](#1-high-performance)
- [Agent-Friendly](#2-agent-friendly)
- [Lightweight](#3-lightweight)
- [Multiple Programming Languages and Platforms](#4-multiple-programming-languages-and-platforms)
- [Supported Sampling Rate and Hop Size](#5-supproted-sampling-rate-and-hop-size)
- [Installation](#installation)
- [Quick Start](#quick-start)
- [Python Usage](#python-usage)
- [Linux](#1-linux)
- [JS Usage](#js-usage)
- [Web](#1-web)
- [C Usage](#c-usage)
- [Linux](#1-linux-1)
- [Windows](#2-windows)
- [macOS](#3-macos)
- [Android](#4-android)
- [iOS](#5-ios)
- [TEN Ecosystem](#ten-ecosystem)
- [Ask Questions](#ask-questions)
- [Citations](#citations)
- [License](#license)
<br>
## Welcome to TEN
TEN is a comprehensive open-source ecosystem for creating, customizing, and deploying real-time conversational AI agents with multimodal capabilities including voice, vision, and avatar interactions.
TEN includes [TEN Framework](https://github.com/ten-framework/ten-framework), [TEN Turn Detection](https://github.com/ten-framework/ten-turn-detection), [TEN VAD](https://github.com/ten-framework/ten-vad), [TEN Agent](https://github.com/TEN-framework/ten-framework/tree/main/ai_agents/demo), [TMAN Designer](https://github.com/TEN-framework/ten-framework/tree/main/core/src/ten_manager/designer_frontend), and [TEN Portal](https://github.com/ten-framework/portal). Check out [TEN Ecosystem](#ten-ecosystem) for more details.
<br>
| Community Channel | Purpose |
| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- |
| [![Follow on X](https://img.shields.io/twitter/follow/TenFramework?logo=X&color=%20%23f5f5f5)](https://twitter.com/intent/follow?screen_name=TenFramework) | Follow TEN Framework on X for updates and announcements |
| [![Follow on LinkedIn](https://custom-icon-badges.demolab.com/badge/LinkedIn-TEN_Framework-0A66C2?logo=linkedin-white&logoColor=fff)](https://www.linkedin.com/company/ten-framework) | Follow TEN Framework on LinkedIn for updates and announcements |
| [![Discord TEN Community](https://dcbadge.vercel.app/api/server/VnPftUzAMJ?&style=flat&theme=light&color=lightgray)](https://discord.gg/VnPftUzAMJ) | Join our Discord community to connect with developers |
| [![Hugging Face Space](https://img.shields.io/badge/Hugging%20Face-TEN%20Framework-yellow?style=flat&logo=huggingface)](https://huggingface.co/TEN-framework) | Join our Hugging Face community to explore our spaces and models |
| [![WeChat](https://img.shields.io/badge/TEN_Framework-WeChat_Group-%2307C160?logo=wechat&labelColor=darkgreen&color=gray)](https://github.com/TEN-framework/ten-agent/discussions/170) | Join our WeChat group for Chinese community discussions |
<br>
> \[!IMPORTANT]
>
> **Star TEN Repositories** ⭐️
>
> Get instant notifications for new releases and updates. Your support helps us grow and improve TEN!
<br>
![TEN star us gif](https://github.com/user-attachments/assets/eeebe996-8c14-4bf7-82ae-f1a1f7e30705)
<br>
## TEN Hugging Face Space
<https://github.com/user-attachments/assets/725a8318-d679-4b17-b9e4-e3dce999b298>
You are more than welcome to [Visit TEN Hugging Face Space](https://huggingface.co/spaces/TEN-framework/ten-agent-demo) to try VAD and Turn Detection together.
<br>
## **Introduction**
**TEN VAD** is a real-time voice activity detection system designed for enterprise use, providing accurate frame-level speech activity detection. It shows superior precision compared to both WebRTC VAD and Silero VAD, which are commonly used in the industry. Additionally, TEN VAD offers lower computational complexity and reduced memory usage compared to Silero VAD. Meanwhile, the architecture's temporal efficiency enables rapid voice activity detection, significantly reducing end-to-end response and turn detection latency in conversational AI systems.
<br>
## **Key Features**
### **1. High-Performance:**
The precision-recall curves comparing the performance of WebRTC VAD (pitch-based), Silero VAD, and TEN VAD are shown below. The evaluation is conducted on the precisely manually annotated testset. The audio files are from librispeech, gigaspeech, DNS Challenge etc. As demonstrated, TEN VAD achieves the best performance. Additionally, cross-validation experiments conducted on large internal real-world datasets demonstrate the reproducibility of these findings. The **testset with annotated labels** is released in directory "testset" of this repository.
<br>
<div style="text-align:">
<img src="./examples/images/PR_Curves_testset.png" width="800">
</div>
Note that the default threshold of 0.5 is used to generate binary speech indicators (0 for non-speech signal, 1 for speech signal). This threshold needs to be tuned according to your domain-specific task. The precision-recall curve can be obtained by executing the following script on Linux x64. The output figure will be saved in the same directory as the script.
```
cd ./examples
python plot_pr_curves.py
```
<br>
### **2. Agent-Friendly:**
As illustrated in the figure below, TEN VAD rapidly detects speech-to-non-speech transitions, whereas Silero VAD suffers from a delay of several hundred milliseconds, resulting in increased end-to-end latency in human-agent interaction systems. In addition, as demonstrated in the 6.5s-7.0s audio segment, Silero VAD fails to identify short silent durations between adjacent speech segments.
<div style="text-align:">
<img src="./examples/images/Agent-Friendly-image.png" width="800">
</div>
<br>
### **3. Lightweight:**
We evaluated the RTF (Real-Time Factor) across five distinct platforms, each equipped with varying CPUs. TEN VAD demonstrates much lower computational complexity and smaller library size than Silero VAD.
<table>
<tr>
<th align="center" rowspan="2" valign="middle"> Platform </th>
<th align="center" rowspan="2" valign="middle"> CPU </th>
<th align="center" colspan="2"> RTF </th>
<th align="center" colspan="2"> Lib Size </th>
</tr>
<tr>
<th align="center" style="white-space: nowrap;"> TEN VAD </th>
<th align="center" style="white-space: nowrap;"> Silero VAD </th>
<th align="center"> TEN VAD </th>
<th align="center"> Silero VAD </th>
</tr>
<tr>
<th align="center" rowspan="3"> Linux </th>
<td style="white-space: nowrap;"> AMD Ryzen 9 5900X 12-Core </td>
<td align="center"> 0.0150 </td>
<td align="center" rowspan="2" valign="middle"> / </td>
<td align="center" rowspan="3" valign="middle"> 306KB </td>
<td align="center" rowspan="10" style="white-space: nowrap;" valign="middle"> 2.16MB(JIT) / 2.22MB(ONNX) </td>
</tr>
<tr>
<td style="white-space: nowrap;"> Intel(R) Xeon(R) Platinum 8253 </td>
<td align="center"> 0.0136 </td>
</tr>
<tr>
<td style="white-space: nowrap;"> Intel(R) Xeon(R) Gold 6348 CPU @ 2.60GHz </td>
<td align="center"> 0.0086 </td>
<td align="center"> 0.0127 </td>
</tr>
<tr>
<th align="center"> Windows </th>
<td> Intel i7-10710U </td>
<td align="center"> 0.0150 </td>
<td align="center" rowspan="7" valign="middle"> / </td>
<td align="center" style="white-space: nowrap;"> 464KB(x86) / 508KB(x64) </td>
</tr>
<tr>
<th align="center"> macOS </th>
<td> M1 </td>
<td align="center"> 0.0160 </td>
<td align="center"> 731KB </td>
</tr>
<tr>
<th align="center"> Web </th>
<td> macOS(M1) </td>
<td align="center"> 0.010 </td>
<td align="center"> 277KB </td>
</tr>
<tr>
<th align="center" rowspan="2"> Android </th>
<td> Galaxy J6+ (32bit, 425) </td>
<td align="center"> 0.0570 </td>
<td align="center" rowspan="2" style="white-space: nowrap;"> 373KB(v7a) / 532KB(v8a)</td>
</tr>
<tr>
<td> Oppo A3s (450) </td>
<td align="center"> 0.0490 </td>
</tr>
<tr>
<th align="center" rowspan="2"> iOS </th>
<td> iPhone6 (A8) </td>
<td align="center"> 0.0210 </td>
<td align="center" rowspan="2"> 320KB</td>
</tr>
<tr>
<td> iPhone8 (A11) </td>
<td align="center"> 0.0050 </td>
</tr>
</table>
<br>
### **4. Multiple programming languages and platforms:**
TEN VAD provides cross-platform C compatibility across five operating systems (Linux x64, Windows, macOS, Android, iOS), with Python bindings optimized for Linux x64, with wasm for Web.
<br>
<br>
### **5. Supproted sampling rate and hop size:**
TEN VAD operates on 16kHz audio input with configurable hop sizes (optimized frame configurations: 160/256 samples=10/16ms). Other sampling rates must be resampled to 16kHz.
<br>
<br>
## **Installation**
```
git clone https://github.com/TEN-framework/ten-vad.git
```
<br>
## **Quick Start**
The project supports five major platforms with dynamic library linking.
<table>
<tr>
<th align="center"> Platform </th>
<th align="center"> Dynamic Lib </th>
<th align="center"> Supported Arch </th>
<th align="center"> Interface Language </th>
<th align="center"> Header </th>
<th align="center"> Comment </v>
</tr>
<tr>
<th align="center"> Linux </th>
<td align="center"> libten_vad.so </td>
<td align="center"> x64 </td>
<td align="center"> Python, C </td>
<td rowspan="6">ten_vad.h <br> ten_vad.py <br> ten_vad.js</td>
<td> </td>
</tr>
<tr>
<th align="center"> Windows </th>
<td align="center"> ten_vad.dll </td>
<td align="center"> x64, x86 </td>
<td align="center"> C </td>
<td> </td>
</tr>
<tr>
<th align="center"> macOS </th>
<td align="center"> ten_vad.framework </td>
<td align="center"> arm64, x86_64 </td>
<td align="center"> C </td>
<td> </td>
</tr>
<tr>
<th align="center"> Web </th>
<td align="center"> ten_vad.wasm </td>
<td align="center"> / </td>
<td align="center"> JS </td>
<td> </td>
</tr>
<tr>
<th align="center"> Android </th>
<td align="center"> libten_vad.so </td>
<td align="center"> arm64-v8a, armeabi-v7a </td>
<td align="center"> C </td>
<td> </td>
</tr>
<tr>
<th align="center"> iOS </th>
<td align="center"> ten_vad.framework </td>
<td align="center"> arm64 </td>
<td align="center"> C </td>
<td> 1. not simulator <br> 2. not iPad </td>
</tr>
</table>
<br>
### **Python Usage**
#### **1. Linux / macOS / Windows**
#### **Requirements**
- numpy (Version 1.17.4/1.26.4 verified)
- scipy (Version >= 1.5.0)
- scikit-learn (Version 1.2.2/1.5.0 verified, for plotting PR curves)
- matplotlib (Version 3.1.3/3.10.0 verified, for plotting PR curves)
- torchaudio (Version 2.2.2 verified, for plotting PR curves)
- Python version 3.8.19/3.10.14 verified
Note: You could use other versions of above packages, but we didn't test other versions.
<br>
The **lib** only depend on numpy, you have to install the dependency via requirements.txt:
`pip install -r requirements.txt`
For **running demo or plotting PR curves**, you have to install the dependencies:
`pip install -r ./examples/requirements.txt`
Note that if you did not install **libc++1** (Linux), you have to run the code below to install it:
```
sudo apt update
sudo apt install libc++1
```
<br>
#### **Usage**
Note: For usage in python, you can either use it by **git clone** or **pip**.
##### **By using git clone:**
1. Clone the repository
```
git clone https://github.com/TEN-framework/ten-vad.git
```
2. Enter examples directory
```
cd ./examples
```
3. Test
```
python test.py s0724-s0730.wav out.txt
```
<br>
##### **By using pip:**
1. Install via pip
```
pip install -U --force-reinstall -v git+https://github.com/TEN-framework/ten-vad.git
```
2. Write your own use cases and import the class, the attributes of class TenVAD you can refer to ten_vad.py
```
from ten_vad import TenVad
```
<br>
### **JS Usage**
#### **1. Web**
##### **Requirements**
- Node.js (macOS v14.18.2, Linux v16.20.2 verified)
- Terminal
##### **Usage**
```
1) cd ./examples
2) node test_node.js s0724-s0730.wav out.txt
```
<br>
### **C Usage**
#### **Build Scripts**
Located in examples/ directory or examples_onnx/ (for **ONNX** usage on Linux):
- Linux: build-and-deploy-linux.sh
- Windows: build-and-deploy-windows.bat
- macOS: build-and-deploy-mac.sh
- Android: build-and-deploy-android.sh
- iOS: build-and-deploy-ios.sh
#### **Dynamic Library Configuration**
Runtime library path configuration:
- Linux/Android: LD_LIBRARY_PATH
- macOS: DYLD_FRAMEWORK_PATH
- Windows: DLL in executable directory or system PATH
#### **Customization**
- Modify platform-specific build scripts
- Adjust CMakeLists.txt
- Configure toolchain and architecture settings
#### **Overview of Usage**
- Navigate to examples/ or examples_onnx/ (for **ONNX** usage on Linux)
- Execute platform-specific build script
- Configure dynamic library path
- Run demo with sample audio s0724-s0730.wav
- Processed results saved to out.txt
<br>
The detailed usage methods of each platform are as follows <br>
#### **1. Linux**
##### **Requirements**
- Clang (e.g. 6.0.0-1ubuntu2 verified)
- CMake
- Terminal
Note that if you did not install **libc++1**, you have to run the code below to install it:
```
sudo apt update
sudo apt install libc++1
```
##### **Usage (prebuilt-lib)**
```
1) cd ./examples
2) ./build-and-deploy-linux.sh
```
##### **Usage (ONNX)**
You have to download the **onnxruntime** packages from the [microsoft official onnxruntime github website](https://github.com/microsoft/onnxruntime). Note that the version of onnxruntime must be higher than or equal to 1.17.1 (e.g. onnxruntime-linux-x64-1.17.1.tgz).
<br>
<br>
You can check the official **ONNX Runtime releases** from [this website](https://github.com/microsoft/onnxruntime/tags). And for example, to download version 1.17.1 (Linux x64), use [this link](https://github.com/microsoft/onnxruntime/releases/download/v1.17.1/onnxruntime-linux-x64-1.17.1.tgz). After extracting the compressed file, you'll find two important directories:`include/` - header files, `lib/` - library files
```
1) cd examples_onnx/
2) ./build-and-deploy-linux.sh --ort-path /absolute/path/to/your/onnxruntime/root/dir
```
**Note 1**: If executing the onnx demo from a different directory than the one used when running build-and-deploy-linux.sh, ensure to create a symbolic link to src/onnx_model/ to prevent ONNX model file loading failures.
<br>
**Note 2**: The **ONNX model** locates in `src/onnx_model` directory.
<br>
#### **2. Windows**
##### **Requirements**
- Visual Studio (2017, 2019, 2022 verified)
- CMake (3.26.0-rc6 verified)
- Terminal (MINGW64 or powershell)
##### **Usage**
```
1) cd ./examples
2) Configure "build-and-deploy-windows.bat" with your preferred:
- Architecture (default: x64)
- Visual Studio version (default: 2019)
3) ./build-and-deploy-windows.bat
```
<br>
#### **3. macOS**
##### **Requirements**
- Xcode (15.2 verified)
- CMake (3.19.2 verified)
##### **Usage**
```
1) cd ./examples
2) Configure "build-and-deploy-mac.sh" with your target architecture:
- Default: arm64 (Apple Silicon)
- Alternative: x86_64 (Intel)
3) ./build-and-deploy-mac.sh
```
<br>
#### **4. Android**
##### **Requirements**
- NDK (r25b, macOS verified)
- CMake (3.19.2, macOS verified)
- adb (1.0.41, macOS verified)
##### **Usage**
```
1) cd ./examples
2) export ANDROID_NDK=/path/to/android-ndk # Replace it with your NDK installation path
3) Configure "build-and-deploy-android.sh" with your build settings:
- Architecture: arm64-v8a (default) or armeabi-v7a
- Toolchain: aarch64-linux-android-clang (default) or custom NDK toolchain
4) ./build-and-deploy-android.sh
```
<br>
#### **5. iOS**
##### **Requirements**
Xcode (15.2, macOS verified)
CMake (3.19.2, macOS verified)
##### **Usage**
1. Enter examples directory
```
cd ./examples
```
2. Creates Xcode project files for iOS build
```
./build-and-deploy-ios.sh
```
3. Follow the steps below to build and test on iOS device:
3.1. Use Xcode to open .xcodeproj files: a) cd ./build-ios, b) open ./ten_vad_demo.xcodeproj
3.2. In Xcode IDE, select ten_vad_demo target (should check: Edit Scheme → Run → Release), then select your iOS Device (not simulator).
<div style="text-align:">
<img src="./examples/images/ios_image_1.jpg" width="800">
</div>
3.3. Drag ten_vad/lib/iOS/ten_vad.framework to "Frameworks, Libraries, and Embedded Content"
- (in TARGETS → ten_vad_demo → ten_vad_demo → General, should set Embed to "Embed & Sign").
- or add it directly in this way: "Frameworks, Libraries, and Embedded Content" → "+" → Add Other... → Add Files →...
- Note: If this step is not completed, you may encounter the following runtime error: "dyld: Library not loaded: @rpath/ten_vad.framework/ten_vad".
<div style="text-align:">
<img src="./examples/images/ios_image_2.png" width="800">
</div>
3.4. Configure iOS device Signature
- in TARGETS → ten_vad_demo → Signing & Capabilities → Signing
- Modify Bundle Identifier: modify "com.yourcompany" to yours;
- Specify Provisioning Profile
- In TARGETS → ten_vad_demo → Build Settings → Signing → Code Signing Identity:
- Specify your Certification
3.5. Build in Xcode and run demo on your device.
<br>
## TEN Ecosystem
| Project | Preview |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------ |
| [**🏚️ TEN Framework**][ten-framework-link]<br>TEN is an open-source framework for real-time, multimodal conversational AI.<br><br>![][ten-framework-shield] | ![][ten-framework-banner] |
| [**️🔂 TEN Turn Detection**][ten-turn-detection-link]<br>TEN is for full-duplex dialogue communication.<br><br>![][ten-turn-detection-shield] | ![][ten-turn-detection-banner] |
| [**🔉 TEN VAD**][ten-vad-link]<br>TEN VAD is a low-latency, lightweight and high-performance streaming voice activity detector (VAD).<br><br>![][ten-vad-shield] | ![][ten-vad-banner] |
| [**🎙️ TEN Agent**][ten-agent-link]<br>TEN Agent is a showcase of TEN Framewrok.<br><br> | ![][ten-agent-banner] |
| [**🎨 TMAN Designer**][tman-designer-link]<br>TMAN Designer is low/no code option to make a voice agent with easy to use workflow UI.<br><br> | ![][tman-designer-banner] |
| [**📒 TEN Portal**][ten-portal-link]<br>The official site of TEN framework, it has documentation and blog.<br><br>![][ten-portal-shield] | ![][ten-portal-banner] |
<br>
## Ask Questions
[![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/TEN-framework/TEN-vad)
Most questions can be answered by using DeepWiki, it is fast, intutive to use and supports multiple languages.
<br>
## **Citations**
```
@misc{TEN VAD,
author = {TEN Team},
title = {TEN VAD: A Low-Latency, Lightweight and High-Performance Streaming Voice Activity Detector (VAD)},
year = {2025},
publisher = {GitHub},
journal = {GitHub repository},
howpublished = {https://github.com/TEN-framework/ten-vad.git},
email = {developer@ten.ai}
}
```
<br>
## License
This project is licensed under Apache 2.0 with certain conditions. Refer to the "LICENSE" file in the root directory for detailed information. Note that `pitch_est.cc` contains modified code derived from [LPCNet](https://github.com/xiph/LPCNet), which is [BSD-2-Clause](https://spdx.org/licenses/BSD-2-Clause.html) and [BSD-3-Clause](https://spdx.org/licenses/BSD-3-Clause.html) licensed, refer to the NOTICES file in the root directory for detailed information.
<br>
[back-to-top]: https://img.shields.io/badge/-Back_to_top-gray?style=flat-square
[ten-framework-shield]: https://img.shields.io/github/stars/ten-framework/ten_framework?color=ffcb47&labelColor=gray&style=flat-square&logo=github
[ten-framework-banner]: https://github.com/user-attachments/assets/7c8f72d7-3993-4d01-8504-b71578a22944
[ten-framework-link]: https://github.com/ten-framework/ten_framework
[ten-vad-link]: https://github.com/ten-framework/ten-vad
[ten-vad-shield]: https://img.shields.io/github/stars/ten-framework/ten-vad?color=ffcb47&labelColor=gray&style=flat-square&logo=github
[ten-vad-banner]: https://github.com/user-attachments/assets/d45870e4-9453-4047-8163-08737f82863f
[ten-turn-detection-link]: https://github.com/ten-framework/ten-turn-detection
[ten-turn-detection-shield]: https://img.shields.io/github/stars/ten-framework/ten-turn-detection?color=ffcb47&labelColor=gray&style=flat-square&logo=github
[ten-turn-detection-banner]: https://github.com/user-attachments/assets/8d0ec716-5d0e-43e4-ad9a-d97b17305658
[ten-agent-link]: https://github.com/TEN-framework/ten-framework/tree/main/ai_agents
[ten-agent-banner]: https://github.com/user-attachments/assets/38de2207-939b-4702-a0aa-04491f5b5275
[tman-designer-banner]: https://github.com/user-attachments/assets/804c3543-0a47-42b7-b40b-ef32b742fb8f
[tman-designer-link]: https://github.com/TEN-framework/ten-framework/tree/main/core/src/ten_manager/designer_frontend
[ten-portal-link]: https://github.com/ten-framework/portal
[ten-portal-shield]: https://img.shields.io/github/stars/ten-framework/portal?color=ffcb47&labelColor=gray&style=flat-square&logo=github
[ten-portal-banner]: https://github.com/user-attachments/assets/e17d8aaa-5928-45dd-ac71-814928e26a89

View file

@ -1,46 +0,0 @@
#
# Copyright © 2025 Agora
# This file is part of TEN Framework, an open source project.
# Licensed under the Apache License, Version 2.0, with certain conditions.
# Refer to the "LICENSE" file in the root directory for more information.
#
cmake_minimum_required(VERSION 3.10)
get_filename_component(ROOT ${CMAKE_CURRENT_SOURCE_DIR}/../ ABSOLUTE)
project(ten_vad_demo)
add_executable(ten_vad_demo ${ROOT}/examples/main.c)
target_include_directories(ten_vad_demo PRIVATE "${ROOT}/include")
if(WIN32)
if(CMAKE_SIZEOF_VOID_P EQUAL 8)
target_link_libraries(ten_vad_demo "${ROOT}/lib/Windows/x64/ten_vad.lib")
else()
target_link_libraries(ten_vad_demo "${ROOT}/lib/Windows/x86/ten_vad.lib")
endif()
elseif(ANDROID)
if(CMAKE_SYSTEM_PROCESSOR STREQUAL "aarch64")
target_link_libraries(ten_vad_demo "${ROOT}/lib/Android/arm64-v8a/libten_vad.so")
else()
target_link_libraries(ten_vad_demo "${ROOT}/lib/Android/armeabi-v7a/libten_vad.so")
endif()
elseif(IOS)
target_link_libraries(ten_vad_demo "${ROOT}/lib/iOS/ten_vad.framework")
set_target_properties(ten_vad_demo PROPERTIES
XCODE_ATTRIBUTE_FRAMEWORK_SEARCH_PATHS "${ROOT}/lib/iOS"
XCODE_ATTRIBUTE_LD_RUNPATH_SEARCH_PATHS "@executable_path/Frameworks"
XCODE_ATTRIBUTE_CODE_SIGN_STYLE "Manual"
XCODE_ATTRIBUTE_DEVELOPMENT_TEAM "${CMAKE_XCODE_ATTRIBUTE_DEVELOPMENT_TEAM}"
XCODE_ATTRIBUTE_PRODUCT_BUNDLE_IDENTIFIER "com.yourcompany.ten_vad_demo"
XCODE_ATTRIBUTE_SUPPORTED_PLATFORMS "iphoneos"
XCODE_ATTRIBUTE_ARCHS "arm64"
)
elseif(APPLE)
target_link_libraries(ten_vad_demo "${ROOT}/lib/macOS/ten_vad.framework")
set_target_properties(ten_vad_demo PROPERTIES
INSTALL_RPATH "@loader_path"
BUILD_WITH_INSTALL_RPATH TRUE
)
elseif(UNIX)
target_link_libraries(ten_vad_demo "${ROOT}/lib/Linux/x64/libten_vad.so")
endif()

View file

@ -1,40 +0,0 @@
#!/bin/bash
#
# Copyright © 2025 Agora
# This file is part of TEN Framework, an open source project.
# Licensed under the Apache License, Version 2.0, with certain conditions.
# Refer to the "LICENSE" file in the root directory for more information.
#
set -eo pipefail
# Customize the arch and toolchain
arch=arm64-v8a
toolchain=aarch64-linux-android-clang
# arch=armeabi-v7a
# toolchain=arm-linux-android-clang
build_dir=build-android/$arch
rm -rf $build_dir
mkdir -p $build_dir
cd $build_dir
# Step 1: Build the demo
cmake ../../ \
-DANDROID_TOOLCHAIN_NAME=$toolchain \
-DCMAKE_TOOLCHAIN_FILE=$ANDROID_NDK/build/cmake/android.toolchain.cmake \
-G "Unix Makefiles"
cmake --build . --config Release
# Step 2: Run the demo
adb push ../../s0724-s0730.wav /data/local/tmp/
adb push ../../../lib/Android/${arch}/libten_vad.so /data/local/tmp/libten_vad.so &&
adb push ten_vad_demo /data/local/tmp/ &&
adb shell "cd /data/local/tmp && chmod +x ten_vad_demo && \
LD_LIBRARY_PATH=/data/local/tmp ./ten_vad_demo ./s0724-s0730.wav ./out.txt && \
exit 0"
adb pull /data/local/tmp/out.txt ./
cd ../../

View file

@ -1,30 +0,0 @@
#!/usr/bin/env bash
#
# Copyright © 2025 Agora
# This file is part of TEN Framework, an open source project.
# Licensed under the Apache License, Version 2.0, with certain conditions.
# Refer to the "LICENSE" file in the root directory for more information.
#
set -euo pipefail
work_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
build_dir="${work_dir}/build-ios"
mkdir -p "${build_dir}"
cd "${build_dir}"
# Step 1: Generate Xcode project for iOS device
echo "[Info] Generating Xcode project"
cmake "${work_dir}" \
-DCMAKE_SYSTEM_NAME=iOS \
-DCMAKE_OSX_SYSROOT="iphoneos" \
-DCMAKE_OSX_ARCHITECTURES="arm64" \
-DCMAKE_XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY="Apple Development" \
-DCMAKE_OSX_DEPLOYMENT_TARGET=12.1 \
-DCMAKE_INSTALL_RPATH="@executable_path/Frameworks" \
-DCMAKE_BUILD_WITH_INSTALL_RPATH=ON \
-G Xcode
# Step 2: Use Xcode to open the project in build-ios directory
# Step 3: Build and run the project in Xcode IDE

View file

@ -1,25 +0,0 @@
#!/bin/bash
#
# Copyright © 2025 Agora
# This file is part of TEN Framework, an open source project.
# Licensed under the Apache License, Version 2.0, with certain conditions.
# Refer to the "LICENSE" file in the root directory for more information.
#
set -euo pipefail
arch=x64
build_dir=build-linux/$arch
rm -rf $build_dir
mkdir -p $build_dir
cd $build_dir
# Step 1: Build the demo
cmake ../../
cmake --build . --config Release
# Step 2: Run the demo
export LD_LIBRARY_PATH=../../../lib/Linux/$arch
./ten_vad_demo ../../s0724-s0730.wav out.txt
cd ../../

View file

@ -1,32 +0,0 @@
#!/bin/bash
#
# Copyright © 2025 Agora
# This file is part of TEN Framework, an open source project.
# Licensed under the Apache License, Version 2.0, with certain conditions.
# Refer to the "LICENSE" file in the root directory for more information.
#
set -euo pipefail
# Customize the arch
arch=arm64
# arch=x86_64
build_dir=build-mac/$arch
rm -rf $build_dir
mkdir -p $build_dir
cd $build_dir
# Step 1: Build the demo
cmake ../../ \
-DCMAKE_CXX_COMPILER=/usr/bin/clang++ \
-DCMAKE_C_COMPILER=/usr/bin/clang \
-DCMAKE_OSX_ARCHITECTURES=${arch} \
-G Xcode
cmake --build . --config Release -- -UseModernBuildSystem=NO
# Step 2: Run the demo
export DYLD_FRAMEWORK_PATH="../../../lib/macOS/"
Release/ten_vad_demo ../../s0724-s0730.wav out.txt
cd ../../

View file

@ -1,74 +0,0 @@
@echo off
setlocal
@REM
@REM Copyright © 2025 Agora
@REM This file is part of TEN Framework, an open source project.
@REM Licensed under the Apache License, Version 2.0, with certain conditions.
@REM Refer to the "LICENSE" file in the root directory for more information.
@REM
@REM Customize the arch
set arch=x64
@REM set arch=x86
@REM step 1: Build the demo
set "build_dir=%~dp0\build-windows"
if exist "%build_dir%" rmdir /s /q "%build_dir%"
mkdir "%build_dir%"
cd /d "%build_dir%"
@REM Customize the Visual Studio version
@REM REM VS 2017
@REM if %arch% == x64 (
@REM cmake .. -G "Visual Studio 15 2017" -A x64
@REM ) else if %arch% == x86 (
@REM cmake .. -G "Visual Studio 15 2017" -A Win32
@REM )
REM VS 2019
if %arch% == x64 (
cmake .. -G "Visual Studio 16 2019" -A x64
) else if %arch% == x86 (
cmake .. -G "Visual Studio 16 2019" -A Win32
)
@REM REM VS 2022
@REM if %arch% == x64 (
@REM cmake .. -G "Visual Studio 17 2022" -A x64
@REM ) else if %arch% == x86 (
@REM cmake .. -G "Visual Studio 17 2022" -A Win32
@REM )
cmake --build . --config Release
cd ..
@REM step 2: Run the demo
pushd "%~dp0"
copy /Y "s0724-s0730.wav" "%build_dir%\Release"
copy /Y "..\lib\Windows\%arch%\ten_vad.dll" "%build_dir%\Release"
if errorlevel 1 (
echo [Error] copy file failed
popd
exit /b 1
)
cd /d "%build_dir%\Release"
if not exist "ten_vad_demo.exe" (
echo Error: ten_vad_demo.exe not found
exit /b 1
)
if not exist "s0724-s0730.wav" (
echo Error: s0724-s0730.wav not found
exit /b 1
)
ten_vad_demo.exe "s0724-s0730.wav" out.txt
if errorlevel 1 (
echo Error: ten_vad_demo.exe failed
exit /b 1
)
cd /d "%~dp0"
popd
exit /b 0

Binary file not shown.

Before

Width:  |  Height:  |  Size: 192 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 174 KiB

View file

@ -1,306 +0,0 @@
//
// Copyright © 2025 Agora
// This file is part of TEN Framework, an open source project.
// Licensed under the Apache License, Version 2.0, with certain conditions.
// Refer to the "LICENSE" file in the root directory for more information.
//
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <time.h>
#include <inttypes.h>
#include <string.h> // memcmp
#ifdef _WIN32
#include <windows.h>
#endif
#include "ten_vad.h"
#if defined(__APPLE__)
#include <TargetConditionals.h>
#if TARGET_OS_IPHONE
#include "sample_array.h"
#endif
#endif
const int hop_size = 256; // 16 ms per frame
uint64_t get_timestamp_ms()
{
#ifdef _WIN32
LARGE_INTEGER frequency;
LARGE_INTEGER counter;
QueryPerformanceFrequency(&frequency);
QueryPerformanceCounter(&counter);
return (uint64_t)(counter.QuadPart * 1000 / frequency.QuadPart);
#else
struct timespec ts;
uint64_t millis;
clock_gettime(CLOCK_MONOTONIC, &ts);
millis = ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
return millis;
#endif
}
// define RIFF header
#pragma pack(push, 1)
typedef struct
{
char chunk_id[4]; // should be "RIFF"
uint32_t chunk_size; // file total size - 8
char format[4]; // should be "WAVE"
} riff_header_t;
// define each sub chunk header
typedef struct
{
char id[4]; // should be "fmt " or "data"
uint32_t size; // chunk data size
} chunk_header_t;
#pragma pack(pop)
// define WAV file info we care about
typedef struct
{
uint16_t audio_format; // audio format (e.g. PCM=1)
uint16_t num_channels; // number of channels
uint32_t sample_rate; // sample rate
uint32_t byte_rate; // byte rate
uint16_t block_align; // block align
uint16_t bits_per_sample; // bits per sample
uint32_t data_size; // data size
long data_offset; // data offset in file
} wav_info_t;
int read_wav_file(FILE *fp, wav_info_t *info);
int vad_process(int16_t *input_buf, uint32_t frame_num,
float *out_probs, int32_t *out_flags,
float *use_time)
{
printf("tenvadsrc version: %s\n", ten_vad_get_version());
void *ten_vad_handle = NULL;
float voice_threshold = 0.5f;
ten_vad_create(&ten_vad_handle, hop_size, voice_threshold);
uint64_t start = get_timestamp_ms();
for (int i = 0; i < frame_num; ++i)
{
int16_t *audio_data = input_buf + i * hop_size;
int res = ten_vad_process(ten_vad_handle, audio_data, hop_size,
&out_probs[i], &out_flags[i]);
if (res == 0)
{
printf("[%d] %0.6f, %d\n", i, out_probs[i], out_flags[i]);
}
else
{
printf("ten_vad_process failed res %d\n", res);
}
}
uint64_t end = get_timestamp_ms();
*use_time = (float)(end - start);
ten_vad_destroy(&ten_vad_handle);
ten_vad_handle = NULL;
return 0;
}
int test_with_wav(int argc, char *argv[])
{
if (argc < 3)
{
printf("Warning: Test.exe input.wav output.txt\n");
return 0;
}
char *input_file = argv[1];
char *out_file = argv[2];
FILE *fp = fopen(input_file, "rb");
if (fp == NULL)
{
printf("Failed to open input file: %s\n", input_file);
return 1;
}
fseek(fp, 0, SEEK_SET);
wav_info_t info;
if (read_wav_file(fp, &info) != 0)
{
printf("Failed to read WAV file header\n");
fclose(fp);
return 1;
}
uint32_t byte_num = info.data_size;
printf("WAV file byte num: %d\n", byte_num);
char *input_buf = (char *)malloc(byte_num);
fseek(fp, info.data_offset, SEEK_SET);
fread(input_buf, 1, byte_num, fp);
fclose(fp);
fp = NULL;
uint32_t sample_num = byte_num / sizeof(int16_t);
float total_audio_time = (float)sample_num / 16.0;
printf("total_audio_time: %.2f(ms)\n", total_audio_time);
uint32_t frame_num = sample_num / hop_size;
printf("Audio frame Num: %d\n", frame_num);
float *out_probs = (float *)malloc(frame_num * sizeof(float));
int32_t *out_flags = (int32_t *)malloc(frame_num * sizeof(int32_t)); // Output flags are binary speech indicators (0 for non-speech signal, 1 for speech signal)
float use_time = .0;
vad_process((int16_t *)input_buf, frame_num,
out_probs, out_flags,
&use_time);
float rtf = use_time / total_audio_time;
printf("Consuming time: %f(ms), audio-time: %.2f(ms), =====> RTF: %0.6f\n",
use_time, total_audio_time, rtf);
FILE *fout = fopen(out_file, "w");
if (fout != NULL)
{
for (int i = 0; i < frame_num; i++)
{
fprintf(fout, "[%d] %0.6f, %d\n", i, out_probs[i], out_flags[i]);
}
fclose(fout);
fout = NULL;
}
free(input_buf);
free(out_probs);
free(out_flags);
return 0;
}
#if TARGET_OS_IPHONE
// Used for iOS APP demo
int test_with_array()
{
char *input_buf = (char *)sample_array;
uint32_t byte_num = sizeof(sample_array) / sizeof(sample_array[0]);
printf("WAV file byte num: %d\n", byte_num);
uint32_t sample_num = byte_num / sizeof(int16_t);
float total_audio_time = (float)sample_num / 16.0;
printf("total_audio_time: %.2f(ms)\n", total_audio_time);
uint32_t frame_num = sample_num / hop_size;
printf("Audio frame Num: %d\n", frame_num);
float *out_probs = (float *)malloc(frame_num * sizeof(float));
int32_t *out_flags = (int32_t *)malloc(frame_num * sizeof(int32_t));
float use_time = .0;
vad_process((int16_t *)input_buf, frame_num,
out_probs, out_flags,
&use_time);
float rtf = use_time / total_audio_time;
printf("Consuming time: %f(ms), audio-time: %.2f(ms), =====> RTF: %0.6f\n",
use_time, total_audio_time, rtf);
return 0;
}
#endif
int main(int argc, char *argv[])
{
#if TARGET_OS_IPHONE
return test_with_array();
#else
return test_with_wav(argc, argv);
#endif
}
// function to read WAV file info
int read_wav_file(FILE *fp, wav_info_t *info)
{
if (fp == NULL || info == NULL)
return -1;
// save current file position
long orig_pos = ftell(fp);
fseek(fp, 0, SEEK_SET);
// read RIFF header
riff_header_t riff;
if (fread(&riff, sizeof(riff_header_t), 1, fp) != 1)
{
fprintf(stderr, "Can not read RIFF head\n");
fseek(fp, orig_pos, SEEK_SET);
return -1;
}
// verify RIFF/WAVE format
if (memcmp(riff.chunk_id, "RIFF", 4) != 0 ||
memcmp(riff.format, "WAVE", 4) != 0)
{
fprintf(stderr, "not a valid RIFF/WAVE file\n");
fseek(fp, orig_pos, SEEK_SET);
return -1;
}
// initialize, mark chunks not found yet
int fmt_found = 0, data_found = 0;
memset(info, 0, sizeof(wav_info_t));
// iterate all chunks
while (!feof(fp))
{
chunk_header_t chunk;
if (fread(&chunk, sizeof(chunk_header_t), 1, fp) != 1)
{
break; // read failed, maybe end of file
}
// check if it's fmt chunk
if (memcmp(chunk.id, "fmt ", 4) == 0)
{
// read fmt data
fmt_found = 1;
if (chunk.size < 16)
{
fprintf(stderr, "fmt chunk size is abnormal\n");
fseek(fp, orig_pos, SEEK_SET);
return -1;
}
// read fmt parameters
if (fread(&info->audio_format, 2, 1, fp) != 1 ||
fread(&info->num_channels, 2, 1, fp) != 1 ||
fread(&info->sample_rate, 4, 1, fp) != 1 ||
fread(&info->byte_rate, 4, 1, fp) != 1 ||
fread(&info->block_align, 2, 1, fp) != 1 ||
fread(&info->bits_per_sample, 2, 1, fp) != 1)
{
fprintf(stderr, "failed to read fmt data\n");
fseek(fp, orig_pos, SEEK_SET);
return -1;
}
// skip fmt extension data
if (chunk.size > 16)
{
fseek(fp, chunk.size - 16, SEEK_CUR);
}
}
// check if it's data chunk
else if (memcmp(chunk.id, "data", 4) == 0)
{
data_found = 1;
info->data_size = chunk.size;
info->data_offset = ftell(fp); // record data start position
break; // found data chunk, can exit loop
}
// other chunks, skip
else
{
// consider byte alignment, pad odd size
fseek(fp, (chunk.size + (chunk.size % 2)), SEEK_CUR);
}
}
// check if necessary chunks are found
if (!fmt_found)
{
fprintf(stderr, "fmt chunk not found\n");
fseek(fp, orig_pos, SEEK_SET);
return -1;
}
if (!data_found)
{
fprintf(stderr, "data chunk not found\n");
fseek(fp, orig_pos, SEEK_SET);
return -1;
}
// restore original file position
fseek(fp, orig_pos, SEEK_SET);
return 0;
}

View file

@ -1,215 +0,0 @@
#
# Copyright © 2025 Agora
# This file is part of TEN Framework, an open source project.
# Licensed under the Apache License, Version 2.0, with certain conditions.
# Refer to the "LICENSE" file in the root directory for more information.
#
import os, glob, sys, torchaudio
import numpy as np
import scipy.io.wavfile as Wavfile
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
os.system('git clone https://github.com/snakers4/silero-vad.git') # Clone the silero-vad repo, using Silero V5
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "./silero-vad/src")))
from silero_vad.utils_vad import VADIterator, init_jit_model
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../include")))
from ten_vad import TenVad
def convert_label_to_framewise(label_file, hop_size):
frame_duration = hop_size / 16000
with open(label_file, "r") as f:
lines = f.readlines()
content = lines[0].strip().split(",")[1:]
start = np.array(
content[::3], dtype=float
) # Start point of each audio segment
end = np.array(
content[1:][::3], dtype=float
) # End point of each audio segment
lab_manual = np.array(
content[2:][::3], dtype=int
) # label, 0/1 stands for non-speech or speech, respectively
assert (
len(start) == len(end)
and len(start) == len(lab_manual)
and len(end) == len(lab_manual)
)
num = np.array(
np.round(((end - start) / frame_duration)), dtype=np.int32
) # get number of frames of each audio segment
label_framewise = np.array([])
for segment_idx in range(len(num)):
cur_lab = int(lab_manual[segment_idx])
num_segment = num[segment_idx]
if cur_lab == 1:
vad_result_this_segment = np.ones(num_segment)
elif cur_lab == 0:
vad_result_this_segment = np.zeros(num_segment)
label_framewise = np.append(label_framewise, vad_result_this_segment)
frame_num = min(
label_framewise.__len__(), int((end[-1] - start[0]) / frame_duration)
)
label_framewise = label_framewise[:frame_num]
return label_framewise
def read_file(file_path):
with open(file_path, "r") as f:
lines = f.readlines()
lines_arr = np.array([])
for line in lines:
lines_arr = np.append(lines_arr, float(line.strip()))
return lines_arr
def get_precision_recall(VAD_result, label, threshold):
vad_result_hard = np.where(VAD_result >= threshold, 1, 0)
# Compute confusion matrix
TN, FP, FN, TP = confusion_matrix(label, vad_result_hard).ravel()
# Compute precision, recall, false positive rate and false negative rate
precision = TP / (TP + FP) if (TP + FP) > 0 else 0
recall = TP / (TP + FN) if (TP + FN) > 0 else 0
FPR = FP / (FP + TN) if (FP + TN) > 0 else 0
FNR = FN / (TP + FN) if (TP + FN) > 0 else 0
return precision, recall, FPR, FNR
def silero_vad_inference_single_file(wav_path):
current_directory = os.path.dirname(os.path.abspath(__file__))
model = init_jit_model(f'{current_directory}/silero-vad/src/silero_vad/data/silero_vad.jit')
vad_iterator = VADIterator(model)
window_size_samples = 512
speech_probs = np.array([])
wav, sr = torchaudio.load(wav_path)
wav = wav.squeeze(0)
for i in range(0, len(wav), window_size_samples):
chunk = wav[i: i+ window_size_samples]
if len(chunk) < window_size_samples:
break
speech_prob = model(chunk, sr).item()
speech_probs = np.append(speech_probs, speech_prob)
vad_iterator.reset_states() # reset model states after each audio
return speech_probs, window_size_samples
def ten_vad_process_wav(ten_vad_instance, wav_path, hop_size=256):
_, data = Wavfile.read(wav_path)
num_frames = data.shape[0] // hop_size
voice_prob_arr = np.array([])
for i in range(num_frames):
input_data = data[i * hop_size: (i + 1) * hop_size]
voice_prob, _ = ten_vad_instance.process(input_data)
voice_prob_arr = np.append(voice_prob_arr, voice_prob)
return voice_prob_arr
if __name__ == "__main__":
# Get the directory of the script
script_dir = os.path.dirname(os.path.abspath(__file__))
# TEN-VAD-TestSet dir
test_dir = f"{script_dir}/../testset"
# Initialization
hop_size = 256
threshold = 0.5
label_all, vad_result_ten_vad_all = np.array([]), np.array([])
label_hop_512_all, vad_result_silero_vad_all = np.array([]), np.array([])
wav_list = glob.glob(f"{test_dir}/*.wav")
# The WebRTC VAD is from the latest version of WebRTC and is not plotted here
print("Start processing")
for wav_path in wav_list:
# Running TEN VAD
ten_vad_instance = TenVad(hop_size, threshold)
label_file = wav_path.replace(".wav", ".scv")
label = convert_label_to_framewise(
label_file, hop_size=hop_size
) # Convert the VAD label to frame-wise one
vad_result_ten_vad = ten_vad_process_wav(
ten_vad_instance, wav_path, hop_size=hop_size
)
frame_num = min(label.__len__(), vad_result_ten_vad.__len__())
vad_result_ten_vad_all = np.append(
vad_result_ten_vad_all, vad_result_ten_vad[1:frame_num]
)
label_all = np.append(label_all, label[:frame_num - 1])
del ten_vad_instance # To prevent getting different results of each run
# Running Silero VAD
label_hop_512 = convert_label_to_framewise(
label_file, hop_size=512
) # Convert the VAD label to frame-wise one for Silero VAD
vad_result_silero_vad, _ = silero_vad_inference_single_file(wav_path)
frame_num_silero_vad = min(label_hop_512.__len__(), vad_result_silero_vad.__len__())
vad_result_silero_vad_all = np.append(vad_result_silero_vad_all, vad_result_silero_vad[:frame_num_silero_vad])
label_hop_512_all = np.append(label_hop_512_all, label_hop_512[:frame_num_silero_vad])
# Compute Precision and Recall
threshold_arr = np.arange(0, 1.01, 0.01)
pr_data_arr = np.zeros((threshold_arr.__len__(), 3))
pr_data_silero_vad_arr = np.zeros((threshold_arr.__len__(), 3))
for ind, threshold in enumerate(threshold_arr):
precision, recall, FPR, FNR = get_precision_recall(vad_result_ten_vad_all, label_all, threshold)
pr_data_arr[ind] = precision, recall, threshold
precision_silero_vad, recall_silero_vad, FPR_silero_vad, FNR_silero_vad = get_precision_recall(vad_result_silero_vad_all, label_hop_512_all, threshold)
pr_data_silero_vad_arr[ind] = precision_silero_vad, recall_silero_vad, threshold
# Plot PR Curve
print("Plotting PR Curve")
pr_data_arr_to_plot = pr_data_arr[:-1]
plt.plot(
pr_data_arr_to_plot[:, 1],
pr_data_arr_to_plot[:, 0],
color="red",
label="TEN VAD",
) # Precision on y-axis, Recall on x-axis
pr_data_silero_vad_arr_to_plot = pr_data_silero_vad_arr[:-1]
plt.plot(
pr_data_silero_vad_arr_to_plot[:, 1], # Recall (x-axis)
pr_data_silero_vad_arr_to_plot[:, 0], # Precision (y-axis)
color="blue",
label="Silero VAD",
)
plt.xlabel("Recall", fontsize=14, fontweight="bold", color="black")
plt.ylabel("Precision", fontsize=14, fontweight="bold", color="black")
legend = plt.legend()
legend.get_texts()[0].set_fontweight("bold")
legend.get_texts()[1].set_fontweight("bold")
plt.grid(True)
plt.xlim(0.65, 1)
plt.ylim(0.7, 1)
plt.title(
"Precision-Recall Curve of TEN VAD on TEN-VAD-TestSet",
fontsize=12,
color="black",
fontweight="bold",
)
save_path = f"{script_dir}/PR_Curves.png"
plt.savefig(save_path, dpi=300, bbox_inches="tight")
print(f"PR Curves png file saved, save path: {save_path}")
# Save the PR data to txt file
pr_data_save_path = f"{script_dir}/PR_data_TEN_VAD.txt"
with open(pr_data_save_path, "w") as f:
for ind in range(pr_data_arr.shape[0]):
precision, recall, threshold = (
pr_data_arr[ind, 0],
pr_data_arr[ind, 1],
pr_data_arr[ind, 2],
)
f.write(f"{threshold:.2f} {precision:.4f} {recall:.4f}\n")
print("Processing done!")

View file

@ -1,4 +0,0 @@
scipy>=1.5.0
scikit-learn
matplotlib
torchaudio

File diff suppressed because it is too large Load diff

View file

@ -1,27 +0,0 @@
#
# Copyright © 2025 Agora
# This file is part of TEN Framework, an open source project.
# Licensed under the Apache License, Version 2.0, with certain conditions.
# Refer to the "LICENSE" file in the root directory for more information.
#
import sys, os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../include")))
from ten_vad import TenVad
import scipy.io.wavfile as Wavfile
if __name__ == "__main__":
input_file, out_path = sys.argv[1], sys.argv[2]
sr, data = Wavfile.read(input_file)
hop_size = 256 # 16 ms per frame
threshold = 0.5
ten_vad_instance = TenVad(hop_size, threshold) # Create a TenVad instance
num_frames = data.shape[0] // hop_size
# Streaming inference
with open(out_path, "w") as f:
for i in range(num_frames):
audio_data = data[i * hop_size: (i + 1) * hop_size]
out_probability, out_flag = ten_vad_instance.process(audio_data) # Out_flag is speech indicator (0 for non-speech signal, 1 for speech signal)
print("[%d] %0.6f, %d" % (i, out_probability, out_flag))
f.write("[%d] %0.6f, %d\n" % (i, out_probability, out_flag))

View file

@ -1,529 +0,0 @@
#!/usr/bin/env node
//
// Copyright © 2025 Agora
// This file is part of TEN Framework, an open source project.
// Licensed under the Apache License, Version 2.0, with certain conditions.
// Refer to the "LICENSE" file in the root directory for more information.
//
/**
* TEN VAD WebAssembly Node.js Test
* Simplified and clean version based on main.c
*/
const fs = require('fs');
const path = require('path');
// Configuration
const HOP_SIZE = 256; // 16ms per frame
const VOICE_THRESHOLD = 0.5; // Voice detection threshold
// WASM module paths
const WASM_DIR = './../lib/Web';
const WASM_JS_FILE = path.join(WASM_DIR, 'ten_vad.js');
const WASM_BINARY_FILE = path.join(WASM_DIR, 'ten_vad.wasm');
// Global state
let vadModule = null;
let vadHandle = null;
let vadHandlePtr = null;
// ============================================================================
// UTILITY FUNCTIONS
// ============================================================================
function getTimestamp() {
return Date.now();
}
function addHelperFunctions() {
if (!vadModule.getValue) {
vadModule.getValue = function(ptr, type) {
switch (type) {
case 'i32': return vadModule.HEAP32[ptr >> 2];
case 'float': return vadModule.HEAPF32[ptr >> 2];
default: throw new Error(`Unsupported type: ${type}`);
}
};
}
if (!vadModule.UTF8ToString) {
vadModule.UTF8ToString = function(ptr) {
if (!ptr) return '';
let result = '';
let i = ptr;
while (vadModule.HEAPU8[i]) {
result += String.fromCharCode(vadModule.HEAPU8[i++]);
}
return result;
};
}
}
// ============================================================================
// AUDIO GENERATION
// ============================================================================
function generateTestAudio(durationMs = 5000) {
const sampleRate = 16000;
const totalSamples = Math.floor(durationMs * sampleRate / 1000);
const audioData = new Int16Array(totalSamples);
console.log(`Generating ${totalSamples} samples for ${durationMs}ms audio...`);
for (let i = 0; i < totalSamples; i++) {
const t = i / sampleRate;
let sample = 0;
if (t < 2.0) {
// Voice frequencies (440Hz + 880Hz)
sample = Math.sin(2 * Math.PI * 440 * t) * 8000 +
Math.sin(2 * Math.PI * 880 * t) * 4000;
} else if (t < 3.0) {
// Noise
sample = (Math.random() - 0.5) * 3000;
} else if (t < 4.0) {
// Mixed voice (220Hz + 660Hz)
sample = Math.sin(2 * Math.PI * 220 * t) * 6000 +
Math.sin(2 * Math.PI * 660 * t) * 3000;
} else {
// Silence with minimal noise
sample = Math.random() * 50;
}
audioData[i] = Math.max(-32768, Math.min(32767, Math.floor(sample)));
}
return audioData;
}
// ============================================================================
// VAD OPERATIONS
// ============================================================================
function getVADVersion() {
if (!vadModule) return "unknown";
try {
const versionPtr = vadModule._ten_vad_get_version();
return vadModule.UTF8ToString(versionPtr);
} catch (error) {
return "unknown";
}
}
function createVADInstance() {
try {
vadHandlePtr = vadModule._malloc(4);
const result = vadModule._ten_vad_create(vadHandlePtr, HOP_SIZE, VOICE_THRESHOLD);
if (result === 0) {
vadHandle = vadModule.getValue(vadHandlePtr, 'i32');
return true;
} else {
console.error(`VAD creation failed with code: ${result}`);
vadModule._free(vadHandlePtr);
return false;
}
} catch (error) {
console.error(`Error creating VAD instance: ${error.message}`);
return false;
}
}
function destroyVADInstance() {
if (vadHandlePtr && vadModule) {
vadModule._ten_vad_destroy(vadHandlePtr);
vadModule._free(vadHandlePtr);
vadHandlePtr = null;
vadHandle = null;
}
}
async function processAudio(inputBuf, frameNum, outProbs, outFlags) {
console.log(`VAD version: ${getVADVersion()}`);
if (!createVADInstance()) {
return -1;
}
const startTime = getTimestamp();
for (let i = 0; i < frameNum; i++) {
const frameStart = i * HOP_SIZE;
const frameData = inputBuf.slice(frameStart, frameStart + HOP_SIZE);
const audioPtr = vadModule._malloc(HOP_SIZE * 2);
const probPtr = vadModule._malloc(4);
const flagPtr = vadModule._malloc(4);
try {
vadModule.HEAP16.set(frameData, audioPtr / 2);
const result = vadModule._ten_vad_process(
vadHandle, audioPtr, HOP_SIZE, probPtr, flagPtr
);
if (result === 0) {
const probability = vadModule.getValue(probPtr, 'float');
const flag = vadModule.getValue(flagPtr, 'i32');
outProbs[i] = probability;
outFlags[i] = flag;
console.log(`[${i}] ${probability.toFixed(6)}, ${flag}`);
} else {
console.error(`Frame ${i} processing failed with code: ${result}`);
outProbs[i] = 0.0;
outFlags[i] = 0;
}
} finally {
vadModule._free(audioPtr);
vadModule._free(probPtr);
vadModule._free(flagPtr);
}
}
const endTime = getTimestamp();
const processingTime = endTime - startTime;
destroyVADInstance();
return processingTime;
}
// ============================================================================
// RESULT HANDLING
// ============================================================================
function printResults(processingTime, totalAudioTime, outFlags, frameNum) {
const rtf = processingTime / totalAudioTime;
const voiceFrames = outFlags.filter(flag => flag === 1).length;
const voicePercentage = (voiceFrames / frameNum * 100).toFixed(1);
console.log(`\n=== Processing Results ===`);
console.log(`Time: ${processingTime}ms, Audio: ${totalAudioTime.toFixed(2)}ms, RTF: ${rtf.toFixed(6)}`);
console.log(`Voice frames: ${voiceFrames}/${frameNum} (${voicePercentage}%)`);
}
function saveResults(outProbs, outFlags, frameNum, filename = 'out.txt') {
let output = '';
for (let i = 0; i < frameNum; i++) {
output += `[${i}] ${outProbs[i].toFixed(6)}, ${outFlags[i]}\n`;
}
try {
fs.writeFileSync(filename, output);
console.log(`Results saved to ${filename}`);
} catch (error) {
console.error(`Failed to save results: ${error.message}`);
}
}
// ============================================================================
// TEST FUNCTIONS
// ============================================================================
async function testWithArray() {
console.log("=== Array Test ===\n");
const inputBuf = generateTestAudio(5000);
const byteNum = inputBuf.byteLength;
const sampleNum = byteNum / 2;
const totalAudioTime = sampleNum / 16.0;
const frameNum = Math.floor(sampleNum / HOP_SIZE);
console.log(`Audio info: ${byteNum} bytes, ${frameNum} frames, ${totalAudioTime.toFixed(2)}ms`);
const outProbs = new Float32Array(frameNum);
const outFlags = new Int32Array(frameNum);
const processingTime = await processAudio(inputBuf, frameNum, outProbs, outFlags);
if (processingTime > 0) {
printResults(processingTime, totalAudioTime, outFlags, frameNum);
}
return 0;
}
// WAV File parsing utilities
function parseWAVHeader(buffer) {
if (buffer.length < 44) {
throw new Error('Invalid WAV file: too small');
}
// Check RIFF header
const riffHeader = buffer.toString('ascii', 0, 4);
if (riffHeader !== 'RIFF') {
throw new Error('Invalid WAV file: missing RIFF header');
}
// Check WAVE format
const waveHeader = buffer.toString('ascii', 8, 12);
if (waveHeader !== 'WAVE') {
throw new Error('Invalid WAV file: not WAVE format');
}
let offset = 12;
let dataOffset = -1;
let dataSize = 0;
let sampleRate = 0;
let channels = 0;
let bitsPerSample = 0;
// Parse chunks
while (offset < buffer.length - 8) {
const chunkId = buffer.toString('ascii', offset, offset + 4);
const chunkSize = buffer.readUInt32LE(offset + 4);
if (chunkId === 'fmt ') {
// Format chunk
const audioFormat = buffer.readUInt16LE(offset + 8);
channels = buffer.readUInt16LE(offset + 10);
sampleRate = buffer.readUInt32LE(offset + 12);
bitsPerSample = buffer.readUInt16LE(offset + 22);
if (audioFormat !== 1) {
throw new Error('Unsupported WAV format: only PCM is supported');
}
if (bitsPerSample !== 16) {
throw new Error('Unsupported bit depth: only 16-bit is supported');
}
} else if (chunkId === 'data') {
// Data chunk
dataOffset = offset + 8;
dataSize = chunkSize;
break;
}
offset += 8 + chunkSize;
// Align to even byte boundary
if (chunkSize % 2 === 1) {
offset++;
}
}
if (dataOffset === -1) {
throw new Error('Invalid WAV file: no data chunk found');
}
return {
sampleRate,
channels,
bitsPerSample,
dataOffset,
dataSize,
totalSamples: dataSize / (bitsPerSample / 8),
samplesPerChannel: dataSize / (bitsPerSample / 8) / channels
};
}
async function testWithWAV(inputFile, outputFile) {
console.log("=== WAV File Test ===\n");
if (!fs.existsSync(inputFile)) {
console.error(`Input file not found: ${inputFile}`);
return 1;
}
try {
const buffer = fs.readFileSync(inputFile);
// Parse WAV header properly
const wavInfo = parseWAVHeader(buffer);
console.log(`WAV Format: ${wavInfo.channels} channel(s), ${wavInfo.sampleRate}Hz, ${wavInfo.bitsPerSample}-bit`);
console.log(`Total samples: ${wavInfo.totalSamples}, samples per channel: ${wavInfo.samplesPerChannel}`);
// Validate format requirements
if (wavInfo.sampleRate !== 16000) {
console.warn(`Warning: Sample rate is ${wavInfo.sampleRate}Hz, expected 16000Hz`);
}
if (wavInfo.channels !== 1) {
console.warn(`Warning: ${wavInfo.channels} channels detected, only first channel will be used`);
}
// Extract audio data
const audioBuffer = buffer.slice(wavInfo.dataOffset, wavInfo.dataOffset + wavInfo.dataSize);
const inputBuf = new Int16Array(audioBuffer.buffer.slice(audioBuffer.byteOffset));
// Calculate correct sample number (for mono audio)
const sampleNum = wavInfo.channels === 1 ?
wavInfo.samplesPerChannel :
Math.floor(wavInfo.samplesPerChannel); // Use only first channel if stereo
const totalAudioTime = sampleNum / wavInfo.sampleRate * 1000; // in milliseconds
const frameNum = Math.floor(sampleNum / HOP_SIZE);
console.log(`Audio info: ${audioBuffer.length} bytes, ${sampleNum} samples, ${frameNum} frames, ${totalAudioTime.toFixed(2)}ms`);
// If stereo, extract only the first channel
let processedInput = inputBuf;
if (wavInfo.channels > 1) {
console.log(`Extracting mono from ${wavInfo.channels} channels...`);
processedInput = new Int16Array(Math.floor(inputBuf.length / wavInfo.channels));
for (let i = 0; i < processedInput.length; i++) {
processedInput[i] = inputBuf[i * wavInfo.channels]; // Take first channel
}
}
const outProbs = new Float32Array(frameNum);
const outFlags = new Int32Array(frameNum);
const processingTime = await processAudio(processedInput, frameNum, outProbs, outFlags);
if (processingTime > 0) {
printResults(processingTime, totalAudioTime, outFlags, frameNum);
saveResults(outProbs, outFlags, frameNum, outputFile);
}
return 0;
} catch (error) {
console.error(`Error processing WAV file: ${error.message}`);
return 1;
}
}
async function runBenchmark() {
console.log("=== Performance Benchmark ===\n");
if (!createVADInstance()) return;
const testData = new Int16Array(HOP_SIZE);
for (let i = 0; i < HOP_SIZE; i++) {
testData[i] = Math.sin(2 * Math.PI * 440 * i / 16000) * 8000;
}
const testCases = [100, 1000, 10000];
for (const numFrames of testCases) {
const audioPtr = vadModule._malloc(HOP_SIZE * 2);
const probPtr = vadModule._malloc(4);
const flagPtr = vadModule._malloc(4);
vadModule.HEAP16.set(testData, audioPtr / 2);
const startTime = getTimestamp();
for (let i = 0; i < numFrames; i++) {
vadModule._ten_vad_process(vadHandle, audioPtr, HOP_SIZE, probPtr, flagPtr);
}
const endTime = getTimestamp();
const totalTime = endTime - startTime;
const avgTime = totalTime / numFrames;
// Calculate RTF (Real-time Factor)
// Each frame represents 16ms of audio (HOP_SIZE=256 samples at 16kHz)
const frameAudioTime = (HOP_SIZE / 16000) * 1000; // 16ms
const totalAudioTime = numFrames * frameAudioTime;
const rtf = totalTime / totalAudioTime;
console.log(`${numFrames} frames: ${totalTime}ms total, ${avgTime.toFixed(3)}ms/frame, RTF: ${rtf.toFixed(3)}`);
vadModule._free(audioPtr);
vadModule._free(probPtr);
vadModule._free(flagPtr);
}
destroyVADInstance();
}
// ============================================================================
// MODULE INITIALIZATION
// ============================================================================
async function loadModule() {
try {
console.log("Loading WebAssembly module...");
if (!fs.existsSync(WASM_JS_FILE)) {
throw new Error(`ten_vad.js not found at ${WASM_JS_FILE}`);
}
if (!fs.existsSync(WASM_BINARY_FILE)) {
throw new Error(`ten_vad.wasm not found at ${WASM_BINARY_FILE}`);
}
// Read and modify the module file for Node.js compatibility
const wasmJsContent = fs.readFileSync(WASM_JS_FILE, 'utf8');
const modifiedContent = wasmJsContent
.replace(/import\.meta\.url/g, `"${path.resolve(WASM_JS_FILE)}"`)
.replace(/export default createVADModule;/, 'module.exports = createVADModule;');
// Write temporary file
const tempPath = './ten_vad_temp.js';
fs.writeFileSync(tempPath, modifiedContent);
// Load WASM binary
const wasmBinary = fs.readFileSync(WASM_BINARY_FILE);
// Load module
const createVADModule = require(path.resolve(tempPath));
vadModule = await createVADModule({
wasmBinary: wasmBinary,
locateFile: (filePath) => filePath.endsWith('.wasm') ? WASM_BINARY_FILE : filePath,
noInitialRun: false,
noExitRuntime: true
});
// Cleanup
fs.unlinkSync(tempPath);
// Add missing helper functions
addHelperFunctions();
console.log(`Module loaded successfully. Version: ${getVADVersion()}\n`);
return true;
} catch (error) {
console.error(`Failed to load module: ${error.message}`);
return false;
}
}
// ============================================================================
// MAIN FUNCTION
// ============================================================================
async function main() {
const args = process.argv.slice(2);
// Initialize module
if (!await loadModule()) {
process.exit(1);
}
try {
if (args.length >= 2) {
// Test with WAV file
const [inputFile, outputFile] = args;
console.log(`Input: ${inputFile}, Output: ${outputFile}\n`);
await testWithWAV(inputFile, outputFile);
} else {
// Test with generated array
await testWithArray();
}
await runBenchmark();
return 0;
} catch (error) {
console.error(`Test failed: ${error.message}`);
return 1;
}
}
// ============================================================================
// EXECUTION
// ============================================================================
if (require.main === module) {
main().then(exitCode => {
process.exit(exitCode);
}).catch(error => {
console.error(`Fatal error: ${error.message}`);
process.exit(1);
});
}
module.exports = { main, testWithArray, testWithWAV, runBenchmark };

View file

@ -1,24 +0,0 @@
#
# Copyright © 2025 Agora
# This file is part of TEN Framework, an open source project.
# Licensed under the Apache License, Version 2.0, with certain conditions.
# Refer to the "LICENSE" file in the root directory for more information.
#
cmake_minimum_required(VERSION 3.10)
get_filename_component(ROOT ${CMAKE_CURRENT_SOURCE_DIR}/../ ABSOLUTE)
project(ten_vad)
set(CMAKE_BUILD_TYPE Release)
add_compile_options(-Wno-write-strings -Wno-unused-result)
include_directories(${ROOT}/src)
include_directories(${ROOT}/include)
include_directories(${ORT_ROOT}/include)
file(GLOB LIBRARY_SOURCES "${ROOT}/src/*.cc" "${ROOT}/src/*.c")
add_library(ten_vad SHARED ${LIBRARY_SOURCES})
link_directories(${ORT_ROOT}/lib)
target_link_libraries(ten_vad "${ORT_ROOT}/lib/libonnxruntime.so")
set(EXECUTABLE_SOURCES ${ROOT}/examples/main.c)
add_executable(ten_vad_demo ${EXECUTABLE_SOURCES})
target_link_libraries(ten_vad_demo ten_vad)

View file

@ -1,37 +0,0 @@
#!/bin/bash
#
# Copyright © 2025 Agora
# This file is part of TEN Framework, an open source project.
# Licensed under the Apache License, Version 2.0, with certain conditions.
# Refer to the "LICENSE" file in the root directory for more information.
#
set -euo pipefail
if [[ "$#" -lt 2 || "$1" != "--ort-path" ]]; then
echo "usage: $0 --ort-path <path_to_onnxruntime>" >&2
exit 1
fi
ORT_ROOT="$2"
shift 2
if [[ ! -d "$ORT_ROOT" || ! -d "$ORT_ROOT/lib" || ! -d "$ORT_ROOT/include" ]]; then
echo "invalid onnxruntime library path: $ORT_ROOT" >&2
exit 1
fi
arch=x64
build_dir=build-linux/$arch
rm -rf $build_dir
mkdir -p $build_dir
cd $build_dir
# Step 1: Build the demo
cmake ../../ -DORT_ROOT="$ORT_ROOT"
cmake --build . --config Release
# Step 2: Run the demo
ln -s ../../../src/onnx_model/
./ten_vad_demo ../../../examples/s0724-s0730.wav out.txt
cd ../../

View file

@ -1,87 +0,0 @@
//
// Copyright © 2025 Agora
// This file is part of TEN Framework, an open source project.
// Licensed under the Apache License, Version 2.0, with certain conditions.
// Refer to the "LICENSE" file in the root directory for more information.
//
#ifndef TEN_VAD_H
#define TEN_VAD_H
#if defined(__APPLE__) || defined(__ANDROID__) || defined(__linux__)
#define TENVAD_API __attribute__((visibility("default")))
#elif defined(_WIN32) || defined(__CYGWIN__)
#ifdef TENVAD_EXPORTS
#define TENVAD_API __declspec(dllexport)
#else
#define TENVAD_API __declspec(dllimport)
#endif
#else
#define TENVAD_API
#endif
#include <stddef.h> /* size_t */
#include <stdint.h> /* int16_t */
#ifdef __cplusplus
extern "C"
{
#endif
/**
* @typedef ten_vad_handle
* @brief Opaque handle for ten_vad instance.
*/
typedef void *ten_vad_handle_t;
/**
* @brief Create and initialize a ten_vad instance.
*
* @param[out] handle Pointer to receive the vad handle.
* @param[in] hop_size The number of samples between the start points of
* two consecutive analysis frames. (e.g., 256).
* @param[in] threshold VAD detection threshold ranging from [0.0, 1.0]
* This threshold is used to determine voice activity by comparing with the output probability.
* When probability >= threshold, voice is detected.
* @return 0 on success, or -1 error occurs.
*/
TENVAD_API int ten_vad_create(ten_vad_handle_t *handle, size_t hop_size,
float threshold);
/**
* @brief Process one audio frame for voice activity detection.
* Must call ten_vad_init() before calling this, and ten_vad_destroy() when done.
*
* @param[in] handle Valid VAD handle returned by ten_vad_create().
* @param[in] audio_data Pointer to an array of int16_t samples,
* buffer length must equal the hop size specified at ten_vad_create.
* @param[in] audio_data_length size of audio_data buffer, here should be equal to hop_size.
* @param[out] out_probability Pointer to a float (size 1) that receives the
* voice activity probability in the range [0.0, 1.0], where higher values indicate higher confidence in voice presence.
* @param[out] out_flag Pointer to an int (size 1) that receives the
* binary voice activity decision: 0: no voice, 1: voice detected.
* This flag is set to 1 when out_probability >= threshold, and 0 otherwise.
* @return 0 on success, or -1 error occurs.
*/
TENVAD_API int ten_vad_process(ten_vad_handle_t handle, const int16_t *audio_data, size_t audio_data_length,
float *out_probability, int *out_flag);
/**
* @brief Destroy a ten_vad instance and release its resources.
*
* @param[in,out] handle Pointer to the ten_vad handle; set to NULL on return.
* @return 0 on success, or -1 error occurs.
*/
TENVAD_API int ten_vad_destroy(ten_vad_handle_t *handle);
/**
* @brief Get the ten_vad library version string.
*
* @return The version string (e.g., "1.0.0").
*/
TENVAD_API const char *ten_vad_get_version(void);
#ifdef __cplusplus
}
#endif
#endif /* TEN_VAD_H */

View file

@ -1,139 +0,0 @@
#
# Copyright © 2025 Agora
# This file is part of TEN Framework, an open source project.
# Licensed under the Apache License, Version 2.0, with certain conditions.
# Refer to the "LICENSE" file in the root directory for more information.
#
from ctypes import c_int, c_int32, c_float, c_size_t, CDLL, c_void_p, POINTER
import numpy as np
import os
import platform
class TenVad:
def __init__(self, hop_size: int = 256, threshold: float = 0.5):
self.hop_size = hop_size
self.threshold = threshold
if platform.system() == "Linux" and platform.machine() == "x86_64":
git_path = os.path.join(
os.path.dirname(os.path.relpath(__file__)),
"../lib/Linux/x64/libten_vad.so"
)
if os.path.exists(git_path):
self.vad_library = CDLL(git_path)
else:
pip_path = os.path.join(
os.path.dirname(os.path.relpath(__file__)),
"./ten_vad_library/libten_vad.so"
)
self.vad_library = CDLL(pip_path)
elif platform.system() == "Darwin":
git_path = os.path.join(
os.path.dirname(os.path.relpath(__file__)),
"../lib/macOS/ten_vad.framework/Versions/A/ten_vad"
)
if os.path.exists(git_path):
self.vad_library = CDLL(git_path)
else:
pip_path = os.path.join(
os.path.dirname(os.path.relpath(__file__)),
"./ten_vad_library/libten_vad"
)
self.vad_library = CDLL(pip_path)
elif platform.system().upper() == 'WINDOWS':
if platform.machine().upper() in ['X64', 'X86_64', 'AMD64']:
git_path = os.path.join(
os.path.dirname(os.path.realpath(__file__)),
"../lib/Windows/x64/ten_vad.dll"
)
if os.path.exists(git_path):
self.vad_library = CDLL(git_path)
else:
pip_path = os.path.join(
os.path.dirname(os.path.realpath(__file__)),
"./ten_vad_library/ten_vad.dll"
)
self.vad_library = CDLL(pip_path)
else:
git_path = os.path.join(
os.path.dirname(os.path.realpath(__file__)),
"../lib/Windows/x86/ten_vad.dll"
)
if os.path.exists(git_path):
self.vad_library = CDLL(git_path)
else:
pip_path = os.path.join(
os.path.dirname(os.path.realpath(__file__)),
"./ten_vad_library/ten_vad.dll"
)
self.vad_library = CDLL(pip_path)
else:
raise NotImplementedError(f"Unsupported platform: {platform.system()} {platform.machine()}")
self.vad_handler = c_void_p(0)
self.out_probability = c_float()
self.out_flags = c_int32()
self.vad_library.ten_vad_create.argtypes = [
POINTER(c_void_p),
c_size_t,
c_float,
]
self.vad_library.ten_vad_create.restype = c_int
self.vad_library.ten_vad_destroy.argtypes = [POINTER(c_void_p)]
self.vad_library.ten_vad_destroy.restype = c_int
self.vad_library.ten_vad_process.argtypes = [
c_void_p,
c_void_p,
c_size_t,
POINTER(c_float),
POINTER(c_int32),
]
self.vad_library.ten_vad_process.restype = c_int
self.create_and_init_handler()
def create_and_init_handler(self):
assert (
self.vad_library.ten_vad_create(
POINTER(c_void_p)(self.vad_handler),
c_size_t(self.hop_size),
c_float(self.threshold),
)
== 0
), "[TEN VAD]: create handler failure!"
def __del__(self):
assert (
self.vad_library.ten_vad_destroy(
POINTER(c_void_p)(self.vad_handler)
)
== 0
), "[TEN VAD]: destroy handler failure!"
def get_input_data(self, audio_data: np.ndarray):
audio_data = np.squeeze(audio_data)
assert (
len(audio_data.shape) == 1
and audio_data.shape[0] == self.hop_size
), "[TEN VAD]: audio data shape should be [%d]" % (
self.hop_size
)
assert (
type(audio_data[0]) == np.int16
), "[TEN VAD]: audio data type error, must be int16"
data_pointer = audio_data.__array_interface__["data"][0]
return c_void_p(data_pointer)
def process(self, audio_data: np.ndarray):
input_pointer = self.get_input_data(audio_data)
self.vad_library.ten_vad_process(
self.vad_handler,
input_pointer,
c_size_t(self.hop_size),
POINTER(c_float)(self.out_probability),
POINTER(c_int32)(self.out_flags),
)
return self.out_probability.value, self.out_flags.value

View file

@ -1 +0,0 @@
numpy

View file

@ -1,46 +0,0 @@
#
# Copyright © 2025 Agora
# This file is part of TEN Framework, an open source project.
# Licensed under the Apache License, Version 2.0, with certain conditions.
# Refer to the "LICENSE" file in the root directory for more information.
#
from setuptools import setup
import os, shutil, platform
from setuptools.command.install import install
class custom_install_command(install):
def run(self):
install.run(self)
target_dir = os.path.join(self.install_lib, "ten_vad_library")
os.makedirs(target_dir, exist_ok=True)
if platform.system() == "Linux" and platform.machine() == "x86_64":
shutil.copy("lib/Linux/x64/libten_vad.so", target_dir)
print(f"Linux x64 library installed to: {target_dir}")
elif platform.system() == "Darwin":
shutil.copy("lib/macOS/ten_vad.framework/Versions/A/ten_vad",
os.path.join(target_dir, "libten_vad"))
print(f"macOS library installed to: {target_dir}")
elif platform.system().upper() == 'WINDOWS':
if platform.machine().upper() in ['X64', 'X86_64', 'AMD64']:
shutil.copy("lib/Windows/x64/ten_vad.dll",
os.path.join(target_dir, "ten_vad.dll"))
print(f"Windows x64 library installed to: {target_dir}")
else:
shutil.copy("lib/Windows/x86/ten_vad.dll",
os.path.join(target_dir, "ten_vad.dll"))
print(f"Windows x86 library installed to: {target_dir}")
else:
raise NotImplementedError(f"Unsupported platform: {platform.system()} {platform.machine()}")
root_dir = os.path.dirname(os.path.abspath(__file__))
shutil.copy(f"{root_dir}/include/ten_vad.py", f"{root_dir}/ten_vad.py")
setup(
name="ten_vad",
version="1.0",
py_modules=["ten_vad"],
cmdclass={
"install": custom_install_command,
},
)
os.remove(f"{root_dir}/ten_vad.py")

View file

@ -1,993 +0,0 @@
//
// Copyright © 2025 Agora
// This file is part of TEN Framework, an open source project.
// Licensed under the Apache License, Version 2.0, with certain conditions.
// Refer to the "LICENSE" file in the root directory for more information.
//
#include <string.h>
#include <stdlib.h>
#include <algorithm>
#include <math.h>
#include "aed.h"
#include "aed_st.h"
#include "coeff.h"
#include "pitch_est.h"
#include "stft.h"
#include <assert.h>
#define AUP_AED_ALIGN8(o) (((o) + 7) & (~7))
#define AUP_AED_MAX(x, y) (((x) > (y)) ? (x) : (y))
#define AUP_AED_MIN(x, y) (((x) > (y)) ? (y) : (x))
#define AUP_AED_EPS (1e-20f)
/// ///////////////////////////////////////////////////////////////////////
/// Internal Utils
/// ///////////////////////////////////////////////////////////////////////
AUP_MODULE_AIVAD::AUP_MODULE_AIVAD(char* onnx_path) {
ort_api = OrtGetApiBase()->GetApi(ORT_API_VERSION);
OrtStatus* status =
ort_api->CreateEnv(ORT_LOGGING_LEVEL_WARNING, "TEN-VAD", &ort_env);
if (status) {
printf("Failed to create env: %s\n", ort_api->GetErrorMessage(status));
ort_api->ReleaseStatus(status);
ort_api->ReleaseEnv(ort_env);
ort_env = NULL;
return;
}
OrtSessionOptions* session_options;
ort_api->CreateSessionOptions(&session_options);
ort_api->SetIntraOpNumThreads(session_options, 1);
status =
ort_api->CreateSession(ort_env, onnx_path, session_options, &ort_session);
ort_api->ReleaseSessionOptions(session_options);
if (status) {
printf("Failed to create ort_session: %s\n",
ort_api->GetErrorMessage(status));
ort_api->ReleaseStatus(status);
ort_api->ReleaseEnv(ort_env);
ort_env = NULL;
return;
}
ort_api->GetAllocatorWithDefaultOptions(&ort_allocator);
size_t num_inputs;
ort_api->SessionGetInputCount(ort_session, &num_inputs);
assert(num_inputs == AUP_AED_MODEL_IO_NUM);
for (size_t i = 0; i < num_inputs; i++) {
char* input_name;
ort_api->SessionGetInputName(ort_session, i, ort_allocator, &input_name);
strncpy(input_names_buf[i], input_name, sizeof(input_names_buf[i]));
input_names[i] = input_names_buf[i];
ort_api->AllocatorFree(ort_allocator, input_name);
}
size_t num_outputs;
ort_api->SessionGetOutputCount(ort_session, &num_outputs);
assert(num_outputs == AUP_AED_MODEL_IO_NUM);
for (size_t i = 0; i < num_outputs; i++) {
char* output_name;
ort_api->SessionGetOutputName(ort_session, i, ort_allocator, &output_name);
strncpy(output_names_buf[i], output_name, sizeof(output_names_buf[i]));
output_names[i] = output_names_buf[i];
ort_api->AllocatorFree(ort_allocator, output_name);
}
OrtMemoryInfo* memory_info;
status = ort_api->CreateCpuMemoryInfo(OrtDeviceAllocator, OrtMemTypeDefault,
&memory_info);
if (status != NULL) {
printf("Failed to create memory info: %s\n",
ort_api->GetErrorMessage(status));
ort_api->ReleaseStatus(status);
ort_api->ReleaseSession(ort_session);
ort_api->ReleaseEnv(ort_env);
ort_session = NULL;
ort_env = NULL;
return;
}
int64_t input_shapes0[] = {1, AUP_AED_CONTEXT_WINDOW_LEN, AUP_AED_FEA_LEN};
int64_t input_shapes1234[] = {1, AUP_AED_MODEL_HIDDEN_DIM};
for (int i = 0; i < num_inputs; i++) {
status = ort_api->CreateTensorWithDataAsOrtValue(
memory_info, i == 0 ? input_data_buf_0 : input_data_buf_1234[i - 1],
i == 0 ? sizeof(input_data_buf_0) : sizeof(input_data_buf_1234[i - 1]),
i == 0 ? input_shapes0 : input_shapes1234,
i == 0 ? sizeof(input_shapes0) / sizeof(input_shapes0[0])
: sizeof(input_shapes1234) / sizeof(input_shapes1234[0]),
ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT, &ort_input_tensors[i]);
if (status != NULL) {
printf("Failed to create input tensor %d: %s\n", i,
ort_api->GetErrorMessage(status));
ort_api->ReleaseStatus(status);
ort_api->ReleaseSession(ort_session);
ort_api->ReleaseEnv(ort_env);
ort_session = NULL;
ort_env = NULL;
return;
}
}
int64_t output_shapes0[] = {1, 1, 1};
int64_t output_shapes1234[] = {1, AUP_AED_MODEL_HIDDEN_DIM};
for (int i = 0; i < num_outputs; i++) {
status = ort_api->CreateTensorAsOrtValue(
ort_allocator, i == 0 ? output_shapes0 : output_shapes1234,
i == 0 ? sizeof(output_shapes0) / sizeof(output_shapes0[0])
: sizeof(output_shapes1234) / sizeof(output_shapes1234[0]),
ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT, &ort_output_tensors[i]);
if (status != NULL) {
printf("Failed to create output tensor %d: %s\n", i,
ort_api->GetErrorMessage(status));
ort_api->ReleaseStatus(status);
ort_api->ReleaseSession(ort_session);
ort_api->ReleaseEnv(ort_env);
ort_session = NULL;
ort_env = NULL;
return;
}
}
inited = 1;
}
AUP_MODULE_AIVAD::~AUP_MODULE_AIVAD() {
for (int i = 0; i < AUP_AED_MODEL_IO_NUM; i++) {
if (ort_output_tensors[i]) {
ort_api->ReleaseValue(ort_output_tensors[i]);
}
}
if (ort_session) {
ort_api->ReleaseSession(ort_session);
}
if (ort_env) {
ort_api->ReleaseEnv(ort_env);
}
}
int AUP_MODULE_AIVAD::Process(float* input, float* output) {
if (!inited) {
printf("not inited!\n");
return -1;
}
memcpy(input_data_buf_0, input, sizeof(input_data_buf_0));
if (clear_hidden) {
memset(input_data_buf_1234, 0, sizeof(input_data_buf_1234));
clear_hidden = 0;
}
OrtStatus* status = ort_api->Run(
ort_session, NULL, input_names, ort_input_tensors, AUP_AED_MODEL_IO_NUM,
output_names, AUP_AED_MODEL_IO_NUM, ort_output_tensors);
float* output_data;
ort_api->GetTensorMutableData(ort_output_tensors[0], (void**)&output_data);
*output = output_data[0];
for (int i = 1; i < AUP_AED_MODEL_IO_NUM; i++) {
ort_api->GetTensorMutableData(ort_output_tensors[i], (void**)&output_data);
memcpy(input_data_buf_1234[i - 1], output_data,
sizeof(input_data_buf_1234[i - 1]));
}
return 0;
}
int AUP_MODULE_AIVAD::Reset() {
if (!inited) {
return -1;
}
clear_hidden = 1;
return 0;
}
static int AUP_Aed_checkStatCfg(Aed_StaticCfg* pCfg) {
if (pCfg == NULL) {
return -1;
}
#if AUP_AED_FEA_LEN < AUP_AED_MEL_FILTER_BANK_NUM
return -1;
#endif
if (pCfg->hopSz < 32) {
return -1;
}
if (pCfg->frqInputAvailableFlag == 1) {
if (pCfg->fftSz < 128 || pCfg->fftSz < pCfg->hopSz) {
return -1;
}
if (pCfg->anaWindowSz > pCfg->fftSz || pCfg->anaWindowSz < pCfg->hopSz) {
return -1;
}
}
return 0;
}
static int AUP_Aed_publishStaticCfg(Aed_St* stHdl) {
const Aed_StaticCfg* pStatCfg;
if (stHdl == NULL) {
return -1;
}
pStatCfg = (const Aed_StaticCfg*)(&(stHdl->stCfg));
stHdl->extFftSz = 0;
stHdl->extNBins = 0;
stHdl->extWinSz = 0;
if (pStatCfg->frqInputAvailableFlag == 1) {
stHdl->extFftSz = pStatCfg->fftSz;
stHdl->extNBins = (stHdl->extFftSz >> 1) + 1;
stHdl->extWinSz = pStatCfg->anaWindowSz;
}
stHdl->extHopSz = pStatCfg->hopSz;
stHdl->intFftSz = AUP_AED_ASSUMED_FFTSZ;
stHdl->intHopSz = AUP_AED_ASSUMED_HOPSZ;
stHdl->intWinSz = AUP_AED_ASSUMED_WINDOWSZ;
stHdl->intNBins = (stHdl->intFftSz >> 1) + 1;
stHdl->intAnalyWindowPtr = AUP_AED_STFTWindow_Hann768;
if (pStatCfg->frqInputAvailableFlag == 0 ||
stHdl->extHopSz != stHdl->intHopSz) {
// external STFT analysis framework is not supported at all
stHdl->intAnalyFlag =
2; // internally redo analysis based on input time signal
} else if (stHdl->extFftSz == stHdl->intFftSz) {
// external STFT analysis framework completely match with internal
// requirement
stHdl->intAnalyFlag = 0; // directly use external spectrum
} else { // external spectrum need to be interpolated or extrapolated before
// AIVAD
stHdl->intAnalyFlag =
1; // use external spectrum with interpolation / exterpolation
}
stHdl->inputTimeFIFOLen = stHdl->extHopSz + stHdl->intHopSz;
// for aiaed release2.0.0, pre-emphasis for input time-signal is needed,
// therefore, we need redo analysis based on input time signal preprocessed by
// pre-emphasis.
stHdl->intAnalyFlag =
2; // internally redo analysis based on input time signal
stHdl->feaSz = (size_t)AUP_AED_FEA_LEN;
stHdl->melFbSz = (size_t)AUP_AED_MEL_FILTER_BANK_NUM;
stHdl->algDelay = (size_t)AUP_AED_LOOKAHEAD_NFRM;
stHdl->algCtxtSz = (size_t)AUP_AED_CONTEXT_WINDOW_LEN;
stHdl->frmRmsBufLen = AUP_AED_MAX(1, stHdl->algDelay);
return 0;
}
static int AUP_Aed_publishDynamCfg(Aed_St* stHdl) {
const Aed_DynamCfg* pDynmCfg;
PE_DynamCfg peDynmCfg;
if (stHdl == NULL) {
return -1;
}
pDynmCfg = (const Aed_DynamCfg*)(&(stHdl->dynamCfg));
stHdl->aivadResetFrmNum = pDynmCfg->resetFrameNum;
stHdl->voiceDecideThresh = pDynmCfg->extVoiceThr;
if (stHdl->pitchEstStPtr != NULL) {
peDynmCfg.voicedThr = pDynmCfg->pitchEstVoicedThr;
AUP_PE_setDynamCfg(stHdl->pitchEstStPtr, &peDynmCfg);
}
return 0;
}
static int AUP_Aed_resetVariables(Aed_St* stHdl) {
if (stHdl == NULL) {
return -1;
}
// first clear all the dynamic memory, all the dynamic variables which are
// not listed bellow are cleared to 0 by this step
memset(stHdl->dynamMemPtr, 0, stHdl->dynamMemSize);
float* melFbCoef = stHdl->melFilterBankCoef;
size_t* melBinBuff = stHdl->melFilterBinBuff;
size_t i, j;
size_t nBins = stHdl->intNBins;
size_t melFbSz = stHdl->melFbSz;
stHdl->aedProcFrmCnt = 0;
stHdl->inputTimeFIFOIdx = 0;
stHdl->aivadResetCnt = 0;
stHdl->timeSignalPre = 0.0f;
stHdl->aivadScore =
-1.0f; // as default value, labeling as aed is not working yet
stHdl->aivadScorePre = -1.0f;
stHdl->pitchFreq = 0.0f;
// generate mel filter-bank coefficients
float low_mel = 2595.0f * log10f(1.0f + 0.0f / 700.0f);
float high_mel = 2595.0f * log10f(1.0f + 8000.0f / 700.0f);
float mel_points = 0.0f;
float hz_points = 0.0f;
size_t idx = 0;
for (i = 0; i < melFbSz + 2; i++) {
mel_points = i * (high_mel - low_mel) / ((float)melFbSz + 1.0f) + low_mel;
hz_points = 700.0f * (powf(10.0f, mel_points / 2595.0f) - 1.0f);
melBinBuff[i] =
(size_t)((stHdl->intFftSz + 1.0f) * hz_points / (float)AUP_AED_FS);
if (i > 0 && melBinBuff[i] == melBinBuff[i - 1]) {
return -1;
}
}
for (j = 0; j < melFbSz; j++) {
for (i = melBinBuff[j]; i < melBinBuff[j + 1]; i++) {
idx = j * nBins + i;
melFbCoef[idx] = (float)(i - melBinBuff[j]) /
(float)(melBinBuff[j + 1] - melBinBuff[j]);
}
for (i = melBinBuff[j + 1]; i < melBinBuff[j + 2]; i++) {
idx = j * nBins + i;
melFbCoef[idx] = (float)(melBinBuff[j + 2] - i) /
(float)(melBinBuff[j + 2] - melBinBuff[j + 1]);
}
}
if (stHdl->pitchEstStPtr != NULL) {
if (AUP_PE_init(stHdl->pitchEstStPtr) < 0) {
return -1;
}
}
if (stHdl->aivadInf != NULL) {
stHdl->aivadInf->Reset();
}
if (stHdl->timeInAnalysis != NULL) {
if (AUP_Analyzer_init(stHdl->timeInAnalysis) < 0) {
return -1;
}
}
return 0;
}
static int AUP_Aed_addOneCnter(int cnter) {
cnter++;
if (cnter >= 1000000000) {
cnter = 0; // reset every half year
}
return (cnter);
}
static void AUP_Aed_binPowerConvert(const float* src, float* tgt, int srcNBins,
int tgtNBins) {
float rate;
int srcIdx, tgtIdx;
if (srcNBins == tgtNBins) {
memcpy(tgt, src, sizeof(float) * tgtNBins);
return;
}
memset(tgt, 0, sizeof(float) * tgtNBins);
rate = (float)(srcNBins - 1) / (float)(tgtNBins - 1);
for (tgtIdx = 0; tgtIdx < tgtNBins; tgtIdx++) {
srcIdx = (int)(tgtIdx * rate);
srcIdx = AUP_AED_MIN(srcNBins - 1, AUP_AED_MAX(srcIdx, 0));
tgt[tgtIdx] = src[srcIdx];
}
return;
}
static void AUP_Aed_CalcBinPow(int nBins, const float* cmplxSpctr,
float* binPow) {
int idx, realIdx, imagIdx;
// bin-0
binPow[0] = cmplxSpctr[0] * cmplxSpctr[0];
// bin-(NBins-1)
binPow[nBins - 1] = cmplxSpctr[1] * cmplxSpctr[1];
for (idx = 1; idx < (nBins - 1); idx++) {
realIdx = idx << 1;
imagIdx = realIdx + 1;
binPow[idx] = cmplxSpctr[realIdx] * cmplxSpctr[realIdx] +
cmplxSpctr[imagIdx] * cmplxSpctr[imagIdx];
}
return;
}
static int AUP_Aed_pitch_proc(void* pitchModule, const float* timeSignal,
size_t timeLen, const float* binPow, size_t nBins,
PE_OutputData* pOut) {
PE_InputData peInData;
peInData.timeSignal = timeSignal;
peInData.hopSz = (int)timeLen;
peInData.inBinPow = binPow;
peInData.nBins = (int)nBins;
pOut->pitchFreq = 0;
pOut->voiced = -1;
return AUP_PE_proc(pitchModule, &peInData, pOut);
}
static int AUP_Aed_aivad_proc(Aed_St* stHdl, const float* inBinPow,
float* aivadScore) {
if (stHdl == NULL || inBinPow == NULL || aivadScore == NULL) {
return -1;
}
size_t i, j;
size_t nBins = stHdl->intNBins;
size_t melFbSz = stHdl->melFbSz;
size_t srcOffset;
size_t srcLen;
float* aivadInputFeatStack = stHdl->aivadInputFeatStack;
float* melFbCoef = stHdl->melFilterBankCoef;
const float* aivadFeatMean = AUP_AED_FEATURE_MEANS;
const float* aivadFeatStd = AUP_AED_FEATURE_STDS;
float* curMelFbCoefPtr = NULL;
float* curInputFeatPtr = NULL;
float perBandValue = 0.0f;
float powerNormal = 32768.0f * 32768.0f;
// update aivad feature buff.
srcOffset = stHdl->feaSz;
srcLen = (stHdl->algCtxtSz - 1) * stHdl->feaSz;
memmove(aivadInputFeatStack, aivadInputFeatStack + srcOffset,
sizeof(float) * srcLen);
curInputFeatPtr = aivadInputFeatStack + srcLen;
// cal. mel-filter-bank feature
for (i = 0; i < melFbSz; i++) {
perBandValue = 0.0f;
curMelFbCoefPtr = melFbCoef + i * nBins;
for (j = 0; j < nBins; j++) {
perBandValue += (inBinPow[j] * curMelFbCoefPtr[j]);
}
perBandValue = perBandValue / powerNormal;
perBandValue = logf(perBandValue + AUP_AED_EPS);
curInputFeatPtr[i] =
(perBandValue - aivadFeatMean[i]) / (aivadFeatStd[i] + AUP_AED_EPS);
}
// extra feat.
for (i = melFbSz; i < stHdl->feaSz; i++) {
curInputFeatPtr[i] =
(stHdl->pitchFreq - aivadFeatMean[i]) / (aivadFeatStd[i] + AUP_AED_EPS);
}
// exe. aivad
// exe. aivad
float aivadOutput;
if (stHdl->aivadInf != NULL &&
stHdl->aivadInf->Process(stHdl->aivadInputFeatStack, &aivadOutput) != 0) {
return -1;
}
(*aivadScore) = aivadOutput;
stHdl->aivadResetCnt += 1;
if (stHdl->aivadResetCnt >= stHdl->aivadResetFrmNum) {
if (stHdl->aivadInf != NULL && stHdl->aivadInf->Reset() != 0) {
}
stHdl->aivadResetCnt = 0;
}
return 0;
}
static int AUP_Aed_dynamMemPrepare(Aed_St* stHdl, void* memPtrExt,
size_t memSize) {
if (stHdl == NULL) {
return -1;
}
size_t pitchInNBins = stHdl->intNBins;
size_t totalMemSize = 0;
size_t inputTimeFIFOMemSize = 0;
size_t inputEmphTimeFIFOMemSize = 0;
size_t aivadInputCmplxSptrmMemSize = 0;
size_t aivadInputBinPowMemSize = 0;
size_t frameRmsBuffMemSize = 0;
size_t aivadInputFeatStackMemSize = 0;
size_t aimdInputFeatStackMemSize = 0;
size_t melFilterBankCoefMemSize = 0;
size_t melFilterBinBuffMemSize = 0;
size_t inputFloatBuffMemSize = 0;
// size_t vadScoreOutputBuffDelaySample = 384; // buff. delay for output
char* memPtr = NULL;
// size_t nBinsBufferMemSize = AUP_AED_ALIGN8(sizeof(float) * nBins);
// size_t spctrmMemSize = AUP_AED_ALIGN8(sizeof(float) * (nBins - 1) * 2);
inputTimeFIFOMemSize =
AUP_AED_ALIGN8(sizeof(float) * stHdl->inputTimeFIFOLen);
totalMemSize += inputTimeFIFOMemSize;
inputEmphTimeFIFOMemSize =
AUP_AED_ALIGN8(sizeof(float) * stHdl->inputTimeFIFOLen);
totalMemSize += inputEmphTimeFIFOMemSize;
aivadInputCmplxSptrmMemSize = AUP_AED_ALIGN8(sizeof(float) * stHdl->intFftSz);
totalMemSize += aivadInputCmplxSptrmMemSize;
aivadInputBinPowMemSize = AUP_AED_ALIGN8(sizeof(float) * stHdl->intNBins);
totalMemSize += aivadInputBinPowMemSize;
aivadInputFeatStackMemSize =
AUP_AED_ALIGN8(sizeof(float) * stHdl->algCtxtSz * stHdl->feaSz);
totalMemSize += aivadInputFeatStackMemSize;
aimdInputFeatStackMemSize =
AUP_AED_ALIGN8(sizeof(float) * stHdl->algCtxtSz * stHdl->feaSz);
totalMemSize += aimdInputFeatStackMemSize;
melFilterBankCoefMemSize =
AUP_AED_ALIGN8(sizeof(float) * pitchInNBins * stHdl->feaSz);
totalMemSize += melFilterBankCoefMemSize;
melFilterBinBuffMemSize = AUP_AED_ALIGN8(sizeof(size_t) * (stHdl->feaSz + 2));
totalMemSize += melFilterBinBuffMemSize;
frameRmsBuffMemSize = AUP_AED_ALIGN8(stHdl->frmRmsBufLen * sizeof(float));
totalMemSize += frameRmsBuffMemSize;
inputFloatBuffMemSize = AUP_AED_ALIGN8(stHdl->extHopSz * sizeof(float));
totalMemSize += inputFloatBuffMemSize;
if (memPtrExt == NULL) {
return ((int)totalMemSize);
}
if (totalMemSize > memSize) {
return -1;
}
memPtr = (char*)memPtrExt;
stHdl->inputTimeFIFO = (float*)memPtr;
memPtr += inputTimeFIFOMemSize;
stHdl->inputEmphTimeFIFO = (float*)memPtr;
memPtr += inputEmphTimeFIFOMemSize;
stHdl->aivadInputCmplxSptrm = (float*)memPtr;
memPtr += aivadInputCmplxSptrmMemSize;
stHdl->aivadInputBinPow = (float*)memPtr;
memPtr += aivadInputBinPowMemSize;
stHdl->aivadInputFeatStack = (float*)memPtr;
memPtr += aivadInputFeatStackMemSize;
stHdl->melFilterBankCoef = (float*)memPtr;
memPtr += melFilterBankCoefMemSize;
stHdl->melFilterBinBuff = (size_t*)memPtr;
memPtr += melFilterBinBuffMemSize;
stHdl->frameRmsBuff = (float*)memPtr;
memPtr += frameRmsBuffMemSize;
stHdl->inputFloatBuff = (float*)memPtr;
memPtr += inputFloatBuffMemSize;
if (((size_t)(memPtr - (char*)memPtrExt)) > totalMemSize) {
return -1;
}
return ((int)totalMemSize);
}
static int AUP_Aed_runOneFrm(Aed_St* stHdl, const float* tSignal, int hopSz,
const float* binPowPtr, int nBins) {
PE_OutputData peOutData = {0, 0};
float aivadScore = -1.0f;
float mediaFilterout = 0;
int mediaIdx = (int)(AUP_AED_OUTPUT_SMOOTH_FILTER_LEN) / 2;
int i;
if (AUP_Aed_pitch_proc(stHdl->pitchEstStPtr, tSignal, hopSz, binPowPtr, nBins,
&peOutData) < 0) {
return -1;
}
stHdl->pitchFreq = peOutData.pitchFreq;
if (AUP_Aed_aivad_proc(stHdl, binPowPtr, &aivadScore) < 0) {
return -1;
}
stHdl->aivadScore = aivadScore;
return 0;
}
/// ///////////////////////////////////////////////////////////////////////
/// Public API
/// ///////////////////////////////////////////////////////////////////////
int AUP_Aed_create(void** stPtr) {
if (stPtr == NULL) {
return -1;
}
Aed_St* tmpPtr = (Aed_St*)malloc(sizeof(Aed_St));
if (tmpPtr == NULL) {
return -1;
}
memset(tmpPtr, 0, sizeof(Aed_St));
if (AUP_PE_create(&(tmpPtr->pitchEstStPtr)) < 0) {
return -1;
}
if (AUP_Analyzer_create(&(tmpPtr->timeInAnalysis)) < 0) {
return -1;
}
tmpPtr->stCfg.enableFlag = 1; // as default, module enabled
tmpPtr->stCfg.fftSz = 1024;
tmpPtr->stCfg.hopSz = 256;
tmpPtr->stCfg.anaWindowSz = 768;
tmpPtr->stCfg.frqInputAvailableFlag = 0;
tmpPtr->dynamCfg.extVoiceThr = 0.5f;
tmpPtr->dynamCfg.extMusicThr = 0.5f;
tmpPtr->dynamCfg.extEnergyThr = 10.0f;
tmpPtr->dynamCfg.resetFrameNum = 1875; // TODO
tmpPtr->dynamCfg.pitchEstVoicedThr = AUP_AED_PITCH_EST_DEFAULT_VOICEDTHR;
(*stPtr) = (void*)tmpPtr;
return 0;
}
int AUP_Aed_destroy(void** stPtr) {
if (stPtr == NULL || (*stPtr) == NULL) {
return -1;
}
Aed_St* stHdl = (Aed_St*)(*stPtr);
if (stHdl->aivadInf != NULL) {
delete stHdl->aivadInf;
}
stHdl->aivadInf = NULL;
if (AUP_PE_destroy(&(stHdl->pitchEstStPtr)) < 0) {
return -1;
}
if (AUP_Analyzer_destroy(&(stHdl->timeInAnalysis)) < 0) {
return -1;
}
if (stHdl->dynamMemPtr != NULL) {
free(stHdl->dynamMemPtr);
}
stHdl->dynamMemPtr = NULL;
if (stHdl != NULL) {
free(stHdl);
}
(*stPtr) = NULL;
return 0;
}
int AUP_Aed_memAllocate(void* stPtr, const Aed_StaticCfg* pCfg) {
Aed_St* stHdl = (Aed_St*)(stPtr);
Aed_StaticCfg aedStatCfg;
PE_StaticCfg pitchStatCfg;
Analyzer_StaticCfg analyzerStatCfg;
int totalMemSize = 0;
if (stPtr == NULL || pCfg == NULL) {
return -1;
}
// 1th: check static cfg.
memcpy(&aedStatCfg, pCfg, sizeof(Aed_StaticCfg));
if (AUP_Aed_checkStatCfg(&aedStatCfg) < 0) {
return -1;
}
memcpy(&(stHdl->stCfg), &aedStatCfg, sizeof(Aed_StaticCfg));
// 2th: publish static configuration to internal statical configuration
// registers
if (AUP_Aed_publishStaticCfg(stHdl) < 0) {
return -1;
}
// 3th: create aivad instance
if (stHdl->aivadInf == NULL) {
stHdl->aivadInf = new AUP_MODULE_AIVAD("onnx_model/ten-vad.onnx");
if (stHdl->aivadInf == NULL) {
return -1;
}
}
stHdl->aivadInf->Reset();
// 4th: memAllocate operation for Pitch-Estimator ............
if (AUP_PE_getStaticCfg(stHdl->pitchEstStPtr, &pitchStatCfg) < 0) {
return -1;
}
pitchStatCfg.fftSz = stHdl->intFftSz;
pitchStatCfg.anaWindowSz = stHdl->intWinSz;
pitchStatCfg.hopSz = stHdl->intHopSz;
pitchStatCfg.useLPCPreFiltering = AUP_AED_PITCH_EST_USE_LPC;
pitchStatCfg.procFs = AUP_AED_PITCH_EST_PROCFS;
if (AUP_PE_memAllocate(stHdl->pitchEstStPtr, &pitchStatCfg) < 0) {
return -1;
}
// creation and initialization with time-analysis module ......
AUP_Analyzer_getStaticCfg(stHdl->timeInAnalysis, &analyzerStatCfg);
analyzerStatCfg.win_len = (int)stHdl->intWinSz;
analyzerStatCfg.hop_size = (int)stHdl->intHopSz;
analyzerStatCfg.fft_size = (int)stHdl->intFftSz;
analyzerStatCfg.ana_win_coeff = stHdl->intAnalyWindowPtr;
if (AUP_Analyzer_memAllocate(stHdl->timeInAnalysis, &analyzerStatCfg) < 0) {
return -1;
}
// 5th: check memory requirement ..............................
totalMemSize = AUP_Aed_dynamMemPrepare(stHdl, NULL, 0);
if (totalMemSize < 0) {
return -1;
}
// 6th: allocate dynamic memory
if (totalMemSize > (int)stHdl->dynamMemSize) {
if (stHdl->dynamMemPtr != NULL) {
free(stHdl->dynamMemPtr);
stHdl->dynamMemPtr = NULL;
stHdl->dynamMemSize = 0;
}
stHdl->dynamMemPtr = malloc(totalMemSize);
if (stHdl->dynamMemPtr == NULL) {
return -1;
}
stHdl->dynamMemSize = totalMemSize;
}
memset(stHdl->dynamMemPtr, 0, stHdl->dynamMemSize);
// 7th: setup the pointers/variable
if (AUP_Aed_dynamMemPrepare(stHdl, stHdl->dynamMemPtr, stHdl->dynamMemSize) <
0) {
return -1;
}
// 8th: publish internal dynamic config registers
if (AUP_Aed_publishDynamCfg(stHdl) < 0) {
return -1;
}
return 0;
}
int AUP_Aed_init(void* stPtr) {
Aed_St* stHdl = (Aed_St*)(stPtr);
if (stPtr == NULL) {
return -1;
}
// publish internal dynamic config registers
if (AUP_Aed_publishDynamCfg(stHdl) < 0) {
return -1;
}
// clear/reset run-time variables
if (AUP_Aed_resetVariables(stHdl) < 0) {
return -1;
}
return 0;
}
int AUP_Aed_setDynamCfg(void* stPtr, const Aed_DynamCfg* pCfg) {
Aed_St* stHdl = (Aed_St*)(stPtr);
if (stPtr == NULL || pCfg == NULL) {
return -1;
}
memcpy(&(stHdl->dynamCfg), pCfg, sizeof(Aed_DynamCfg));
// publish internal dynamic configuration registers
if (AUP_Aed_publishDynamCfg(stHdl) < 0) {
return -1;
}
return 0;
}
int AUP_Aed_getStaticCfg(const void* stPtr, Aed_StaticCfg* pCfg) {
const Aed_St* stHdl = (const Aed_St*)(stPtr);
if (stPtr == NULL || pCfg == NULL) {
return -1;
}
memcpy(pCfg, &(stHdl->stCfg), sizeof(Aed_StaticCfg));
return 0;
}
int AUP_Aed_getDynamCfg(const void* stPtr, Aed_DynamCfg* pCfg) {
const Aed_St* stHdl = (const Aed_St*)(stPtr);
if (stPtr == NULL || pCfg == NULL) {
return -1;
}
memcpy(pCfg, &(stHdl->dynamCfg), sizeof(Aed_DynamCfg));
return 0;
}
int AUP_Aed_getAlgDelay(const void* stPtr, int* delayInFrms) {
const Aed_St* stHdl = (const Aed_St*)(stPtr);
if (stPtr == NULL || delayInFrms == NULL) {
return -1;
}
(*delayInFrms) = (int)stHdl->algDelay;
return 0;
}
int AUP_Aed_proc(void* stPtr, const Aed_InputData* pIn, Aed_OutputData* pOut) {
Analyzer_InputData analyzerInput;
Analyzer_OutputData analyzerOutput;
Aed_St* stHdl = (Aed_St*)(stPtr);
const float* binPowPtr = NULL;
float frameRms = 0.0f;
float frameEnergy = 0.0f;
float powerNormal = 32768.0f * 32768.0f;
int idx;
if (stPtr == NULL) {
return -1;
}
if (stHdl->stCfg.enableFlag == 0) { // this module is disabled
return 0;
}
if (pIn == NULL || pIn->timeSignal == NULL || pOut == NULL) {
return -1;
}
if (stHdl->intAnalyFlag != 2) { // the external spectra is going to be used
if (pIn->binPower == NULL) {
return -1;
}
if (pIn->nBins != (int)((stHdl->stCfg.fftSz >> 1) + 1) ||
pIn->hopSz != (int)(stHdl->stCfg.hopSz)) {
return -1;
}
}
// cal. input frame energy ....
for (idx = 0; idx < pIn->hopSz; idx++) {
frameRms += (pIn->timeSignal[idx] * pIn->timeSignal[idx]);
}
frameEnergy = frameRms;
frameRms = sqrtf(frameRms / (float)pIn->hopSz);
memmove(stHdl->frameRmsBuff, stHdl->frameRmsBuff + 1,
sizeof(float) * (stHdl->frmRmsBufLen - 1));
stHdl->frameRmsBuff[stHdl->frmRmsBufLen - 1] = frameRms;
// input signal conversion .........
if ((stHdl->inputTimeFIFOIdx + pIn->hopSz) > (int)stHdl->inputTimeFIFOLen) {
return -1;
}
// update pre-emphasis time signal FIFO
float* timeSigEphaPtr = stHdl->inputEmphTimeFIFO + stHdl->inputTimeFIFOIdx;
for (idx = 0; idx < pIn->hopSz; idx++) {
timeSigEphaPtr[idx] = pIn->timeSignal[idx] - 0.97f * stHdl->timeSignalPre;
stHdl->timeSignalPre = pIn->timeSignal[idx];
}
memcpy(stHdl->inputTimeFIFO + stHdl->inputTimeFIFOIdx, pIn->timeSignal,
sizeof(float) * (pIn->hopSz));
stHdl->inputTimeFIFOIdx += pIn->hopSz;
if (stHdl->intAnalyFlag == 0) { // directly use external spectra
if (stHdl->inputTimeFIFOIdx != (int)(stHdl->intHopSz) ||
(int)(stHdl->intNBins) != pIn->nBins) {
return -1;
}
// one-time processing ...
stHdl->aedProcFrmCnt = AUP_Aed_addOneCnter(stHdl->aedProcFrmCnt);
binPowPtr = pIn->binPower;
// update: stHdl->pitchFreq, stHdl->aivadScore
if (AUP_Aed_runOneFrm(stHdl, stHdl->inputTimeFIFO, (int)stHdl->intHopSz,
binPowPtr, (int)stHdl->intNBins) < 0) {
return -1;
}
// update the inputTimeFIFO
stHdl->inputTimeFIFOIdx = 0;
} else if (stHdl->intAnalyFlag ==
1) { // do interpolation or extrapolation with external spectra
if (stHdl->inputTimeFIFOIdx != (int)(stHdl->intHopSz) ||
(int)(stHdl->extNBins) != pIn->nBins) {
return -1;
}
// one-time processing ....
stHdl->aedProcFrmCnt = AUP_Aed_addOneCnter(stHdl->aedProcFrmCnt);
AUP_Aed_binPowerConvert(pIn->binPower, stHdl->aivadInputBinPow,
(int)stHdl->extNBins, (int)stHdl->intNBins);
binPowPtr = stHdl->aivadInputBinPow;
// update: stHdl->pitchFreq, stHdl->aivadScore
if (AUP_Aed_runOneFrm(stHdl, stHdl->inputTimeFIFO, (int)stHdl->intHopSz,
binPowPtr, (int)stHdl->intNBins) < 0) {
return -1;
}
// update the inputTimeFIFO
stHdl->inputTimeFIFOIdx = 0;
} else { // we need to do STFT on the input time-signal
if (stHdl->timeInAnalysis == NULL) {
return -1;
}
// loop processing .....
while (stHdl->inputTimeFIFOIdx >= (int)stHdl->intHopSz) {
stHdl->aedProcFrmCnt = AUP_Aed_addOneCnter(stHdl->aedProcFrmCnt);
analyzerInput.input = stHdl->inputEmphTimeFIFO;
analyzerInput.iLength = (int)stHdl->intHopSz;
analyzerOutput.output = stHdl->aivadInputCmplxSptrm;
analyzerOutput.oLength = (int)stHdl->intFftSz;
if (AUP_Analyzer_proc(stHdl->timeInAnalysis, &analyzerInput,
&analyzerOutput) < 0) {
return -1;
}
AUP_Aed_CalcBinPow((int)stHdl->intNBins, stHdl->aivadInputCmplxSptrm,
stHdl->aivadInputBinPow);
binPowPtr = stHdl->aivadInputBinPow;
// update: stHdl->pitchFreq, stHdl->aivadScore
if (AUP_Aed_runOneFrm(stHdl, stHdl->inputTimeFIFO, (int)stHdl->intHopSz,
binPowPtr, (int)stHdl->intNBins) < 0) {
return -1;
}
// update the inputTimeFIFO & inputEmphTimeFIFO.....
if (stHdl->inputTimeFIFOIdx > (int)stHdl->intHopSz) {
memcpy(stHdl->inputTimeFIFO, stHdl->inputTimeFIFO + stHdl->intHopSz,
sizeof(float) * (stHdl->inputTimeFIFOIdx - stHdl->intHopSz));
memcpy(stHdl->inputEmphTimeFIFO,
stHdl->inputEmphTimeFIFO + stHdl->intHopSz,
sizeof(float) * (stHdl->inputTimeFIFOIdx - stHdl->intHopSz));
}
stHdl->inputTimeFIFOIdx -= (int)stHdl->intHopSz;
}
}
// write to output res.
pOut->frameEnergy = frameEnergy / powerNormal;
pOut->frameRms = stHdl->frameRmsBuff[0];
pOut->pitchFreq = stHdl->pitchFreq;
pOut->voiceProb = stHdl->aivadScore;
if (pOut->voiceProb < 0.0f) {
pOut->vadRes = -1;
} else if (pOut->voiceProb <= stHdl->voiceDecideThresh) {
pOut->vadRes = 0;
} else {
pOut->vadRes = 1;
}
return 0;
}

View file

@ -1,226 +0,0 @@
//
// Copyright © 2025 Agora
// This file is part of TEN Framework, an open source project.
// Licensed under the Apache License, Version 2.0, with certain conditions.
// Refer to the "LICENSE" file in the root directory for more information.
//
#ifndef __AED_H__
#define __AED_H__
#include <stdint.h>
#include <stdlib.h>
#define AUP_AED_MAX_FFT_SZ (1024) // the max. fft-size supported by VAD module
#define AUP_AED_MAX_NBINS ((AUP_AED_MAX_FFT_SZ >> 1) + 1)
#define AUP_AED_FS (16000) // assumed input freq.
// Configuration Parameters, which impacts dynamic memory occupation, can only
// be set during allocation
typedef struct Aed_StaticCfg_ {
int enableFlag; // flag to enable or disable this module
// 0: disable, o.w.: enable
size_t fftSz; // fft-size, only support: 128, 256, 512, 1024
size_t hopSz; // fft-Hop Size, will be used to check
size_t anaWindowSz; // fft-window Size, will be used to calc rms
int frqInputAvailableFlag; // whether Aed_InputData will contain external
// freq. power-sepctra
} Aed_StaticCfg;
// Configuraiton parameters which can be modified/set every frames
typedef struct Aed_DynamCfg_ {
float extVoiceThr; // threshold for ai based voice decision [0,1]
float extMusicThr; // threshold for ai based music decision [0,1]
float extEnergyThr; // threshold for energy based vad decision [0, ---]
size_t resetFrameNum; // frame number for aivad reset [1875, 75000]
float pitchEstVoicedThr; // threshold for pitch-estimator to output estimated
// pitch
} Aed_DynamCfg;
// Spectrum are assumed to be generated with time-domain samples in [-32768,
// 32767] with or without pre-emphasis operation
typedef struct Aed_InputData_ {
const float* binPower; // [NBins], power spectrum of 16KHz samples
int nBins;
const float*
timeSignal; // [hopSz] // this frame's input signal, in [-32768, 32767]
int hopSz; // should be equal to StaticCfg->hopSz
} Aed_InputData;
// return data from statistical ns module
typedef struct Aed_OutputData_ {
float frameEnergy; // frame energy for input normalized data
float frameRms; // rms for input int16 data
int energyVadRes; // vad res 0/1 with extEnergyThreshold based on input frame
// energy
float voiceProb; // vad score [0,1]
int vadRes; // vad res 0/1 with extVoiceThr based on ai method, t + 16ms res
// correspond to the t input
float pitchFreq; // estimated pitch freq.
} Aed_OutputData;
#ifdef __cplusplus
extern "C" {
#endif
/****************************************************************************
* AUP_Aed_Create(...)
*
* This function creats a state handler from nothing, which is NOT ready for
* processing
*
* Input:
*
* Output:
* - stPtr : buffer to store the returned state handler
*
* Return value : 0 - Ok
* -1 - Error
*/
int AUP_Aed_create(void** stPtr);
/****************************************************************************
* AUP_Aed_Destroy(...)
*
* destroy VAD instance, and releasing all the dynamically allocated memory
* this interface will also release ainsFactory, which was
* created externally and passed to VAD module through memAllocate interface
*
* Input:
* - stPtr : buffer of State Handler, after this method, this
* handler won't be usable anymore
*
* Output:
*
* Return value : 0 - Ok
* -1 - Error
*/
int AUP_Aed_destroy(void** stPtr);
/****************************************************************************
* AUP_Aed_MemAllocate(...)
*
* This function sets Static Config params and does memory allocation
* operation, will lose the dynamCfg values
*
* Input:
* - stPtr : State Handler which was returned by _create
* - pCfg : static configuration parameters
*
* Output:
*
* Return value : 0 - Ok
* -1 - Error
*/
int AUP_Aed_memAllocate(void* stPtr, const Aed_StaticCfg* pCfg);
/****************************************************************************
* AUP_Aed_init(...)
*
* This function resets (initialize) the VAD module and gets it prepared for
* processing
*
* Input:
* - stPtr : State Handler which has gone through create and
* memAllocate
*
* Output:
*
* Return value : 0 - Ok
* -1 - Error
*/
int AUP_Aed_init(void* stPtr);
/****************************************************************************
* AUP_Aed_setDynamCfg(...)
*
* This function set dynamic (per-frame variable) configuration
*
* Input:
* - stPtr : State Handler which has gone through create and
* memAllocate
* - pCfg : configuration content
*
* Output:
*
* Return value : 0 - Ok
* -1 - Error
*/
int AUP_Aed_setDynamCfg(void* stPtr, const Aed_DynamCfg* pCfg);
/****************************************************************************
* AUP_Aed_getStaticCfg(...)
*
* This function get static configuration status from VAD module
*
* Input:
* - stPtr : State Handler which has gone through create and
* memAllocate
*
* Output:
* - pCfg : configuration content
*
* Return value : 0 - Ok
* -1 - Error
*/
int AUP_Aed_getStaticCfg(const void* stPtr, Aed_StaticCfg* pCfg);
/****************************************************************************
* AUP_Aed_getDynamCfg(...)
*
* This function get dynamic (per-frame variable) configuration status from
* VAD module
*
* Input:
* - stPtr : State Handler which has gone through create and
* memAllocate
*
* Output:
* - pCfg : configuration content
*
* Return value : 0 - Ok
* -1 - Error
*/
int AUP_Aed_getDynamCfg(const void* stPtr, Aed_DynamCfg* pCfg);
/****************************************************************************
* AUP_Aed_getAlgDelay(...)
*
* This function get algorithm delay from VAD module
*
* Input:
* - stPtr : State Handler which has gone through create and
* memAllocate
*
* Output:
* - delayInFrms : algorithm delay in terms of frames
*
* Return value : 0 - Ok
* -1 - Error
*/
int AUP_Aed_getAlgDelay(const void* stPtr, int* delayInFrms);
/****************************************************************************
* AUP_Aed_proc(...)
*
* process a single frame
*
* Input:
* - stPtr : State Handler which has gone through create and
* memAllocate and reset
* - pCtrl : per-frame variable control parameters
* - pIn : input data stream
*
* Output:
* - pOut : output data (mask, highband time-domain gain etc.)
*
* Return value : 0 - Ok
* -1 - Error
*/
int AUP_Aed_proc(void* stPtr, const Aed_InputData* pIn, Aed_OutputData* pOut);
#ifdef __cplusplus
}
#endif
#endif

View file

@ -1,132 +0,0 @@
//
// Copyright © 2025 Agora
// This file is part of TEN Framework, an open source project.
// Licensed under the Apache License, Version 2.0, with certain conditions.
// Refer to the "LICENSE" file in the root directory for more information.
//
#ifndef __AED_ST_H__
#define __AED_ST_H__
#include <stdio.h>
#include <onnxruntime_c_api.h>
#include "aed.h"
#define AUP_AED_FS (16000)
#define AUP_AED_MAX_IN_BUFF_SIZE (256)
#define AUP_AED_POWER_SPCTR_NORMALIZER (9.3132e-10f) // = 1/(32768^2)
#define AUP_AED_OUTPUT_SMOOTH_FILTER_LEN (10) // 160ms
#define AUP_AED_MEL_FILTER_BANK_NUM (40)
#define AUP_AED_LOOKAHEAD_NFRM (1)
#define AUP_AED_CONTEXT_WINDOW_LEN (3) // context window length of AIVAD
#define AUP_AED_FEA_LEN \
(AUP_AED_MEL_FILTER_BANK_NUM + 1) // feature length of AIVAD
#define AUP_AED_PITCH_EST_USE_LPC (1)
#define AUP_AED_PITCH_EST_PROCFS (4000)
#if AUP_AED_PITCH_EST_PROCFS == 2000
#define AUP_AED_PITCH_EST_DEFAULT_VOICEDTHR (0.45f)
#else
#define AUP_AED_PITCH_EST_DEFAULT_VOICEDTHR (0.4f)
#endif
#define AUP_AED_MODEL_IO_NUM (5)
#define AUP_AED_MODEL_NAME_LENGTH (32)
#define AUP_AED_MODEL_HIDDEN_DIM (64)
class AUP_MODULE_AIVAD {
public:
AUP_MODULE_AIVAD(char* onnx_path);
~AUP_MODULE_AIVAD();
int Process(float* input, float* output);
int Reset();
private:
const OrtApi* ort_api = NULL;
OrtAllocator* ort_allocator = NULL;
OrtEnv* ort_env = NULL;
OrtSession* ort_session = NULL;
int inited = 0;
int clear_hidden = 0;
char input_names_buf[AUP_AED_MODEL_IO_NUM][AUP_AED_MODEL_NAME_LENGTH] = {0};
const char* input_names[AUP_AED_MODEL_IO_NUM] = {NULL};
float input_data_buf_0[AUP_AED_CONTEXT_WINDOW_LEN * AUP_AED_FEA_LEN] = {0};
float input_data_buf_1234[AUP_AED_MODEL_IO_NUM - 1]
[AUP_AED_MODEL_HIDDEN_DIM] = {0};
OrtValue* ort_input_tensors[AUP_AED_MODEL_IO_NUM] = {NULL};
char output_names_buf[AUP_AED_MODEL_IO_NUM][AUP_AED_MODEL_NAME_LENGTH] = {0};
const char* output_names[AUP_AED_MODEL_IO_NUM] = {NULL};
OrtValue* ort_output_tensors[AUP_AED_MODEL_IO_NUM] = {NULL};
};
typedef struct Aed_St_ {
void* dynamMemPtr; // memory pointer holding the dynamic memory
size_t dynamMemSize; // size of the buffer *dynamMemPtr
Aed_StaticCfg stCfg;
Aed_DynamCfg dynamCfg;
// Internal Static Config Registers, which are generated from stCfg
size_t extFftSz; // externally decided FFT-Sz
size_t extHopSz; // externally decided FFT-Hop-Sz
size_t extNBins; // (FFTSz/2) + 1
size_t extWinSz; // externally decided FFT-Window-Sz
size_t intFftSz; // internal FFT Sz
size_t intHopSz; // internal Hop Sz
size_t intWinSz; // internal Window Sz
size_t intNBins; // internal NBins
const float* intAnalyWindowPtr; // internal analysis pointer
int intAnalyFlag; // whether to do internal analysis
// 0: directly use external spectrum
// 1: use external spectrum with interpolation / exterpolation
// 2: need to redo analysis based on input time-domain signal
size_t inputTimeFIFOLen; // length of input FIFO buffer
// if = 0: no need for input time-domain FIFO Queue
// Internal static config registers for pitch-est module
size_t feaSz;
size_t melFbSz;
size_t algDelay; // in terms of processing frames
size_t algCtxtSz;
size_t frmRmsBufLen; // frameRmsBuff: buffer-length of frameRmsBuff (FIFO)
// Internal dynamic Config Registers, which are generated from dynamCfg
size_t aivadResetFrmNum;
float voiceDecideThresh;
// SubModules
AUP_MODULE_AIVAD* aivadInf;
void* pitchEstStPtr; // pitch-estimation module handler
void* timeInAnalysis;
// state handler of STFT analysis module
// Variables
int aedProcFrmCnt; // counter of consecutive AI-VAD processed frames
int inputTimeFIFOIdx;
float* inputTimeFIFO; // [inputTimeFIFOLen]
// input fifo buffer of time-signal to adjust between extHopSz and intHopSz
float* inputEmphTimeFIFO; // [inputTimeFIFOLen]
float* aivadInputCmplxSptrm; // [intFftSz]
float* aivadInputBinPow; // [intNBins] // AIVAD input power spectrum
size_t aivadResetCnt;
float timeSignalPre;
float aivadScore;
float aivadScorePre;
float pitchFreq; // input audio pitch in Hz
float* frameRmsBuff; // [frmRmsBufLen], FIFO, to delay frmRms result so that
// it aligns with AIVAD result
float* aivadInputFeatStack; // [...] = [AUP_AED_CONTEXT_WINDOW_LEN *
// AUP_AED_FEA_LEN]
float* melFilterBankCoef; // [melFbSz][nBins]
size_t* melFilterBinBuff; // [melFbSz + 2]
float* inputFloatBuff; // [hopSz]
} Aed_St;
#endif

View file

@ -1,354 +0,0 @@
//
// Copyright © 2025 Agora
// This file is part of TEN Framework, an open source project.
// Licensed under the Apache License, Version 2.0, with certain conditions.
// Refer to the "LICENSE" file in the root directory for more information.
//
#include "biquad.h"
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "biquad_st.h"
#define AUP_BIQUAD_NUM_DUMP_FILES (20)
#define AUP_BIQUAD_DUMP_FILENAMES (200)
// ==========================================================================================
// internal tools
// ==========================================================================================
static int AUP_Biquad_checkStatCfg(const Biquad_StaticCfg* pCfg) {
int secIdx;
if (pCfg == NULL) {
return -1;
}
if (pCfg->maxNSample == 0 ||
pCfg->maxNSample > AGORA_UAP_BIQUAD_MAX_INPUT_LEN) {
return -1;
}
if (pCfg->nsect > AGORA_UAP_BIQUAD_MAX_SECTION) {
return -1;
}
// if external filter coefficients are required, we need to check the
// external filter coeff pointers' validness
if (pCfg->nsect > 0) {
for (secIdx = 0; secIdx < pCfg->nsect; secIdx++) {
if (pCfg->B[secIdx] == NULL || pCfg->A[secIdx] == NULL) {
return -1;
}
}
if (pCfg->G == NULL) {
return -1;
}
}
return 0;
}
static int AUP_Biquad_publishStaticCfg(Biquad_St* stHdl) {
const Biquad_StaticCfg* pStatCfg;
int idx;
if (stHdl == NULL) {
return -1;
}
pStatCfg = (const Biquad_StaticCfg*)(&(stHdl->stCfg));
stHdl->maxNSample = (int)pStatCfg->maxNSample;
// first, give default (all-pass-filter) values to filter coeffs
for (idx = 0; idx < AGORA_UAP_BIQUAD_MAX_SECTION; idx++) {
stHdl->BCoeff[idx][0] = 1.0f;
stHdl->BCoeff[idx][1] = 0;
stHdl->BCoeff[idx][2] = 0;
stHdl->ACoeff[idx][0] = 1.0f;
stHdl->ACoeff[idx][1] = 0;
stHdl->ACoeff[idx][2] = 0;
stHdl->GCoeff[idx] = 1.0f;
}
if (pStatCfg->nsect <= 0) {
stHdl->nsect = _BIQUAD_DC_REMOVAL_NSECT;
for (idx = 0; idx < stHdl->nsect; idx++) {
stHdl->BCoeff[idx][0] = _BIQUAD_DC_REMOVAL_B[idx][0];
stHdl->BCoeff[idx][1] = _BIQUAD_DC_REMOVAL_B[idx][1];
stHdl->BCoeff[idx][2] = _BIQUAD_DC_REMOVAL_B[idx][2];
stHdl->ACoeff[idx][0] = _BIQUAD_DC_REMOVAL_A[idx][0];
stHdl->ACoeff[idx][1] = _BIQUAD_DC_REMOVAL_A[idx][1];
stHdl->ACoeff[idx][2] = _BIQUAD_DC_REMOVAL_A[idx][2];
stHdl->GCoeff[idx] = _BIQUAD_DC_REMOVAL_G[idx];
}
} else {
stHdl->nsect = pStatCfg->nsect;
for (idx = 0; idx < stHdl->nsect; idx++) {
stHdl->BCoeff[idx][0] = pStatCfg->B[idx][0];
stHdl->BCoeff[idx][1] = pStatCfg->B[idx][1];
stHdl->BCoeff[idx][2] = pStatCfg->B[idx][2];
stHdl->ACoeff[idx][0] = pStatCfg->A[idx][0];
stHdl->ACoeff[idx][1] = pStatCfg->A[idx][1];
stHdl->ACoeff[idx][2] = pStatCfg->A[idx][2];
stHdl->GCoeff[idx] = pStatCfg->G[idx];
}
}
return 0;
}
static int AUP_Biquad_resetVariables(Biquad_St* stHdl) {
memset(stHdl->dynamMemPtr, 0, stHdl->dynamMemSize);
memset(stHdl->sectW, 0, sizeof(stHdl->sectW));
return 0;
}
// ==========================================================================================
// public APIS
// ==========================================================================================
int AUP_Biquad_create(void** stPtr) {
Biquad_St* tmpPtr;
if (stPtr == NULL) {
return -1;
}
*stPtr = (void*)malloc(sizeof(Biquad_St));
if (*stPtr == NULL) {
return -1;
}
memset(*stPtr, 0, sizeof(Biquad_St));
tmpPtr = (Biquad_St*)(*stPtr);
tmpPtr->dynamMemPtr = NULL;
tmpPtr->dynamMemSize = 0;
tmpPtr->stCfg.maxNSample = 768;
tmpPtr->stCfg.nsect = 0;
for (int idx = 0; idx < AGORA_UAP_BIQUAD_MAX_SECTION; idx++) {
tmpPtr->stCfg.A[idx] = NULL;
tmpPtr->stCfg.B[idx] = NULL;
}
tmpPtr->stCfg.G = NULL;
return 0;
}
int AUP_Biquad_destroy(void** stPtr) {
Biquad_St* stHdl;
if (stPtr == NULL) {
return 0;
}
stHdl = (Biquad_St*)(*stPtr);
if (stHdl == NULL) {
return 0;
}
if (stHdl->dynamMemPtr != NULL) {
free(stHdl->dynamMemPtr);
}
stHdl->dynamMemPtr = NULL;
free(stHdl);
(*stPtr) = NULL;
return 0;
}
int AUP_Biquad_memAllocate(void* stPtr, const Biquad_StaticCfg* pCfg) {
Biquad_St* stHdl = NULL;
char* memPtr = NULL;
int maxNSample, nsect, idx;
int inputTempBufMemSize = 0;
int sectOutputBufMemSize_EACH = 0;
int totalMemSize = 0;
if (stPtr == NULL || pCfg == NULL) {
return -1;
}
stHdl = (Biquad_St*)(stPtr);
if (AUP_Biquad_checkStatCfg(pCfg) < 0) {
return -1;
}
memcpy(&(stHdl->stCfg), pCfg, sizeof(Biquad_StaticCfg));
if (AUP_Biquad_publishStaticCfg(stHdl) < 0) {
return -1;
}
maxNSample = stHdl->maxNSample;
nsect = stHdl->nsect;
// check memory requirement
inputTempBufMemSize = AGORA_UAP_BIQUAD_ALIGN8(sizeof(float) * maxNSample);
totalMemSize += inputTempBufMemSize;
sectOutputBufMemSize_EACH =
AGORA_UAP_BIQUAD_ALIGN8(sizeof(float) * maxNSample);
totalMemSize += sectOutputBufMemSize_EACH * nsect;
// allocate dynamic memory
if ((size_t)totalMemSize > stHdl->dynamMemSize) {
if (stHdl->dynamMemPtr != NULL) {
free(stHdl->dynamMemPtr);
stHdl->dynamMemSize = 0;
}
stHdl->dynamMemPtr = malloc(totalMemSize);
if (stHdl->dynamMemPtr == NULL) {
return -1;
}
stHdl->dynamMemSize = totalMemSize;
}
memset(stHdl->dynamMemPtr, 0, stHdl->dynamMemSize);
// setup the pointers/variable
memPtr = (char*)(stHdl->dynamMemPtr);
stHdl->inputTempBuf = (float*)memPtr;
memPtr += inputTempBufMemSize;
for (idx = 0; idx < nsect; idx++) {
stHdl->sectOutputBuf[idx] = (float*)memPtr;
memPtr += sectOutputBufMemSize_EACH;
}
for (; idx < AGORA_UAP_BIQUAD_MAX_SECTION; idx++) {
stHdl->sectOutputBuf[idx] = NULL;
}
if (((int)(memPtr - (char*)(stHdl->dynamMemPtr))) > totalMemSize) {
return -1;
}
return 0;
}
int AUP_Biquad_init(void* stPtr) {
Biquad_St* stHdl;
if (stPtr == NULL) {
return -1;
}
stHdl = (Biquad_St*)(stPtr);
if (AUP_Biquad_resetVariables(stHdl) < 0) {
return -1;
}
return 0;
}
int AUP_Biquad_getStaticCfg(const void* stPtr, Biquad_StaticCfg* pCfg) {
const Biquad_St* stHdl;
if (stPtr == NULL || pCfg == NULL) {
return -1;
}
stHdl = (const Biquad_St*)(stPtr);
memcpy(pCfg, &(stHdl->stCfg), sizeof(Biquad_StaticCfg));
return 0;
}
int AUP_Biquad_getAlgDelay(const void* stPtr, int* delayInSamples) {
const Biquad_St* stHdl;
if (stPtr == NULL || delayInSamples == NULL) {
return -1;
}
stHdl = (const Biquad_St*)(stPtr);
*delayInSamples = stHdl->nsect;
return 0;
}
int AUP_Biquad_proc(void* stPtr, const Biquad_InputData* pIn,
Biquad_OutputData* pOut) {
Biquad_St* stHdl = NULL;
int isFloatIO = 0;
int inputNSamples, nSect;
int sectIdx, smplIdx;
float tmp1;
const short* pShortTemp;
float* src;
float* tgt;
if (stPtr == NULL || pIn == NULL || pOut == NULL) { // pCtrl == NULL
return -1;
}
if (pIn->samplesPtr == NULL || pOut->outputBuff == NULL) {
return -1;
}
stHdl = (Biquad_St*)(stPtr);
if (((int)pIn->nsamples) > stHdl->maxNSample) {
return -1;
}
isFloatIO = 0;
if (pIn->sampleType != 0) {
isFloatIO = 1;
}
inputNSamples = (int)pIn->nsamples;
nSect = stHdl->nsect;
// special handle for input
if (isFloatIO == 0) {
pShortTemp = (const short*)pIn->samplesPtr;
for (smplIdx = 0; smplIdx < inputNSamples; smplIdx++) {
stHdl->inputTempBuf[smplIdx] = (float)pShortTemp[smplIdx];
}
} else {
memcpy(stHdl->inputTempBuf, (const float*)pIn->samplesPtr,
sizeof(float) * inputNSamples);
}
for (sectIdx = 0; sectIdx < nSect; sectIdx++) {
if (sectIdx == 0) {
src = stHdl->inputTempBuf;
} else {
src = stHdl->sectOutputBuf[sectIdx - 1];
}
tgt = stHdl->sectOutputBuf[sectIdx];
for (smplIdx = 0; smplIdx < inputNSamples; smplIdx++) {
tmp1 = src[smplIdx] -
stHdl->ACoeff[sectIdx][1] * stHdl->sectW[sectIdx][0] -
stHdl->ACoeff[sectIdx][2] * stHdl->sectW[sectIdx][1];
tgt[smplIdx] = stHdl->GCoeff[sectIdx] *
(stHdl->BCoeff[sectIdx][0] * tmp1 +
stHdl->BCoeff[sectIdx][1] * stHdl->sectW[sectIdx][0] +
stHdl->BCoeff[sectIdx][2] * stHdl->sectW[sectIdx][1]);
stHdl->sectW[sectIdx][1] = stHdl->sectW[sectIdx][0];
stHdl->sectW[sectIdx][0] = tmp1;
}
}
// prepare output buffer
if (isFloatIO == 0) {
for (smplIdx = 0; smplIdx < inputNSamples; smplIdx++) {
((short*)pOut->outputBuff)[smplIdx] =
(short)_BIQUAD_FLOAT2SHORT(stHdl->sectOutputBuf[nSect - 1][smplIdx]);
}
} else {
memcpy(pOut->outputBuff, stHdl->sectOutputBuf[nSect - 1],
sizeof(float) * inputNSamples);
}
return 0;
}

View file

@ -1,190 +0,0 @@
//
// Copyright © 2025 Agora
// This file is part of TEN Framework, an open source project.
// Licensed under the Apache License, Version 2.0, with certain conditions.
// Refer to the "LICENSE" file in the root directory for more information.
//
#ifndef __BIQUAD_H__
#define __BIQUAD_H__
#include <stdio.h>
#define AGORA_UAP_BIQUAD_MAX_SECTION (20)
// the max. number of sections supported by this Biquad module
#define AGORA_UAP_BIQUAD_MAX_INPUT_LEN (3840)
// max. number of samples each time can be fed in
#define AGORA_UAP_BIQUAD_ALIGN8(o) (((o) + 7) & (~7))
#define _BIQUAD_FLOAT2SHORT(x) \
((x) < -32767.5f ? -32768 : ((x) > 32766.5f ? 32767 : (short)floor(.5 + (x))))
#define _BIQUAD_DC_REMOVAL_NSECT (2)
const float _BIQUAD_DC_REMOVAL_B[_BIQUAD_DC_REMOVAL_NSECT][3] = {
{1.0f, -2.0f, 1.0f}, {1.0f, -1.0f, 0.0f}};
const float _BIQUAD_DC_REMOVAL_A[_BIQUAD_DC_REMOVAL_NSECT][3] = {
{1.0f, -1.93944294f, 0.94281253f}, {1.0f, -0.94276431f, 0.0f}};
// const float _BIQUAD_DC_REMOVAL_G[_BIQUAD_DC_REMOVAL_NSECT] = {0.97056387f,
// 0.97138215f};
const float _BIQUAD_DC_REMOVAL_G[_BIQUAD_DC_REMOVAL_NSECT] = {0.97056387f,
0.8655014957f};
// Configuration Parameters, which impacts dynamic memory occupation, can only
// be set during allocation
typedef struct Biquad_StaticCfg_ {
size_t maxNSample; // max. number of samples each time can be fed in
// (0, AGORA_UAP_BIQUAD_MAX_INPUT_LEN]
int nsect; // the number of sections to be processed by this Biquad module
// (-inf, AGORA_UAP_BIQUAD_MAX_SECTION]
// if <= 0, use internal default filter coefficients
const float* B[AGORA_UAP_BIQUAD_MAX_SECTION];
const float* A[AGORA_UAP_BIQUAD_MAX_SECTION];
// always assume A[...][0] = 1.0f
const float* G;
} Biquad_StaticCfg;
typedef struct Biquad_InputData_ {
const void*
samplesPtr; // externally provided buffer containing input time samples
// either in short or float type
short sampleType; // = 0: samplesPtr = short*; o.w. samplesPtr = float*
size_t nsamples; // number of samples fed in this time
} Biquad_InputData;
typedef struct Biquad_OutputData_ {
void* outputBuff; // externally provided output buffer,
// assumed to be of enough size nsamples *
// sizeof(short)/sizeof(short) output data type is the same
// as input
} Biquad_OutputData;
#ifdef __cplusplus
extern "C" {
#endif
/****************************************************************************
* AUP_Biquad_create(...)
*
* This function creats a state handler from nothing, which is NOT ready for
* processing
*
* Input:
*
* Output:
* - stPtr : buffer to store the returned state handler
*
* Return value : 0 - Ok
* -1 - Error
*/
int AUP_Biquad_create(void** stPtr);
/****************************************************************************
* AUP_Biquad_destroy(...)
*
* destroy biquad instance, and releasing all the dynamically allocated memory
*
* Input:
* - stPtr : buffer of State Handler, after this method, this
* handler won't be usable anymore
*
* Output:
*
* Return value : 0 - Ok
* -1 - Error
*/
int AUP_Biquad_destroy(void** stPtr);
/****************************************************************************
* AUP_Biquad_memAllocate(...)
*
* This function sets Static Config params and does memory allocation
* operation
*
* Input:
* - stPtr : State Handler which was returned by _create
* - pCfg : static configuration parameters
*
* Output:
*
* Return value : 0 - Ok
* -1 - Error
*/
int AUP_Biquad_memAllocate(void* stPtr, const Biquad_StaticCfg* pCfg);
/****************************************************************************
* AUP_Biquad_init(...)
*
* This function resets (initialize) the biquad module and gets it prepared for
* processing
*
* Input:
* - stPtr : State Handler which has gone through create and
* memAllocate
*
* Output:
*
* Return value : 0 - Ok
* -1 - Error
*/
int AUP_Biquad_init(void* stPtr);
/****************************************************************************
* AUP_Biquad_getStaticCfg(...)
*
* This function get static configuration status from Biquad module
*
* Input:
* - stPtr : State Handler which has gone through create and
* memAllocate
*
* Output:
* - pCfg : configuration content
*
* Return value : 0 - Ok
* -1 - Error
*/
int AUP_Biquad_getStaticCfg(const void* stPtr, Biquad_StaticCfg* pCfg);
/****************************************************************************
* AUP_Biquad_getAlgDelay(...)
*
* This function get algorithm delay from biquad module
*
* Input:
* - stPtr : State Handler which has gone through create and
* memAllocate
*
* Output:
* - delayInSamples : algorithm delay in terms of samples
*
* Return value : 0 - Ok
* -1 - Error
*/
int AUP_Biquad_getAlgDelay(const void* stPtr, int* delayInSamples);
/****************************************************************************
* AUP_Biquad_proc(...)
*
* process a single frame
*
* Input:
* - stPtr : State Handler which has gone through create and
* memAllocate
* - pCtrl : per-frame variable control parameters
* - pIn : input data stream
*
* Output:
* - pOut : output data (mask, highband time-domain gain etc.)
*
* Return value : 0 - Ok
* -1 - Error
*/
int AUP_Biquad_proc(void* stPtr, const Biquad_InputData* pIn,
Biquad_OutputData* pOut);
#ifdef __cplusplus
}
#endif
#endif // __BIQUAD_H__

View file

@ -1,37 +0,0 @@
//
// Copyright © 2025 Agora
// This file is part of TEN Framework, an open source project.
// Licensed under the Apache License, Version 2.0, with certain conditions.
// Refer to the "LICENSE" file in the root directory for more information.
//
#ifndef __BIQUAD_ST_H__
#define __BIQUAD_ST_H__
#include <stdio.h>
#include "biquad.h"
typedef struct Biquad_St_ {
void* dynamMemPtr; // memory pointer holding the dynamic memory
size_t dynamMemSize; // size of the buffer *dynamMemPtr
// Static Configuration
Biquad_StaticCfg stCfg;
// ---------------------------------------------------------------
// Internal Static Config Registers, which are generated from stCfg
int maxNSample;
int nsect;
float BCoeff[AGORA_UAP_BIQUAD_MAX_SECTION][3];
float ACoeff[AGORA_UAP_BIQUAD_MAX_SECTION][3];
float GCoeff[AGORA_UAP_BIQUAD_MAX_SECTION]; // gain for each section
// Variables
float* inputTempBuf; // [maxNSample]
float sectW[AGORA_UAP_BIQUAD_MAX_SECTION][2];
// each section's register
float* sectOutputBuf
[AGORA_UAP_BIQUAD_MAX_SECTION]; //[AGORA_UAP_BIQUAD_MAX_SECTION][maxNSample]
// each section's output buffer
} Biquad_St;
#endif // __BIQUAD_ST_H__

View file

@ -1,246 +0,0 @@
//
// Copyright © 2025 Agora
// This file is part of TEN Framework, an open source project.
// Licensed under the Apache License, Version 2.0, with certain conditions.
// Refer to the "LICENSE" file in the root directory for more information.
//
#ifndef __COEFF_H__
#define __COEFF_H__
#include "aed_st.h"
#define AUP_AED_MEAN_STD_NBINS AUP_AED_FEA_LEN
#define AUP_AED_ASSUMED_HOPSZ (256)
#define AUP_AED_ASSUMED_WINDOWSZ (768)
#define AUP_AED_ASSUMED_FFTSZ (1024)
// means of inpu-mel-filterbank
const float AUP_AED_FEATURE_MEANS[AUP_AED_MEAN_STD_NBINS] = {
-8.198236465454e+00f, -6.265716552734e+00f, -5.483818531036e+00f,
-4.758691310883e+00f, -4.417088985443e+00f, -4.142892837524e+00f,
-3.912850379944e+00f, -3.845927953720e+00f, -3.657090425491e+00f,
-3.723418712616e+00f, -3.876134157181e+00f, -3.843890905380e+00f,
-3.690405130386e+00f, -3.756065845490e+00f, -3.698696136475e+00f,
-3.650463104248e+00f, -3.700468778610e+00f, -3.567321300507e+00f,
-3.498900175095e+00f, -3.477807044983e+00f, -3.458816051483e+00f,
-3.444923877716e+00f, -3.401328563690e+00f, -3.306261301041e+00f,
-3.278556823730e+00f, -3.233250856400e+00f, -3.198616027832e+00f,
-3.204526424408e+00f, -3.208798646927e+00f, -3.257838010788e+00f,
-3.381376743317e+00f, -3.534021377563e+00f, -3.640867948532e+00f,
-3.726858854294e+00f, -3.773730993271e+00f, -3.804667234421e+00f,
-3.832901000977e+00f, -3.871120452881e+00f, -3.990592956543e+00f,
-4.480289459229e+00f, 9.235690307617e+01f};
// stds of input-mel-filterbank
const float AUP_AED_FEATURE_STDS[AUP_AED_MEAN_STD_NBINS] = {
5.166063785553e+00f, 4.977209568024e+00f, 4.698895931244e+00f,
4.630621433258e+00f, 4.634347915649e+00f, 4.641156196594e+00f,
4.640676498413e+00f, 4.666367053986e+00f, 4.650534629822e+00f,
4.640020847321e+00f, 4.637400150299e+00f, 4.620099067688e+00f,
4.596316337585e+00f, 4.562654972076e+00f, 4.554360389709e+00f,
4.566910743713e+00f, 4.562489986420e+00f, 4.562412738800e+00f,
4.585299491882e+00f, 4.600179672241e+00f, 4.592845916748e+00f,
4.585922718048e+00f, 4.583496570587e+00f, 4.626092910767e+00f,
4.626957893372e+00f, 4.626289367676e+00f, 4.637005805969e+00f,
4.683015823364e+00f, 4.726813793182e+00f, 4.734289646149e+00f,
4.753227233887e+00f, 4.849722862244e+00f, 4.869434833527e+00f,
4.884482860565e+00f, 4.921327114105e+00f, 4.959212303162e+00f,
4.996619224548e+00f, 5.044823646545e+00f, 5.072216987610e+00f,
5.096439361572e+00f, 1.152136917114e+02f};
const float AUP_AED_STFTWindow_Hann768[768] = {
0.0000000e+00f, 1.6733041e-05f, 6.6931045e-05f, 1.5059065e-04f,
2.6770626e-04f, 4.1827004e-04f, 6.0227190e-04f, 8.1969953e-04f,
1.0705384e-03f, 1.3547717e-03f, 1.6723803e-03f, 2.0233432e-03f,
2.4076367e-03f, 2.8252351e-03f, 3.2761105e-03f, 3.7602327e-03f,
4.2775693e-03f, 4.8280857e-03f, 5.4117450e-03f, 6.0285082e-03f,
6.6783340e-03f, 7.3611788e-03f, 8.0769970e-03f, 8.8257407e-03f,
9.6073598e-03f, 1.0421802e-02f, 1.1269013e-02f, 1.2148935e-02f,
1.3061510e-02f, 1.4006678e-02f, 1.4984373e-02f, 1.5994532e-02f,
1.7037087e-02f, 1.8111967e-02f, 1.9219101e-02f, 2.0358415e-02f,
2.1529832e-02f, 2.2733274e-02f, 2.3968661e-02f, 2.5235910e-02f,
2.6534935e-02f, 2.7865651e-02f, 2.9227967e-02f, 3.0621794e-02f,
3.2047037e-02f, 3.3503601e-02f, 3.4991388e-02f, 3.6510300e-02f,
3.8060234e-02f, 3.9641086e-02f, 4.1252752e-02f, 4.2895122e-02f,
4.4568088e-02f, 4.6271536e-02f, 4.8005353e-02f, 4.9769424e-02f,
5.1563629e-02f, 5.3387849e-02f, 5.5241962e-02f, 5.7125844e-02f,
5.9039368e-02f, 6.0982406e-02f, 6.2954829e-02f, 6.4956504e-02f,
6.6987298e-02f, 6.9047074e-02f, 7.1135695e-02f, 7.3253021e-02f,
7.5398909e-02f, 7.7573217e-02f, 7.9775799e-02f, 8.2006508e-02f,
8.4265194e-02f, 8.6551706e-02f, 8.8865891e-02f, 9.1207593e-02f,
9.3576658e-02f, 9.5972925e-02f, 9.8396234e-02f, 1.0084642e-01f,
1.0332333e-01f, 1.0582679e-01f, 1.0835663e-01f, 1.1091268e-01f,
1.1349477e-01f, 1.1610274e-01f, 1.1873640e-01f, 1.2139558e-01f,
1.2408010e-01f, 1.2678978e-01f, 1.2952444e-01f, 1.3228389e-01f,
1.3506796e-01f, 1.3787646e-01f, 1.4070919e-01f, 1.4356597e-01f,
1.4644661e-01f, 1.4935091e-01f, 1.5227868e-01f, 1.5522973e-01f,
1.5820385e-01f, 1.6120085e-01f, 1.6422052e-01f, 1.6726267e-01f,
1.7032709e-01f, 1.7341358e-01f, 1.7652192e-01f, 1.7965192e-01f,
1.8280336e-01f, 1.8597603e-01f, 1.8916971e-01f, 1.9238420e-01f,
1.9561929e-01f, 1.9887474e-01f, 2.0215035e-01f, 2.0544589e-01f,
2.0876115e-01f, 2.1209590e-01f, 2.1544993e-01f, 2.1882300e-01f,
2.2221488e-01f, 2.2562536e-01f, 2.2905421e-01f, 2.3250119e-01f,
2.3596607e-01f, 2.3944863e-01f, 2.4294863e-01f, 2.4646583e-01f,
2.5000000e-01f, 2.5355090e-01f, 2.5711830e-01f, 2.6070196e-01f,
2.6430163e-01f, 2.6791708e-01f, 2.7154806e-01f, 2.7519434e-01f,
2.7885565e-01f, 2.8253178e-01f, 2.8622245e-01f, 2.8992744e-01f,
2.9364649e-01f, 2.9737934e-01f, 3.0112576e-01f, 3.0488549e-01f,
3.0865828e-01f, 3.1244388e-01f, 3.1624203e-01f, 3.2005248e-01f,
3.2387498e-01f, 3.2770926e-01f, 3.3155507e-01f, 3.3541216e-01f,
3.3928027e-01f, 3.4315913e-01f, 3.4704849e-01f, 3.5094809e-01f,
3.5485766e-01f, 3.5877695e-01f, 3.6270569e-01f, 3.6664362e-01f,
3.7059048e-01f, 3.7454600e-01f, 3.7850991e-01f, 3.8248196e-01f,
3.8646187e-01f, 3.9044938e-01f, 3.9444422e-01f, 3.9844613e-01f,
4.0245484e-01f, 4.0647007e-01f, 4.1049157e-01f, 4.1451906e-01f,
4.1855226e-01f, 4.2259092e-01f, 4.2663476e-01f, 4.3068351e-01f,
4.3473690e-01f, 4.3879466e-01f, 4.4285652e-01f, 4.4692220e-01f,
4.5099143e-01f, 4.5506394e-01f, 4.5913946e-01f, 4.6321772e-01f,
4.6729844e-01f, 4.7138134e-01f, 4.7546616e-01f, 4.7955263e-01f,
4.8364046e-01f, 4.8772939e-01f, 4.9181913e-01f, 4.9590943e-01f,
5.0000000e-01f, 5.0409057e-01f, 5.0818087e-01f, 5.1227061e-01f,
5.1635954e-01f, 5.2044737e-01f, 5.2453384e-01f, 5.2861866e-01f,
5.3270156e-01f, 5.3678228e-01f, 5.4086054e-01f, 5.4493606e-01f,
5.4900857e-01f, 5.5307780e-01f, 5.5714348e-01f, 5.6120534e-01f,
5.6526310e-01f, 5.6931649e-01f, 5.7336524e-01f, 5.7740908e-01f,
5.8144774e-01f, 5.8548094e-01f, 5.8950843e-01f, 5.9352993e-01f,
5.9754516e-01f, 6.0155387e-01f, 6.0555578e-01f, 6.0955062e-01f,
6.1353813e-01f, 6.1751804e-01f, 6.2149009e-01f, 6.2545400e-01f,
6.2940952e-01f, 6.3335638e-01f, 6.3729431e-01f, 6.4122305e-01f,
6.4514234e-01f, 6.4905191e-01f, 6.5295151e-01f, 6.5684087e-01f,
6.6071973e-01f, 6.6458784e-01f, 6.6844493e-01f, 6.7229074e-01f,
6.7612502e-01f, 6.7994752e-01f, 6.8375797e-01f, 6.8755612e-01f,
6.9134172e-01f, 6.9511451e-01f, 6.9887424e-01f, 7.0262066e-01f,
7.0635351e-01f, 7.1007256e-01f, 7.1377755e-01f, 7.1746822e-01f,
7.2114435e-01f, 7.2480566e-01f, 7.2845194e-01f, 7.3208292e-01f,
7.3569837e-01f, 7.3929804e-01f, 7.4288170e-01f, 7.4644910e-01f,
7.5000000e-01f, 7.5353417e-01f, 7.5705137e-01f, 7.6055137e-01f,
7.6403393e-01f, 7.6749881e-01f, 7.7094579e-01f, 7.7437464e-01f,
7.7778512e-01f, 7.8117700e-01f, 7.8455007e-01f, 7.8790410e-01f,
7.9123885e-01f, 7.9455411e-01f, 7.9784965e-01f, 8.0112526e-01f,
8.0438071e-01f, 8.0761580e-01f, 8.1083029e-01f, 8.1402397e-01f,
8.1719664e-01f, 8.2034808e-01f, 8.2347808e-01f, 8.2658642e-01f,
8.2967291e-01f, 8.3273733e-01f, 8.3577948e-01f, 8.3879915e-01f,
8.4179615e-01f, 8.4477027e-01f, 8.4772132e-01f, 8.5064909e-01f,
8.5355339e-01f, 8.5643403e-01f, 8.5929081e-01f, 8.6212354e-01f,
8.6493204e-01f, 8.6771611e-01f, 8.7047556e-01f, 8.7321022e-01f,
8.7591990e-01f, 8.7860442e-01f, 8.8126360e-01f, 8.8389726e-01f,
8.8650523e-01f, 8.8908732e-01f, 8.9164337e-01f, 8.9417321e-01f,
8.9667667e-01f, 8.9915358e-01f, 9.0160377e-01f, 9.0402708e-01f,
9.0642334e-01f, 9.0879241e-01f, 9.1113411e-01f, 9.1344829e-01f,
9.1573481e-01f, 9.1799349e-01f, 9.2022420e-01f, 9.2242678e-01f,
9.2460109e-01f, 9.2674698e-01f, 9.2886431e-01f, 9.3095293e-01f,
9.3301270e-01f, 9.3504350e-01f, 9.3704517e-01f, 9.3901759e-01f,
9.4096063e-01f, 9.4287416e-01f, 9.4475804e-01f, 9.4661215e-01f,
9.4843637e-01f, 9.5023058e-01f, 9.5199465e-01f, 9.5372846e-01f,
9.5543191e-01f, 9.5710488e-01f, 9.5874725e-01f, 9.6035891e-01f,
9.6193977e-01f, 9.6348970e-01f, 9.6500861e-01f, 9.6649640e-01f,
9.6795296e-01f, 9.6937821e-01f, 9.7077203e-01f, 9.7213435e-01f,
9.7346506e-01f, 9.7476409e-01f, 9.7603134e-01f, 9.7726673e-01f,
9.7847017e-01f, 9.7964159e-01f, 9.8078090e-01f, 9.8188803e-01f,
9.8296291e-01f, 9.8400547e-01f, 9.8501563e-01f, 9.8599332e-01f,
9.8693849e-01f, 9.8785107e-01f, 9.8873099e-01f, 9.8957820e-01f,
9.9039264e-01f, 9.9117426e-01f, 9.9192300e-01f, 9.9263882e-01f,
9.9332167e-01f, 9.9397149e-01f, 9.9458825e-01f, 9.9517191e-01f,
9.9572243e-01f, 9.9623977e-01f, 9.9672389e-01f, 9.9717476e-01f,
9.9759236e-01f, 9.9797666e-01f, 9.9832762e-01f, 9.9864523e-01f,
9.9892946e-01f, 9.9918030e-01f, 9.9939773e-01f, 9.9958173e-01f,
9.9973229e-01f, 9.9984941e-01f, 9.9993307e-01f, 9.9998327e-01f,
1.0000000e+00f, 9.9998327e-01f, 9.9993307e-01f, 9.9984941e-01f,
9.9973229e-01f, 9.9958173e-01f, 9.9939773e-01f, 9.9918030e-01f,
9.9892946e-01f, 9.9864523e-01f, 9.9832762e-01f, 9.9797666e-01f,
9.9759236e-01f, 9.9717476e-01f, 9.9672389e-01f, 9.9623977e-01f,
9.9572243e-01f, 9.9517191e-01f, 9.9458825e-01f, 9.9397149e-01f,
9.9332167e-01f, 9.9263882e-01f, 9.9192300e-01f, 9.9117426e-01f,
9.9039264e-01f, 9.8957820e-01f, 9.8873099e-01f, 9.8785107e-01f,
9.8693849e-01f, 9.8599332e-01f, 9.8501563e-01f, 9.8400547e-01f,
9.8296291e-01f, 9.8188803e-01f, 9.8078090e-01f, 9.7964159e-01f,
9.7847017e-01f, 9.7726673e-01f, 9.7603134e-01f, 9.7476409e-01f,
9.7346506e-01f, 9.7213435e-01f, 9.7077203e-01f, 9.6937821e-01f,
9.6795296e-01f, 9.6649640e-01f, 9.6500861e-01f, 9.6348970e-01f,
9.6193977e-01f, 9.6035891e-01f, 9.5874725e-01f, 9.5710488e-01f,
9.5543191e-01f, 9.5372846e-01f, 9.5199465e-01f, 9.5023058e-01f,
9.4843637e-01f, 9.4661215e-01f, 9.4475804e-01f, 9.4287416e-01f,
9.4096063e-01f, 9.3901759e-01f, 9.3704517e-01f, 9.3504350e-01f,
9.3301270e-01f, 9.3095293e-01f, 9.2886431e-01f, 9.2674698e-01f,
9.2460109e-01f, 9.2242678e-01f, 9.2022420e-01f, 9.1799349e-01f,
9.1573481e-01f, 9.1344829e-01f, 9.1113411e-01f, 9.0879241e-01f,
9.0642334e-01f, 9.0402708e-01f, 9.0160377e-01f, 8.9915358e-01f,
8.9667667e-01f, 8.9417321e-01f, 8.9164337e-01f, 8.8908732e-01f,
8.8650523e-01f, 8.8389726e-01f, 8.8126360e-01f, 8.7860442e-01f,
8.7591990e-01f, 8.7321022e-01f, 8.7047556e-01f, 8.6771611e-01f,
8.6493204e-01f, 8.6212354e-01f, 8.5929081e-01f, 8.5643403e-01f,
8.5355339e-01f, 8.5064909e-01f, 8.4772132e-01f, 8.4477027e-01f,
8.4179615e-01f, 8.3879915e-01f, 8.3577948e-01f, 8.3273733e-01f,
8.2967291e-01f, 8.2658642e-01f, 8.2347808e-01f, 8.2034808e-01f,
8.1719664e-01f, 8.1402397e-01f, 8.1083029e-01f, 8.0761580e-01f,
8.0438071e-01f, 8.0112526e-01f, 7.9784965e-01f, 7.9455411e-01f,
7.9123885e-01f, 7.8790410e-01f, 7.8455007e-01f, 7.8117700e-01f,
7.7778512e-01f, 7.7437464e-01f, 7.7094579e-01f, 7.6749881e-01f,
7.6403393e-01f, 7.6055137e-01f, 7.5705137e-01f, 7.5353417e-01f,
7.5000000e-01f, 7.4644910e-01f, 7.4288170e-01f, 7.3929804e-01f,
7.3569837e-01f, 7.3208292e-01f, 7.2845194e-01f, 7.2480566e-01f,
7.2114435e-01f, 7.1746822e-01f, 7.1377755e-01f, 7.1007256e-01f,
7.0635351e-01f, 7.0262066e-01f, 6.9887424e-01f, 6.9511451e-01f,
6.9134172e-01f, 6.8755612e-01f, 6.8375797e-01f, 6.7994752e-01f,
6.7612502e-01f, 6.7229074e-01f, 6.6844493e-01f, 6.6458784e-01f,
6.6071973e-01f, 6.5684087e-01f, 6.5295151e-01f, 6.4905191e-01f,
6.4514234e-01f, 6.4122305e-01f, 6.3729431e-01f, 6.3335638e-01f,
6.2940952e-01f, 6.2545400e-01f, 6.2149009e-01f, 6.1751804e-01f,
6.1353813e-01f, 6.0955062e-01f, 6.0555578e-01f, 6.0155387e-01f,
5.9754516e-01f, 5.9352993e-01f, 5.8950843e-01f, 5.8548094e-01f,
5.8144774e-01f, 5.7740908e-01f, 5.7336524e-01f, 5.6931649e-01f,
5.6526310e-01f, 5.6120534e-01f, 5.5714348e-01f, 5.5307780e-01f,
5.4900857e-01f, 5.4493606e-01f, 5.4086054e-01f, 5.3678228e-01f,
5.3270156e-01f, 5.2861866e-01f, 5.2453384e-01f, 5.2044737e-01f,
5.1635954e-01f, 5.1227061e-01f, 5.0818087e-01f, 5.0409057e-01f,
5.0000000e-01f, 4.9590943e-01f, 4.9181913e-01f, 4.8772939e-01f,
4.8364046e-01f, 4.7955263e-01f, 4.7546616e-01f, 4.7138134e-01f,
4.6729844e-01f, 4.6321772e-01f, 4.5913946e-01f, 4.5506394e-01f,
4.5099143e-01f, 4.4692220e-01f, 4.4285652e-01f, 4.3879466e-01f,
4.3473690e-01f, 4.3068351e-01f, 4.2663476e-01f, 4.2259092e-01f,
4.1855226e-01f, 4.1451906e-01f, 4.1049157e-01f, 4.0647007e-01f,
4.0245484e-01f, 3.9844613e-01f, 3.9444422e-01f, 3.9044938e-01f,
3.8646187e-01f, 3.8248196e-01f, 3.7850991e-01f, 3.7454600e-01f,
3.7059048e-01f, 3.6664362e-01f, 3.6270569e-01f, 3.5877695e-01f,
3.5485766e-01f, 3.5094809e-01f, 3.4704849e-01f, 3.4315913e-01f,
3.3928027e-01f, 3.3541216e-01f, 3.3155507e-01f, 3.2770926e-01f,
3.2387498e-01f, 3.2005248e-01f, 3.1624203e-01f, 3.1244388e-01f,
3.0865828e-01f, 3.0488549e-01f, 3.0112576e-01f, 2.9737934e-01f,
2.9364649e-01f, 2.8992744e-01f, 2.8622245e-01f, 2.8253178e-01f,
2.7885565e-01f, 2.7519434e-01f, 2.7154806e-01f, 2.6791708e-01f,
2.6430163e-01f, 2.6070196e-01f, 2.5711830e-01f, 2.5355090e-01f,
2.5000000e-01f, 2.4646583e-01f, 2.4294863e-01f, 2.3944863e-01f,
2.3596607e-01f, 2.3250119e-01f, 2.2905421e-01f, 2.2562536e-01f,
2.2221488e-01f, 2.1882300e-01f, 2.1544993e-01f, 2.1209590e-01f,
2.0876115e-01f, 2.0544589e-01f, 2.0215035e-01f, 1.9887474e-01f,
1.9561929e-01f, 1.9238420e-01f, 1.8916971e-01f, 1.8597603e-01f,
1.8280336e-01f, 1.7965192e-01f, 1.7652192e-01f, 1.7341358e-01f,
1.7032709e-01f, 1.6726267e-01f, 1.6422052e-01f, 1.6120085e-01f,
1.5820385e-01f, 1.5522973e-01f, 1.5227868e-01f, 1.4935091e-01f,
1.4644661e-01f, 1.4356597e-01f, 1.4070919e-01f, 1.3787646e-01f,
1.3506796e-01f, 1.3228389e-01f, 1.2952444e-01f, 1.2678978e-01f,
1.2408010e-01f, 1.2139558e-01f, 1.1873640e-01f, 1.1610274e-01f,
1.1349477e-01f, 1.1091268e-01f, 1.0835663e-01f, 1.0582679e-01f,
1.0332333e-01f, 1.0084642e-01f, 9.8396234e-02f, 9.5972925e-02f,
9.3576658e-02f, 9.1207593e-02f, 8.8865891e-02f, 8.6551706e-02f,
8.4265194e-02f, 8.2006508e-02f, 7.9775799e-02f, 7.7573217e-02f,
7.5398909e-02f, 7.3253021e-02f, 7.1135695e-02f, 6.9047074e-02f,
6.6987298e-02f, 6.4956504e-02f, 6.2954829e-02f, 6.0982406e-02f,
5.9039368e-02f, 5.7125844e-02f, 5.5241962e-02f, 5.3387849e-02f,
5.1563629e-02f, 4.9769424e-02f, 4.8005353e-02f, 4.6271536e-02f,
4.4568088e-02f, 4.2895122e-02f, 4.1252752e-02f, 3.9641086e-02f,
3.8060234e-02f, 3.6510300e-02f, 3.4991388e-02f, 3.3503601e-02f,
3.2047037e-02f, 3.0621794e-02f, 2.9227967e-02f, 2.7865651e-02f,
2.6534935e-02f, 2.5235910e-02f, 2.3968661e-02f, 2.2733274e-02f,
2.1529832e-02f, 2.0358415e-02f, 1.9219101e-02f, 1.8111967e-02f,
1.7037087e-02f, 1.5994532e-02f, 1.4984373e-02f, 1.4006678e-02f,
1.3061510e-02f, 1.2148935e-02f, 1.1269013e-02f, 1.0421802e-02f,
9.6073598e-03f, 8.8257407e-03f, 8.0769970e-03f, 7.3611788e-03f,
6.6783340e-03f, 6.0285082e-03f, 5.4117450e-03f, 4.8280857e-03f,
4.2775693e-03f, 3.7602327e-03f, 3.2761105e-03f, 2.8252351e-03f,
2.4076367e-03f, 2.0233432e-03f, 1.6723803e-03f, 1.3547717e-03f,
1.0705384e-03f, 8.1969953e-04f, 6.0227190e-04f, 4.1827004e-04f,
2.6770626e-04f, 1.5059065e-04f, 6.6931045e-05f, 1.6733041e-05f};
#endif

File diff suppressed because it is too large Load diff

View file

@ -1,47 +0,0 @@
//
// Copyright © 2025 Agora
// This file is part of TEN Framework, an open source project.
// Licensed under the Apache License, Version 2.0, with certain conditions.
// Refer to the "LICENSE" file in the root directory for more information.
//
#ifndef __FFTW_H__
#define __FFTW_H__
#include <stdio.h>
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
// Spectrum Storage Format definition:
// format1: [Real-0, Real-Nyq, Real-1, Imag-1, Real-2, Imag-2, ...]
// format2: [Real-0, Real-1, (-1)*Imag-1, Real-2, (-1)*Imag-2, ..., Real-Nyq]
// the following functions assume input and output spectrum to be stored in
// format2
void AUP_FFTW_r2c_256(float* in, float* out);
void AUP_FFTW_c2r_256(float* in, float* out);
void AUP_FFTW_c2r_512(float* in, float* out);
void AUP_FFTW_r2c_512(float* in, float* out);
void AUP_FFTW_r2c_1024(float* in, float* out);
void AUP_FFTW_c2r_1024(float* in, float* out);
void AUP_FFTW_r2c_2048(float* in, float* out);
void AUP_FFTW_c2r_2048(float* in, float* out);
void AUP_FFTW_r2c_4096(float* in, float* out);
void AUP_FFTW_c2r_4096(float* in, float* out);
// if direction == 0: format1->format2
// if direction == 1: format2->format1
void AUP_FFTW_InplaceTransf(int direction, int fftSz, float* inplaceTranfBuf);
void AUP_FFTW_RescaleFFTOut(int fftSz, float* inplaceBuf);
void AUP_FFTW_RescaleIFFTOut(int fftSz, float* inplaceBuf);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif // __FFTW_H__

View file

@ -1,541 +0,0 @@
//
// Copyright © 2025 Agora
// This file is part of TEN Framework, an open source project.
// Licensed under the Apache License, Version 2.0, with certain conditions.
// Refer to the "LICENSE" file in the root directory for more information.
//
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "fscvrt.h"
#include "fscvrt_st.h"
#include "biquad.h"
// ==========================================================================================
// internal tools
// ==========================================================================================
static int AUP_Fscvrt_FilterSet(int resampleRate, int* nsect,
const float* B[_FSCVRT_MAXNSEC],
const float* A[_FSCVRT_MAXNSEC],
const float** G) {
int idx;
if (resampleRate == 2) {
*nsect = _FSCVRT_1over2_LOWPASS_NSEC;
for (idx = 0; idx < (*nsect); idx++) {
B[idx] = &(_FSCVRT_1over2_LOWPASS_B[idx][0]);
A[idx] = &(_FSCVRT_1over2_LOWPASS_A[idx][0]);
}
*G = _FSCVRT_1over2_LOWPASS_G;
} else if (resampleRate == 3) {
*nsect = _FSCVRT_1over3_LOWPASS_NSEC;
for (idx = 0; idx < (*nsect); idx++) {
B[idx] = &(_FSCVRT_1over3_LOWPASS_B[idx][0]);
A[idx] = &(_FSCVRT_1over3_LOWPASS_A[idx][0]);
}
*G = _FSCVRT_1over3_LOWPASS_G;
} else if (resampleRate == 4) {
*nsect = _FSCVRT_1over4_LOWPASS_NSEC;
for (idx = 0; idx < (*nsect); idx++) {
B[idx] = &(_FSCVRT_1over4_LOWPASS_B[idx][0]);
A[idx] = &(_FSCVRT_1over4_LOWPASS_A[idx][0]);
}
*G = _FSCVRT_1over4_LOWPASS_G;
} else if (resampleRate == 6) {
*nsect = _FSCVRT_1over6_LOWPASS_NSEC;
for (idx = 0; idx < (*nsect); idx++) {
B[idx] = &(_FSCVRT_1over6_LOWPASS_B[idx][0]);
A[idx] = &(_FSCVRT_1over6_LOWPASS_A[idx][0]);
}
*G = _FSCVRT_1over6_LOWPASS_G;
} else { // unknown resample rate
return -1;
}
return 0;
}
static int AUP_Fscvrt_dynamMemPrepare(FscvrtSt* stHdl, void* memPtrExt,
size_t memSize) {
char* memPtr = NULL;
int biquadInBufMemSize = 0;
int biquadOutBufMemSize = 0;
int totalMemSize = 0;
if (stHdl == NULL) {
return -1;
}
biquadInBufMemSize = _FSCVRT_ALIGN8(sizeof(float) * stHdl->biquadInBufLen);
totalMemSize += biquadInBufMemSize;
biquadOutBufMemSize = _FSCVRT_ALIGN8(sizeof(float) * stHdl->biquadOutBufLen);
totalMemSize += biquadOutBufMemSize;
totalMemSize = _FSCVRT_MAX(totalMemSize, 80);
// if no external memory provided, we are only profiling the memory
// requirement
if (memPtrExt == NULL) {
return (totalMemSize);
}
// if required memory is more than provided, error
if ((size_t)totalMemSize > memSize) {
return -1;
}
memPtr = (char*)memPtrExt;
stHdl->biquadInBuf = NULL;
if (biquadInBufMemSize != 0) {
stHdl->biquadInBuf = (float*)memPtr;
memPtr += biquadInBufMemSize;
}
stHdl->biquadOutBuf = NULL;
if (biquadOutBufMemSize != 0) {
stHdl->biquadOutBuf = (float*)memPtr;
memPtr += biquadOutBufMemSize;
}
if (((int)(memPtr - (char*)memPtrExt)) > totalMemSize) {
return -1;
}
return (totalMemSize);
}
static int AUP_Fscvrt_checkStatCfg(FscvrtStaticCfg* pCfg) {
if (pCfg == NULL) {
return -1;
}
if (pCfg->inputFs != 16000 && pCfg->inputFs != 24000 &&
pCfg->inputFs != 32000 && pCfg->inputFs != 48000) {
return -1;
}
if (pCfg->outputFs != 16000 && pCfg->outputFs != 24000 &&
pCfg->outputFs != 32000 && pCfg->outputFs != 48000) {
return -1;
}
if (pCfg->stepSz > AUP_FSCVRT_MAX_INPUT_LEN || pCfg->stepSz < 1) {
return -1;
}
if (pCfg->inputType != 0) {
pCfg->inputType = 1;
}
if (pCfg->outputType != 0) {
pCfg->outputType = 1;
}
return 0;
}
static int AUP_Fscvrt_publishStaticCfg(FscvrtSt* stHdl) {
int tmpRatio;
int ret;
int maxResmplRate = 0;
stHdl->mode = 0;
stHdl->upSmplRate = 1;
stHdl->downSmplRate = 1;
if (stHdl->stCfg.inputFs != stHdl->stCfg.outputFs) {
if (stHdl->stCfg.outputFs > stHdl->stCfg.inputFs) {
tmpRatio = (stHdl->stCfg.outputFs / stHdl->stCfg.inputFs);
if (stHdl->stCfg.outputFs == tmpRatio * stHdl->stCfg.inputFs) {
stHdl->mode = 1;
stHdl->upSmplRate = tmpRatio;
stHdl->downSmplRate = 1;
} else {
stHdl->mode = 3;
stHdl->upSmplRate = _FSCVRT_COMMON_FS / stHdl->stCfg.inputFs;
stHdl->downSmplRate = _FSCVRT_COMMON_FS / stHdl->stCfg.outputFs;
}
} else { // stHdl->stCfg.outputFs < stHdl->stCfg.inputFs
tmpRatio = (stHdl->stCfg.inputFs / stHdl->stCfg.outputFs);
if (stHdl->stCfg.inputFs == tmpRatio * stHdl->stCfg.outputFs) {
stHdl->mode = 2;
stHdl->upSmplRate = 1;
stHdl->downSmplRate = tmpRatio;
} else {
stHdl->mode = 3;
stHdl->upSmplRate = _FSCVRT_COMMON_FS / stHdl->stCfg.inputFs;
stHdl->downSmplRate = _FSCVRT_COMMON_FS / stHdl->stCfg.outputFs;
}
}
}
if (stHdl->mode == 0) {
stHdl->biquadInBufLen = 0;
stHdl->biquadOutBufLen = 0;
} else {
stHdl->biquadInBufLen = stHdl->stCfg.stepSz * stHdl->upSmplRate;
stHdl->biquadOutBufLen = 2 * (stHdl->stCfg.stepSz * stHdl->upSmplRate);
}
maxResmplRate = _FSCVRT_MAX(stHdl->upSmplRate, stHdl->downSmplRate);
stHdl->nSec = 0;
memset(stHdl->biquadB, 0, sizeof(stHdl->biquadB));
memset(stHdl->biquadA, 0, sizeof(stHdl->biquadA));
stHdl->biquadG = NULL; // gain for each section
if (stHdl->mode != 0) {
ret = AUP_Fscvrt_FilterSet(maxResmplRate, &(stHdl->nSec), stHdl->biquadB,
stHdl->biquadA, &(stHdl->biquadG));
if (ret < 0) {
return -1;
}
}
return 0;
}
static int AUP_Fscvrt_resetVariables(FscvrtSt* stHdl) {
stHdl->biquadInBufCnt = 0;
stHdl->biquadOutBufCnt = 0;
if (stHdl->dynamMemPtr != NULL && stHdl->dynamMemSize > 0) {
memset(stHdl->dynamMemPtr, 0, stHdl->dynamMemSize);
}
return 0;
}
// ==========================================================================================
// public APIs
// ==========================================================================================
int AUP_Fscvrt_create(void** stPtr) {
FscvrtSt* tmpPtr;
if (stPtr == NULL) {
return -1;
}
*stPtr = (void*)malloc(sizeof(FscvrtSt));
if (*stPtr == NULL) {
return -1;
}
memset(*stPtr, 0, sizeof(FscvrtSt));
tmpPtr = (FscvrtSt*)(*stPtr);
tmpPtr->dynamMemPtr = NULL;
tmpPtr->dynamMemSize = 0;
tmpPtr->stCfg.inputFs = 24000;
tmpPtr->stCfg.outputFs = 32000;
tmpPtr->stCfg.stepSz = 240; // 10ms processing step
tmpPtr->stCfg.inputType = 0; // short in
tmpPtr->stCfg.outputType = 0; // short out
if (AUP_Biquad_create(&(tmpPtr->biquadSt)) < 0) {
return -1;
}
return 0;
}
int AUP_Fscvrt_destroy(void** stPtr) {
FscvrtSt* stHdl;
if (stPtr == NULL) {
return 0;
}
stHdl = (FscvrtSt*)(*stPtr);
if (stHdl == NULL) {
return 0;
}
AUP_Biquad_destroy(&(stHdl->biquadSt));
if (stHdl->dynamMemPtr != NULL) {
free(stHdl->dynamMemPtr);
}
stHdl->dynamMemPtr = NULL;
free(stHdl);
(*stPtr) = NULL;
return 0;
}
int AUP_Fscvrt_memAllocate(void* stPtr, const FscvrtStaticCfg* pCfg) {
FscvrtSt* stHdl = NULL;
FscvrtStaticCfg tmpStatCfg = {0};
Biquad_StaticCfg bqStatCfg;
int idx, ret;
int totalMemSize = 0;
if (stPtr == NULL || pCfg == NULL) {
return -1;
}
stHdl = (FscvrtSt*)(stPtr);
memcpy(&tmpStatCfg, pCfg, sizeof(FscvrtStaticCfg));
if (AUP_Fscvrt_checkStatCfg(&tmpStatCfg) < 0) {
return -1;
}
memcpy(&(stHdl->stCfg), &tmpStatCfg, sizeof(FscvrtStaticCfg));
if (AUP_Fscvrt_publishStaticCfg(stHdl) < 0) {
return -1;
}
// check memory requirement
totalMemSize = AUP_Fscvrt_dynamMemPrepare(stHdl, NULL, 0);
if (totalMemSize < 0) {
return -1;
}
// allocate dynamic memory
if ((size_t)totalMemSize > stHdl->dynamMemSize) {
if (stHdl->dynamMemPtr != NULL) {
free(stHdl->dynamMemPtr);
stHdl->dynamMemSize = 0;
}
stHdl->dynamMemPtr = (void*)malloc(totalMemSize);
if (stHdl->dynamMemPtr == NULL) {
return -1;
}
stHdl->dynamMemSize = totalMemSize;
}
memset(stHdl->dynamMemPtr, 0, stHdl->dynamMemSize);
// setup the pointers/variable
if (AUP_Fscvrt_dynamMemPrepare(stHdl, stHdl->dynamMemPtr,
stHdl->dynamMemSize) < 0) {
return -1;
}
// memAllocation for upSmplBiquadSt and downSmplBiquadSt
if (stHdl->nSec != 0) {
if (stHdl->nSec > AGORA_UAP_BIQUAD_MAX_SECTION) {
return -1;
}
memset(&bqStatCfg, 0, sizeof(Biquad_StaticCfg));
bqStatCfg.maxNSample = (size_t)(stHdl->biquadInBufLen);
bqStatCfg.nsect = stHdl->nSec;
for (idx = 0; idx < stHdl->nSec; idx++) {
bqStatCfg.B[idx] = stHdl->biquadB[idx];
bqStatCfg.A[idx] = stHdl->biquadA[idx];
}
bqStatCfg.G = stHdl->biquadG;
ret = AUP_Biquad_memAllocate(stHdl->biquadSt, &bqStatCfg);
if (ret < 0) {
return -1;
}
}
return 0;
}
int AUP_Fscvrt_init(void* stPtr) {
FscvrtSt* stHdl;
if (stPtr == NULL) {
return -1;
}
stHdl = (FscvrtSt*)(stPtr);
// clear/reset run-time variables
if (AUP_Fscvrt_resetVariables(stHdl) < 0) {
return -1;
}
// init submodules ...
if (stHdl->biquadSt != NULL && stHdl->nSec != 0) {
if (AUP_Biquad_init(stHdl->biquadSt) < 0) {
return -1;
}
}
return 0;
}
int AUP_Fscvrt_getStaticCfg(const void* stPtr, FscvrtStaticCfg* pCfg) {
const FscvrtSt* stHdl;
if (stPtr == NULL || pCfg == NULL) {
return -1;
}
stHdl = (const FscvrtSt*)(stPtr);
memcpy(pCfg, &(stHdl->stCfg), sizeof(FscvrtStaticCfg));
return 0;
}
int AUP_Fscvrt_getInfor(const void* stPtr, FscvrtGetData* buff) {
const FscvrtSt* stHdl;
int delayBiquad = 0;
int tmp;
if (stPtr == NULL || buff == NULL) {
return -1;
}
stHdl = (const FscvrtSt*)(stPtr);
if (stHdl->nSec != 0) {
if (AUP_Biquad_getAlgDelay(stHdl->biquadSt, &delayBiquad) < 0) {
return -1;
}
}
if (stHdl->mode == 0) {
buff->delayInInputFs = 0;
} else if (stHdl->mode == 1) {
buff->delayInInputFs =
(int)roundf(delayBiquad / (float)(stHdl->upSmplRate));
} else if (stHdl->mode == 2) { // direct downsampling
buff->delayInInputFs = delayBiquad;
} else { // stHdl->mode == 3
buff->delayInInputFs =
(int)roundf(delayBiquad / (float)(stHdl->upSmplRate));
}
tmp = stHdl->stCfg.stepSz * stHdl->upSmplRate / stHdl->downSmplRate;
if (tmp * stHdl->downSmplRate == stHdl->stCfg.stepSz * stHdl->upSmplRate) {
buff->maxOutputStepSz = tmp;
} else {
buff->maxOutputStepSz = tmp + 1;
}
return 0;
}
int AUP_Fscvrt_proc(void* stPtr, const FscvrtInData* pIn, FscvrtOutData* pOut) {
FscvrtSt* stHdl = NULL;
const FscvrtStaticCfg* pCfg;
Biquad_InputData bqdInData;
Biquad_OutputData bqdOutData;
const short* shortSrcPtr = NULL;
const float* floatSrcPtr = NULL;
short* shortTgtPtr = NULL;
float* floatTgtPtr = NULL;
int idx, tgtIdx;
int nOutSamples = 0, samplesTaken = 0, samplesLeft = 0;
int jumpRate;
if (stPtr == NULL || pIn == NULL || pOut == NULL || pIn->inDataSeq == NULL ||
pOut->outDataSeq == NULL) { // pCtrl == NULL
return -1;
}
stHdl = (FscvrtSt*)(stPtr);
pCfg = (const FscvrtStaticCfg*)&(stHdl->stCfg);
shortSrcPtr = (const short*)(pIn->inDataSeq);
floatSrcPtr = (const float*)(pIn->inDataSeq);
// ==============================================================================
// mode-0: bypass
if (stHdl->mode == 0) { // direct bypass
if (pIn->outDataSeqLen < pCfg->stepSz) {
return -1;
}
pOut->nOutData = pCfg->stepSz;
pOut->outDataType = pCfg->outputType;
if (pIn->inDataSeq == pOut->outDataSeq) {
if (pCfg->outputType == pCfg->inputType)
return 0; // we don't need to do anything
return -1;
// if input buffer and the output buffer are the same, but required
// different data type: error, we currently do not support such usecase
}
if (pCfg->inputType == 0 && pCfg->outputType == 0) {
memcpy(pOut->outDataSeq, pIn->inDataSeq, sizeof(short) * pCfg->stepSz);
} else if (pCfg->inputType == 1 && pCfg->outputType == 1) {
memcpy(pOut->outDataSeq, pIn->inDataSeq, sizeof(float) * pCfg->stepSz);
} else if (pCfg->inputType == 0 && pCfg->outputType == 1) {
for (idx = 0; idx < pCfg->stepSz; idx++) {
((float*)pOut->outDataSeq)[idx] = ((short*)pIn->inDataSeq)[idx];
}
} else { // if (pCfg->inputType == 1 && pCfg->outputType == 0)
for (idx = 0; idx < pCfg->stepSz; idx++) {
((short*)pOut->outDataSeq)[idx] =
(short)_FSCVRT_FLOAT2SHORT(((float*)pIn->inDataSeq)[idx]);
}
}
return 0;
}
// prepare input buffer for Biquad .....
memset(stHdl->biquadInBuf, 0, sizeof(float) * stHdl->biquadInBufLen);
if (pCfg->inputType == 0) {
for (idx = 0; idx < pCfg->stepSz; idx++) {
stHdl->biquadInBuf[idx * (stHdl->upSmplRate)] =
((float)shortSrcPtr[idx]) * stHdl->upSmplRate;
}
} else {
for (idx = 0; idx < pCfg->stepSz; idx++) {
stHdl->biquadInBuf[idx * (stHdl->upSmplRate)] =
floatSrcPtr[idx] * stHdl->upSmplRate;
}
}
// biquad filtering ......
memset(&bqdInData, 0, sizeof(Biquad_InputData));
memset(&bqdOutData, 0, sizeof(Biquad_OutputData));
bqdInData.samplesPtr = (const void*)(stHdl->biquadInBuf);
bqdInData.sampleType = 1;
bqdInData.nsamples = (size_t)(pCfg->stepSz * stHdl->upSmplRate);
bqdOutData.outputBuff = (void*)&(stHdl->biquadOutBuf[stHdl->biquadOutBufCnt]);
if (stHdl->biquadOutBufCnt + (pCfg->stepSz * stHdl->upSmplRate) >
stHdl->biquadOutBufLen) {
return -1;
}
if (AUP_Biquad_proc(stHdl->biquadSt, &bqdInData, &bqdOutData) < 0) {
return -1;
}
stHdl->biquadOutBufCnt += (pCfg->stepSz * stHdl->upSmplRate);
// checking the output buffer .........
nOutSamples = stHdl->biquadOutBufCnt / stHdl->downSmplRate;
if (pIn->outDataSeqLen < nOutSamples) {
return -1;
}
// prepare output data, downsampling and throwing out ......
pOut->nOutData = nOutSamples;
pOut->outDataType = pCfg->outputType;
shortTgtPtr = (short*)pOut->outDataSeq;
floatTgtPtr = (float*)pOut->outDataSeq;
jumpRate = stHdl->downSmplRate;
if (pCfg->outputType == 0) { // -> shortTgtPtr
for (idx = (jumpRate - 1), tgtIdx = 0; idx < stHdl->biquadOutBufCnt;
idx += jumpRate, tgtIdx++) {
shortTgtPtr[tgtIdx] = _FSCVRT_FLOAT2SHORT(stHdl->biquadOutBuf[idx]);
}
} else { // -> floatTgtPtr
for (idx = (jumpRate - 1), tgtIdx = 0; idx < stHdl->biquadOutBufCnt;
idx += jumpRate, tgtIdx++) {
floatTgtPtr[tgtIdx] = stHdl->biquadOutBuf[idx];
}
}
if (nOutSamples != tgtIdx) {
return -1;
}
// update the stHdl->biquadOutBuf and stHdl->biquadOutBufCnt
samplesTaken = nOutSamples * jumpRate;
samplesLeft = stHdl->biquadOutBufCnt - samplesTaken;
if (samplesLeft == 0) {
stHdl->biquadOutBufCnt = 0;
} else if (samplesLeft > 0) {
stHdl->biquadOutBufCnt = samplesLeft;
memmove(stHdl->biquadOutBuf, &(stHdl->biquadOutBuf[samplesTaken]),
sizeof(float) * samplesLeft);
} else { // samplesLeft < 0
stHdl->biquadOutBufCnt = 0;
return -1;
}
return 0;
}

View file

@ -1,186 +0,0 @@
//
// Copyright © 2025 Agora
// This file is part of TEN Framework, an open source project.
// Licensed under the Apache License, Version 2.0, with certain conditions.
// Refer to the "LICENSE" file in the root directory for more information.
//
#ifndef __FSCVRT_H__
#define __FSCVRT_H__
#define AUP_FSCVRT_MAX_INPUT_LEN (2400)
// max. number of samples each time can be fed in
#include <stdio.h>
typedef struct FscvrtStaticCfg_ {
int inputFs; // input stream sampling freq.
int outputFs; // output stream sampling freq.
int stepSz; // number of input samples per each proc.
int inputType; // input data type, 0: short, 1: float
int outputType; // output data type, 0: short, 1: float
} FscvrtStaticCfg;
typedef struct FscvrtInData_ {
const void* inDataSeq; // [stepSz], externally provided buffer
int outDataSeqLen;
// the length of externally provided buffer outDataSeq in OutData
} FscvrtInData;
typedef struct FscvrtOutData_ {
int nOutData; // number of samples in outDataSeq
// this value may vary by +-1 from frame-to-frame
// and the user needs to check if nOutData <= outDataSeqLen
// o.w. the buffer outDataSeq is not long enough
int outDataType; // output data type, 0: short, 1: float
void* outDataSeq; // [outDataSeqLen], externally provided buffer
} FscvrtOutData;
typedef struct FscvrtGetData_ {
int maxOutputStepSz; // max. number of output samples per each proc.
int delayInInputFs; // algorithm delay in terms of samples @ input fs
} FscvrtGetData;
#ifdef __cplusplus
extern "C" {
#endif
/****************************************************************************
* AUP_Fscvrt_create(...)
*
* This function creats a state handler from nothing, which is NOT ready for
* processing
*
* Input:
*
* Output:
* - stPtr : buffer to store the returned state handler
*
* Return value : 0 - Ok
* -1 - Error
*/
int AUP_Fscvrt_create(void** stPtr);
/****************************************************************************
* AUP_Fscvrt_destroy(...)
*
* destroy biquad instance, and releasing all the dynamically allocated memory
*
* Input:
* - stPtr : buffer of State Handler, after this method, this
* handler won't be usable anymore
*
* Output:
*
* Return value : 0 - Ok
* -1 - Error
*/
int AUP_Fscvrt_destroy(void** stPtr);
/****************************************************************************
* AUP_Fscvrt_memAllocate(...)
*
* This function sets Static Config params and does memory allocation
* operation
*
* Input:
* - stPtr : State Handler which was returned by _create
* - pCfg : static configuration parameters
*
* Output:
*
* Return value : 0 - Ok
* -1 - Error
*/
int AUP_Fscvrt_memAllocate(void* stPtr, const FscvrtStaticCfg* pCfg);
/****************************************************************************
* AUP_Fscvrt_init(...)
*
* This function resets (initialize) the XXXX module and gets it prepared for
* processing
*
* Input:
* - stPtr : State Handler which has gone through create and
* memAllocate
*
* Output:
*
* Return value : 0 - Ok
* -1 - Error
*/
int AUP_Fscvrt_init(void* stPtr);
/****************************************************************************
* AUP_Fscvrt_setDynamCfg(...)
*
* This function set dynamic (per-frame variable) configuration
*
* Input:
* - stPtr : State Handler which has gone through create and
* memAllocate
* - pCfg : configuration content
*
* Output:
*
* Return value : 0 - Ok
* -1 - Error
*/
int AUP_Fscvrt_setDynamCfg(void* stPtr);
/****************************************************************************
* AUP_Fscvrt_getStaticCfg(...)
*
* This function get static configuration status from XXXXX module
*
* Input:
* - stPtr : State Handler which has gone through create and
* memAllocate
*
* Output:
* - pCfg : configuration content
*
* Return value : 0 - Ok
* -1 - Error
*/
int AUP_Fscvrt_getStaticCfg(const void* stPtr, FscvrtStaticCfg* pCfg);
/****************************************************************************
* AUP_Fscvrt_getInfor(...)
*
* This function get subsidiary information from Fs-Converter module
*
* Input:
* - stPtr : State Handler which has gone through create and
* memAllocate
*
* Output:
* - FscvrtGetData : returned information
*
* Return value : 0 - Ok
* -1 - Error
*/
int AUP_Fscvrt_getInfor(const void* stPtr, FscvrtGetData* buff);
/****************************************************************************
* AUP_Fscvrt_proc(...)
*
* process a single frame
*
* Input:
* - stPtr : State Handler which has gone through create and
* memAllocate
* - pCtrl : per-frame variable control parameters
* - pIn : input data stream
*
* Output:
* - pOut : output data (mask, highband time-domain gain etc.)
*
* Return value : 0 - Ok
* -1 - Error
*/
int AUP_Fscvrt_proc(void* stPtr, const FscvrtInData* pIn, FscvrtOutData* pOut);
#ifdef __cplusplus
}
#endif
#endif // __FSCVRT_H__

View file

@ -1,123 +0,0 @@
//
// Copyright © 2025 Agora
// This file is part of TEN Framework, an open source project.
// Licensed under the Apache License, Version 2.0, with certain conditions.
// Refer to the "LICENSE" file in the root directory for more information.
//
#ifndef __FSCVRT_ST_H__
#define __FSCVRT_ST_H__
#include <stdio.h>
#include "fscvrt.h"
#define _FSCVRT_MAXNSEC (40)
#define _FSCVRT_COMMON_FS (96000)
#define _FSCVRT_ALIGN8(o) (((o) + 7) & (~7))
#define _FSCVRT_FLOAT2SHORT(x) \
((x) < -32767.5f ? -32768 : ((x) > 32766.5f ? 32767 : (short)floor(.5 + (x))))
#define _FSCVRT_MIN(x, y) ((x > y) ? (y) : (x))
#define _FSCVRT_MAX(x, y) ((x > y) ? (x) : (y))
#define _FSCVRT_1over2_LOWPASS_NSEC (5)
static const float _FSCVRT_1over2_LOWPASS_B[_FSCVRT_1over2_LOWPASS_NSEC][3] = {
{1.000000e+00f, 1.830863e+00f, 1.000000e+00f},
{1.000000e+00f, 1.039654e+00f, 1.000000e+00f},
{1.000000e+00f, 4.900788e-01f, 1.000000e+00f},
{1.000000e+00f, 2.419292e-01f, 1.000000e+00f},
{1.000000e+00f, 1.517919e-01f, 1.000000e+00f}};
static const float _FSCVRT_1over2_LOWPASS_A[_FSCVRT_1over2_LOWPASS_NSEC][3] = {
{1.000000e+00f, -8.445478e-01f, 2.453003e-01f},
{1.000000e+00f, -5.469711e-01f, 5.010509e-01f},
{1.000000e+00f, -2.646897e-01f, 7.464574e-01f},
{1.000000e+00f, -1.074159e-01f, 8.912371e-01f},
{1.000000e+00f, -4.448528e-02f, 9.702184e-01f}};
static const float _FSCVRT_1over2_LOWPASS_G[_FSCVRT_1over2_LOWPASS_NSEC] = {
// 4.184914e-01f,4.184914e-01f,4.184914e-01f,4.184914e-01f,4.184914e-01f
4.233410e-01f, 4.233410e-01f, 4.233410e-01f, 4.233410e-01f, 4.233410e-01f};
#define _FSCVRT_1over3_LOWPASS_NSEC (5)
static const float _FSCVRT_1over3_LOWPASS_B[_FSCVRT_1over3_LOWPASS_NSEC][3] = {
{1.000000e+00f, 1.535971e+00f, 1.000000e+00f},
{1.000000e+00f, 6.284728e-02f, 1.000000e+00f},
{1.000000e+00f, -5.726159e-01f, 1.000000e+00f},
{1.000000e+00f, -7.990919e-01f, 1.000000e+00f},
{1.000000e+00f, -8.741772e-01f, 1.000000e+00f}};
static const float _FSCVRT_1over3_LOWPASS_A[_FSCVRT_1over3_LOWPASS_NSEC][3] = {
{1.000000e+00f, -1.261229e+00f, 4.351921e-01f},
{1.000000e+00f, -1.171732e+00f, 6.072938e-01f},
{1.000000e+00f, -1.078980e+00f, 7.901941e-01f},
{1.000000e+00f, -1.026436e+00f, 9.073955e-01f},
{1.000000e+00f, -1.013524e+00f, 9.743813e-01f}};
static const float _FSCVRT_1over3_LOWPASS_G[_FSCVRT_1over3_LOWPASS_NSEC] = {
// 3.126979e-01f,3.126979e-01f,3.126979e-01f,3.126979e-01f,3.126979e-01f
3.1704682e-01f, 3.1704682e-01f, 3.1704682e-01f, 3.1704682e-01f,
3.1704682e-01f};
#define _FSCVRT_1over4_LOWPASS_NSEC (5)
static const float _FSCVRT_1over4_LOWPASS_B[_FSCVRT_1over4_LOWPASS_NSEC][3] = {
{1.000000e+00f, 1.193034e+00f, 1.000000e+00f},
{1.000000e+00f, -5.757392e-01f, 1.000000e+00f},
{1.000000e+00f, -1.105338e+00f, 1.000000e+00f},
{1.000000e+00f, -1.271233e+00f, 1.000000e+00f},
{1.000000e+00f, -1.323929e+00f, 1.000000e+00f}};
static const float _FSCVRT_1over4_LOWPASS_A[_FSCVRT_1over4_LOWPASS_NSEC][3] = {
{1.000000e+00f, -1.447526e+00f, 5.478735e-01f},
{1.000000e+00f, -1.429707e+00f, 6.830356e-01f},
{1.000000e+00f, -1.412017e+00f, 8.292100e-01f},
{1.000000e+00f, -1.405145e+00f, 9.242718e-01f},
{1.000000e+00f, -1.412679e+00f, 9.790443e-01f}};
static const float _FSCVRT_1over4_LOWPASS_G[_FSCVRT_1over4_LOWPASS_NSEC] = {
// 2.700060e-01f,2.700060e-01f,2.700060e-01f,2.700060e-01f,2.700060e-01f
2.7502688e-01f, 2.7502688e-01f, 2.7502688e-01f, 2.7502688e-01f,
2.7502688e-01f};
#define _FSCVRT_1over6_LOWPASS_NSEC (5)
static const float _FSCVRT_1over6_LOWPASS_B[_FSCVRT_1over6_LOWPASS_NSEC][3] = {
{1.000000e+00f, 4.149228e-01f, 1.000000e+00f},
{1.000000e+00f, -1.285358e+00f, 1.000000e+00f},
{1.000000e+00f, -1.583012e+00f, 1.000000e+00f},
{1.000000e+00f, -1.663823e+00f, 1.000000e+00f},
{1.000000e+00f, -1.688104e+00f, 1.000000e+00f}};
static const float _FSCVRT_1over6_LOWPASS_A[_FSCVRT_1over6_LOWPASS_NSEC][3] = {
{1.000000e+00f, -1.688731e+00f, 7.264798e-01f},
{1.000000e+00f, -1.696982e+00f, 8.146896e-01f},
{1.000000e+00f, -1.706117e+00f, 9.049889e-01f},
{1.000000e+00f, -1.713737e+00f, 9.598250e-01f},
{1.000000e+00f, -1.723161e+00f, 9.892408e-01f}};
static const float _FSCVRT_1over6_LOWPASS_G[_FSCVRT_1over6_LOWPASS_NSEC] = {
// 2.333130e-01f,2.333130e-01f,2.333130e-01f,2.333130e-01f,2.333130e-01f
2.3765156e-01f, 2.3765156e-01f, 2.3765156e-01f, 2.3765156e-01f,
2.3765156e-01f};
typedef struct FscvrtSt_ {
void* dynamMemPtr; // memory pointer holding the dynamic memory
size_t dynamMemSize; // size of the buffer *dynamMemPtr
// Static Configuration
FscvrtStaticCfg stCfg;
// Internal Static Config Registers, which are generated from stCfg
int mode;
// 0: direct bypass, 1: direct upsampling, 2: direct downsampling
// 3: upsampling->downsampling
int upSmplRate;
int downSmplRate;
int biquadInBufLen; // biquad input buffer length
int biquadOutBufLen; // biquad output buffer length
int nSec;
const float* biquadB[_FSCVRT_MAXNSEC];
const float* biquadA[_FSCVRT_MAXNSEC];
const float* biquadG; // gain for each section
// ---------------------------------------------------------------
// Variables
void* biquadSt; // biqua filter state handler
int biquadInBufCnt;
float* biquadInBuf; // [biquadInBufLen]
int biquadOutBufCnt;
float* biquadOutBuf; // [biquadOutBufLen]
} FscvrtSt;
#endif // __FSCVRT_ST_H__

File diff suppressed because it is too large Load diff

View file

@ -1,229 +0,0 @@
//
// Copyright © 2025 Agora
// This file is part of TEN Framework, an open source project.
// Licensed under the Apache License, Version 2.0, with certain conditions.
//
// Refer to the "LICENSE" file in the root directory for more information.
//
#ifndef __PITCH_EST_H__
#define __PITCH_EST_H__
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#define AUP_PE_MAX_FFTSIZE (1024)
#define AUP_PE_MAX_NBINS ((AUP_PE_MAX_FFTSIZE >> 1) + 1)
#define AUP_PE_FS (16000)
// assumed sampling freq. of this module
// Configuration Parameters, which impacts dynamic memory occupation, can only
// be set during allocation
typedef struct PE_StaticCfg_ {
size_t fftSz; // fft-size, only support: 128, 256, 512, 1024
size_t anaWindowSz; // analysis fft-Window Size, will be used in LPC estimate
size_t hopSz; // fft-Hop Size, will be used to check
int useLPCPreFiltering;
// 0: use raw pcm to estimate pitch
// 1: use LPC prefiltering before pitch estimation
size_t procFs; // internal processing sampling rate
// 2000/4000/8000/16000
} PE_StaticCfg;
// Configuraiton parameters which can be modified/set every frames
typedef struct PE_DynamCfg_ {
float voicedThr; // threshold on frame correlation coeff to label if voice
// present
// suggested value: procFs == 2KHz, Yes: 0.45, No: 0.4
} PE_DynamCfg;
// Spectrum are assumed to be generated with time-domain samples in [-32768,
// 32767] WITH LEC blowup protection Note: the input timeSignal has to be in
// 16KHz sampling-rate
typedef struct PE_InputData_ {
const float*
timeSignal; // [hopSz] // this frame's input signal, in [-32768, 32767]
int hopSz; // should be equal to StaticCfg->hopSz
// if useLPCPreFiltering == 0, the following two input argument
// are not necessary
const float* inBinPow; // [nBins], bin-wise power
int nBins;
} PE_InputData;
typedef struct PE_OutputData_ {
float pitchFreq; // the current estimated pitch freq.
// <= 0: no voice
int voiced; // 0: no-voice, 1: voice-present
} PE_OutputData;
typedef struct PE_GetData_ {
float pitchFreq; // the current estimated pitch freq.
// <= 0: no voice
int voiced; // 0: no-voice, 1: voice-present
} PE_GetData;
#ifdef __cplusplus
extern "C" {
#endif
/****************************************************************************
* AUP_PE_create(...)
*
* This function creats a state handler from nothing, which is NOT ready for
* processing
*
* Input:
*
* Output:
* - stPtr : buffer to store the returned state handler
*
* Return value : 0 - Ok
* -1 - Error
*/
int AUP_PE_create(void** stPtr);
/****************************************************************************
* AUP_PE_destroy(...)
*
* destroy PE instance, and releasing all the dynamically allocated memory
*
* Input:
* - stPtr : buffer of State Handler, after this method, this
* handler won't be usable anymore
*
* Output:
*
* Return value : 0 - Ok
* -1 - Error
*/
int AUP_PE_destroy(void** stPtr);
/****************************************************************************
* AUP_PE_memAllocate(...)
*
* This function sets Static Config params and does memory allocation
* operation, will lose the dynamCfg values
*
* Input:
* - stPtr : State Handler which was returned by _create
* - pCfg : static configuration parameters
*
* Output:
*
* Return value : 0 - Ok
* -1 - Error
*/
int AUP_PE_memAllocate(void* stPtr, const PE_StaticCfg* pCfg);
/****************************************************************************
* AUP_PE_init(...)
*
* This function resets (initialize) the PE module and gets it prepared for
* processing
*
* Input:
* - stPtr : State Handler which has gone through create and
* memAllocate
*
* Output:
*
* Return value : 0 - Ok
* -1 - Error
*/
int AUP_PE_init(void* stPtr);
/****************************************************************************
* AUP_PE_setDynamCfg(...)
*
* This function set dynamic (per-frame variable) configuration
*
* Input:
* - stPtr : State Handler which has gone through create and
* memAllocate
* - pCfg : configuration content
*
* Output:
*
* Return value : 0 - Ok
* -1 - Error
*/
int AUP_PE_setDynamCfg(void* stPtr, const PE_DynamCfg* pCfg);
/****************************************************************************
* AUP_PE_getStaticCfg(...)
*
* This function get static configuration status from PE module
*
* Input:
* - stPtr : State Handler which has gone through create and
* memAllocate
*
* Output:
* - pCfg : configuration content
*
* Return value : 0 - Ok
* -1 - Error
*/
int AUP_PE_getStaticCfg(const void* stPtr, PE_StaticCfg* pCfg);
/****************************************************************************
* AUP_PE_getDynamCfg(...)
*
* This function get dynamic (per-frame variable) configuration status from
* PE module
*
* Input:
* - stPtr : State Handler which has gone through create and
* memAllocate
*
* Output:
* - pCfg : configuration content
*
* Return value : 0 - Ok
* -1 - Error
*/
int AUP_PE_getDynamCfg(const void* stPtr, PE_DynamCfg* pCfg);
/****************************************************************************
* AUP_PE_getAlgDelay(...)
*
* This function get algorithm delay from PE module
*
* Input:
* - stPtr : State Handler which has gone through create and
* memAllocate
*
* Output:
* - delayInFrms : algorithm delay in terms of frames
*
* Return value : 0 - Ok
* -1 - Error
*/
int AUP_PE_getAlgDelay(const void* stPtr, int* delayInFrms);
/****************************************************************************
* AUP_PE_proc(...)
*
* process a single frame
*
* Input:
* - stPtr : State Handler which has gone through create and
* memAllocate and reset
* - pCtrl : per-frame variable control parameters
* - pIn : input data stream
*
* Output:
* - pOut : output data (mask, highband time-domain gain etc.)
*
* Return value : 0 - Ok
* -1 - Error
*/
int AUP_PE_proc(void* stPtr, const PE_InputData* pIn, PE_OutputData* pOut);
#ifdef __cplusplus
}
#endif
#endif // __PITCH_EST_H__

View file

@ -1,166 +0,0 @@
//
// Copyright © 2025 Agora
// This file is part of TEN Framework, an open source project.
// Licensed under the Apache License, Version 2.0, with certain conditions.
// Refer to the "LICENSE" file in the root directory for more information.
//
#ifndef __PITCH_EST_ST_H__
#define __PITCH_EST_ST_H__
#include <stdio.h>
#include "pitch_est.h"
#define AUP_PE_ALIGN8(o) (((o) + 7) & (~7))
#define AUP_PE_MAX(x, y) (((x) > (y)) ? (x) : (y))
#define AUP_PE_MIN(x, y) (((x) > (y)) ? (y) : (x))
#define AUP_PE_NB_BANDS (18) // number of mel bands
#define AUP_PE_LPC_ORDER (16)
#define AUP_PE_XCORR_TRAINING_OFFSET (80) // = 80
#define AUP_PE_MIN_PERIOD_16KHZ (32) // stands for 1.333kHz, PITCH_MIN_PERIOD
#define AUP_PE_MAX_PERIOD_16KHZ (256) // stands for ~62Hz, PITCH_MAX_PERIOD
#define AUP_PE_LOWPSS_NSEC (5)
const float AUP_PE_B_2KHZ[AUP_PE_LOWPSS_NSEC][3] = {
{1.000000e+00f, -1.303155e-01f, 1.000000e+00f},
{1.000000e+00f, -1.563002e+00f, 1.000000e+00f},
{1.000000e+00f, -1.759739e+00f, 1.000000e+00f},
{1.000000e+00f, -1.811650e+00f, 1.000000e+00f},
{1.000000e+00f, -1.827332e+00f, 1.000000e+00f}};
const float AUP_PE_A_2KHZ[AUP_PE_LOWPSS_NSEC][3] = {
{1.000000e+00f, -1.726800e+00f, 7.526543e-01f},
{1.000000e+00f, -1.762977e+00f, 8.277960e-01f},
{1.000000e+00f, -1.802014e+00f, 9.079320e-01f},
{1.000000e+00f, -1.828423e+00f, 9.594240e-01f},
{1.000000e+00f, -1.846774e+00f, 9.888390e-01f}};
const float AUP_PE_G_2KHZ[AUP_PE_LOWPSS_NSEC] = {
2.156619e-01f, 2.156619e-01f, 2.156619e-01f, 2.156619e-01f, 2.156619e-01f};
const float AUP_PE_B_4KHZ[AUP_PE_LOWPSS_NSEC][3] = {
{1.000000e+00f, 1.198825e+00f, 1.000000e+00f},
{1.000000e+00f, -5.674614e-01f, 1.000000e+00f},
{1.000000e+00f, -1.099061e+00f, 1.000000e+00f},
{1.000000e+00f, -1.265846e+00f, 1.000000e+00f},
{1.000000e+00f, -1.318849e+00f, 1.000000e+00f}};
const float AUP_PE_A_4KHZ[AUP_PE_LOWPSS_NSEC][3] = {
{1.000000e+00f, -1.445267e+00f, 5.463974e-01f},
{1.000000e+00f, -1.426720e+00f, 6.820138e-01f},
{1.000000e+00f, -1.408255e+00f, 8.286664e-01f},
{1.000000e+00f, -1.400909e+00f, 9.240320e-01f},
{1.000000e+00f, -1.408242e+00f, 9.789776e-01f}};
const float AUP_PE_G_4KHZ[AUP_PE_LOWPSS_NSEC] = {
2.692541e-01f, 2.692541e-01f, 2.692541e-01f, 2.692541e-01f, 2.692541e-01f};
const float AUP_PE_B_8KHZ[AUP_PE_LOWPSS_NSEC][3] = {
{1.000000e+00f, 1.830863e+00f, 1.000000e+00f},
{1.000000e+00f, 1.039654e+00f, 1.000000e+00f},
{1.000000e+00f, 4.900788e-01f, 1.000000e+00f},
{1.000000e+00f, 2.419292e-01f, 1.000000e+00f},
{1.000000e+00f, 1.517919e-01f, 1.000000e+00f}};
const float AUP_PE_A_8KHZ[AUP_PE_LOWPSS_NSEC][3] = {
{1.000000e+00f, -8.445478e-01f, 2.453003e-01f},
{1.000000e+00f, -5.469711e-01f, 5.010509e-01f},
{1.000000e+00f, -2.646897e-01f, 7.464574e-01f},
{1.000000e+00f, -1.074159e-01f, 8.912371e-01f},
{1.000000e+00f, -4.448528e-02f, 9.702184e-01f}};
const float AUP_PE_G_8KHZ[AUP_PE_LOWPSS_NSEC] = {
4.165686e-01f, 4.165686e-01f, 4.165686e-01f, 4.165686e-01f, 4.165686e-01f};
#define AUP_PE_PI (3.1415926f)
#define AUP_PE_FEAT_TIME_WINDOW (40) // in ms
// how much time data to use for cross-correlation calculation
#define AUP_PE_FEAT_MAX_NFRM (12)
#define AUP_PE_TOTAL_NFEAT (55)
#define AUP_PE_ASSUMED_FFT_4_BAND_ENG (80)
const int AUP_PE_BAND_START_INDEX[AUP_PE_NB_BANDS] = {
// 0 200 400 600 800 1k 1.2 1.4 1.6 2k 2.4 2.8 3.2 4k 4.8 5.6 6.8 8k
0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 34, 40};
// compensation
const float AUP_PE_BAND_LPC_COMP[AUP_PE_NB_BANDS] = {
0.8f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 0.666667f,
0.5f, 0.5f, 0.5f, 0.333333f, 0.25f, 0.25f, 0.2f, 0.166667f, 0.173913f};
#define AUP_PE_PITCHMAXPATH_W (0.02f)
typedef struct PE_St_ {
void* dynamMemPtr; // memory pointer holding the dynamic memory
size_t dynamMemSize; // size of the buffer *dynamMemPtr
// void* ifftStHdl; // AgoraFft*
void* biquadIIRPtr;
// ---------------------------------------------------------------
// Static Configuration
PE_StaticCfg stCfg;
// ---------------------------------------------------------------
// Internal Static Config Registers, which are generated from stCfg
int nBins;
int procResampleRate; // AUP_PE_FS / stCfg.procFs
int minPeriod; // min. pitch period in procFs
int maxPeriod; // max. pitch period in procFs
int difPeriod; // maxPeriod - minPeriod
int inputResampleBufLen; // length of the resampling output buffer
int inputQLen; // MAX(TRAINING_OFFSET_XXXX, hopSz) + hopSz
int excBufLen; // PITCH_MAX_PERIOD + hopSz + 1
int nFeat; // number of feature frames to use/store
int estDelay; // pitch estimate delay in terms of frames
float dct_table[AUP_PE_NB_BANDS *
AUP_PE_NB_BANDS]; // coeff. table of DCT transformation
// ---------------------------------------------------------------
// Dynamic Configuration
PE_DynamCfg dynamCfg;
// ---------------------------------------------------------------
// Internal Dynamic Config Registers, which are generated from dynamCfg
// ---------------------------------------------------------------
// Variables
/////////////////////////////////////////////////////////////////////////
float* inputResampleBuf; // [inputResampleBufLen]
int inputResampleBufIdx;
float* inputQ; // [inputQLen]
float* alignedIn; // [hopSz]
float* lpcFilterOutBuf; // [hopSz]
float* excBuf; // [excBufLen]
// excBuf stores the smoothed LPC prediction result
float* excBufSq; // [excBufLen]
// = excBuf.^2
float lpc[AUP_PE_LPC_ORDER];
float pitch_mem[AUP_PE_LPC_ORDER];
float pitch_filt;
float tmpFeat[AUP_PE_TOTAL_NFEAT];
int xCorrOffsetIdx; // the oldest frame's index in xCorr Buffer
float* xCorrInst; // [maxPeriod]
float* xCorr[AUP_PE_FEAT_MAX_NFRM * 2]; // [stHdl->nFeat * 2][maxPeriod + 1]
// circ-buffer [<--->][...]
float*
xCorrTmp[AUP_PE_FEAT_MAX_NFRM * 2]; // [stHdl->nFeat * 2][maxPeriod + 1]
// temporarily modified version of xCorr
float frmWeight[AUP_PE_FEAT_MAX_NFRM * 2];
float frmWeightNorm[AUP_PE_FEAT_MAX_NFRM * 2];
// normalized version of frmWeight
// variables for best pitch estimation ....
/////////////////////////////////////////////////////////////////////////
float* pitchMaxPathReg[2]; // [2][maxPeriod]
int* pitchPrev[AUP_PE_FEAT_MAX_NFRM * 2]; // [stHdl->nFeat * 2][maxPeriod]
float pitchMaxPathAll;
int bestPeriodEst;
int voiced; // whether this frame has voice
float pitchEstResult; // the final result storing the estimated pitch freq.
} PE_St;
#endif // __PITCH_EST_ST_H__

View file

@ -1,295 +0,0 @@
//
// Copyright © 2025 Agora
// This file is part of TEN Framework, an open source project.
// Licensed under the Apache License, Version 2.0, with certain conditions.
// Refer to the "LICENSE" file in the root directory for more information.
//
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "stft.h"
#include "stft_st.h"
#include "fftw.h"
// ==========================================================================================
// internal tools
// ==========================================================================================
static int AUP_Analyzer_checkStatCfg(Analyzer_StaticCfg* pCfg) {
if (pCfg == NULL) {
return -1;
}
if (pCfg->fft_size != 256 && pCfg->fft_size != 512 &&
pCfg->fft_size != 1024 && pCfg->fft_size != 2048 &&
pCfg->fft_size != 4096) {
return -1;
}
if (pCfg->win_len <= 0 || pCfg->win_len < pCfg->hop_size ||
pCfg->win_len > pCfg->fft_size) {
return -1;
}
if (pCfg->hop_size <= 0) {
return -1;
}
return 0;
}
static int AUP_Analyzer_publishStaticCfg(Analyzer_St* stHdl) {
const Analyzer_StaticCfg* pStatCfg;
int idx;
if (stHdl == NULL) {
return -1;
}
pStatCfg = (const Analyzer_StaticCfg*)(&(stHdl->stCfg));
stHdl->nBins = (pStatCfg->fft_size >> 1) + 1;
if (pStatCfg->ana_win_coeff != NULL) {
memcpy(stHdl->windowCoffCopy, pStatCfg->ana_win_coeff,
sizeof(float) * pStatCfg->win_len);
} else {
for (idx = 0; idx < AUP_STFT_MAX_FFTSZ; idx++) {
stHdl->windowCoffCopy[idx] = 1.0f;
}
}
return 0;
}
static int AUP_Analyzer_resetVariables(Analyzer_St* stHdl) {
memset(stHdl->dynamMemPtr, 0, stHdl->dynamMemSize);
return 0;
}
static int AUP_Analyzer_dynamMemPrepare(Analyzer_St* stHdl, void* memPtrExt,
size_t memSize) {
int inputQMemSz = 0;
int fftInputBufMemSz = 0;
int totalMemSize = 0;
char* memPtr = NULL;
inputQMemSz = AUP_STFT_ALIGN8(sizeof(float) * (stHdl->stCfg.win_len + 4));
totalMemSize += inputQMemSz;
fftInputBufMemSz =
AUP_STFT_ALIGN8(sizeof(float) * (stHdl->stCfg.fft_size + 4));
totalMemSize += fftInputBufMemSz;
// if no external memory provided, we are only profiling the memory
// requirement
if (memPtrExt == NULL) {
return (totalMemSize);
}
// if required memory is more than provided, error
if ((size_t)totalMemSize > memSize) {
return -1;
}
memPtr = (char*)memPtrExt;
stHdl->inputQ = (float*)memPtr;
memPtr += inputQMemSz;
stHdl->fftInputBuf = (float*)memPtr;
memPtr += fftInputBufMemSz;
if (((int)(memPtr - (char*)memPtrExt)) > totalMemSize) {
return -1;
}
return (totalMemSize);
}
// ==========================================================================================
// public APIs
// ==========================================================================================
int AUP_Analyzer_create(void** stPtr) {
Analyzer_St* tmpPtr;
if (stPtr == NULL) {
return -1;
}
*stPtr = (void*)malloc(sizeof(Analyzer_St));
if (*stPtr == NULL) {
return -1;
}
memset(*stPtr, 0, sizeof(Analyzer_St));
tmpPtr = (Analyzer_St*)(*stPtr);
tmpPtr->dynamMemPtr = NULL;
tmpPtr->dynamMemSize = 0;
tmpPtr->stCfg.win_len = 768;
tmpPtr->stCfg.hop_size = 256;
tmpPtr->stCfg.fft_size = 1024;
tmpPtr->stCfg.ana_win_coeff = NULL;
return 0;
}
int AUP_Analyzer_destroy(void** stPtr) {
Analyzer_St* stHdl;
if (stPtr == NULL) {
return 0;
}
stHdl = (Analyzer_St*)(*stPtr);
if (stHdl == NULL) {
return 0;
}
if (stHdl->dynamMemPtr != NULL) {
free(stHdl->dynamMemPtr);
}
stHdl->dynamMemPtr = NULL;
free(stHdl);
(*stPtr) = NULL;
return 0;
}
int AUP_Analyzer_memAllocate(void* stPtr, const Analyzer_StaticCfg* pCfg) {
Analyzer_St* stHdl = NULL;
Analyzer_StaticCfg localStCfg;
int totalMemSize = 0;
if (stPtr == NULL || pCfg == NULL) {
return -1;
}
stHdl = (Analyzer_St*)(stPtr);
memcpy(&localStCfg, pCfg, sizeof(Analyzer_StaticCfg));
if (AUP_Analyzer_checkStatCfg(&localStCfg) < 0) {
return -1;
}
memcpy(&(stHdl->stCfg), &localStCfg, sizeof(Analyzer_StaticCfg));
// 1st. publish internal static configuration registers
if (AUP_Analyzer_publishStaticCfg(stHdl) < 0) {
return -1;
}
// 4th: check memory requirement
totalMemSize = AUP_Analyzer_dynamMemPrepare(stHdl, NULL, 0);
if (totalMemSize < 0) {
return -1;
}
// 5th: allocate dynamic memory
if ((size_t)totalMemSize > stHdl->dynamMemSize) {
if (stHdl->dynamMemPtr != NULL) {
free(stHdl->dynamMemPtr);
stHdl->dynamMemSize = 0;
}
stHdl->dynamMemPtr = malloc(totalMemSize);
if (stHdl->dynamMemPtr == NULL) {
return -1;
}
stHdl->dynamMemSize = totalMemSize;
}
memset(stHdl->dynamMemPtr, 0, stHdl->dynamMemSize);
// 6th: setup the pointers/variable
if (AUP_Analyzer_dynamMemPrepare(stHdl, stHdl->dynamMemPtr,
stHdl->dynamMemSize) < 0) {
return -1;
}
return 0;
}
int AUP_Analyzer_init(void* stPtr) {
Analyzer_St* stHdl;
if (stPtr == NULL) {
return -1;
}
stHdl = (Analyzer_St*)(stPtr);
if (AUP_Analyzer_resetVariables(stHdl) < 0) {
return -1;
}
return 0;
}
int AUP_Analyzer_getStaticCfg(const void* stPtr, Analyzer_StaticCfg* pCfg) {
const Analyzer_St* stHdl;
if (stPtr == NULL || pCfg == NULL) {
return -1;
}
stHdl = (const Analyzer_St*)(stPtr);
memcpy(pCfg, &(stHdl->stCfg), sizeof(Analyzer_StaticCfg));
return 0;
}
int AUP_Analyzer_proc(void* stPtr, const Analyzer_InputData* pIn,
Analyzer_OutputData* pOut) {
Analyzer_St* stHdl = NULL;
int hopSz, fftSz, winLen, nBins;
int idx = 0;
if (stPtr == NULL || pIn == NULL || pIn->input == NULL || pOut == NULL ||
pOut->output == NULL) {
return -1;
}
stHdl = (Analyzer_St*)(stPtr);
if (pIn->iLength != stHdl->stCfg.hop_size ||
pOut->oLength < stHdl->stCfg.fft_size) {
return -1;
}
hopSz = stHdl->stCfg.hop_size;
fftSz = stHdl->stCfg.fft_size;
nBins = (fftSz >> 1) + 1;
winLen = stHdl->stCfg.win_len;
memset(pOut->output, 0, sizeof(float) * pOut->oLength);
memmove(stHdl->inputQ, stHdl->inputQ + hopSz,
sizeof(float) * (winLen - hopSz));
memcpy(stHdl->inputQ + (winLen - hopSz), pIn->input, sizeof(float) * hopSz);
if (stHdl->stCfg.ana_win_coeff != NULL) {
for (idx = 0; idx < winLen; idx++) {
stHdl->fftInputBuf[idx] = stHdl->inputQ[idx] * stHdl->windowCoffCopy[idx];
}
} else {
for (idx = 0; idx < winLen; idx++) {
stHdl->fftInputBuf[idx] = stHdl->inputQ[idx];
}
}
for (; idx < fftSz; idx++) {
stHdl->fftInputBuf[idx] = 0;
}
if (fftSz == 256) {
AUP_FFTW_r2c_256(stHdl->fftInputBuf, pOut->output);
} else if (fftSz == 512) {
AUP_FFTW_r2c_512(stHdl->fftInputBuf, pOut->output);
} else if (fftSz == 1024) {
AUP_FFTW_r2c_1024(stHdl->fftInputBuf, pOut->output);
} else if (fftSz == 2048) {
AUP_FFTW_r2c_2048(stHdl->fftInputBuf, pOut->output);
} else if (fftSz == 4096) {
AUP_FFTW_r2c_4096(stHdl->fftInputBuf, pOut->output);
}
AUP_FFTW_InplaceTransf(1, fftSz, pOut->output);
AUP_FFTW_RescaleFFTOut(fftSz, pOut->output);
return 0;
}

View file

@ -1,148 +0,0 @@
//
// Copyright © 2025 Agora
// This file is part of TEN Framework, an open source project.
// Licensed under the Apache License, Version 2.0, with certain conditions.
// Refer to the "LICENSE" file in the root directory for more information.
//
#ifndef __STFT_H__
#define __STFT_H__
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#define AUP_STFT_MAX_FFTSZ (4096)
// Configuration Parameters, which impacts dynamic memory occupation, can only
// be set during allocation
typedef struct Analyzer_StaticCfg_ {
int win_len;
int hop_size;
int fft_size;
const float* ana_win_coeff;
} Analyzer_StaticCfg;
// Spectrum are assumed to be generated with time-domain samples in [-32768,
// 32767] WITH LEC blowup protection Note: the input timeSignal has to be in
// 16KHz sampling-rate
typedef struct Analyzer_InputData_ {
float* input;
int iLength;
} Analyzer_InputData;
typedef struct Analyzer_OutputData_ {
float* output; // externally provided buffe
int oLength; // externally provided buffer length
} Analyzer_OutputData;
#ifdef __cplusplus
extern "C" {
#endif
/****************************************************************************
* AUP_Analyzer_create(...)
*
* This function creats a state handler from nothing, which is NOT ready for
* processing
*
* Input:
*
* Output:
* - stPtr : buffer to store the returned state handler
*
* Return value : 0 - Ok
* -1 - Error
*/
int AUP_Analyzer_create(void** stPtr);
/****************************************************************************
* AUP_Analyzer_destroy(...)
*
* destroy PE instance, and releasing all the dynamically allocated memory
*
* Input:
* - stPtr : buffer of State Handler, after this method, this
* handler won't be usable anymore
*
* Output:
*
* Return value : 0 - Ok
* -1 - Error
*/
int AUP_Analyzer_destroy(void** stPtr);
/****************************************************************************
* AUP_Analyzer_memAllocate(...)
*
* This function sets Static Config params and does memory allocation
* operation, will lose the dynamCfg values
*
* Input:
* - stPtr : State Handler which was returned by _create
* - pCfg : static configuration parameters
*
* Output:
*
* Return value : 0 - Ok
* -1 - Error
*/
int AUP_Analyzer_memAllocate(void* stPtr, const Analyzer_StaticCfg* pCfg);
/****************************************************************************
* AUP_Analyzer_init(...)
*
* This function resets (initialize) the PE module and gets it prepared for
* processing
*
* Input:
* - stPtr : State Handler which has gone through create and
* memAllocate
*
* Output:
*
* Return value : 0 - Ok
* -1 - Error
*/
int AUP_Analyzer_init(void* stPtr);
/****************************************************************************
* AUP_Analyzer_getStaticCfg(...)
*
* This function get static configuration status from PE module
*
* Input:
* - stPtr : State Handler which has gone through create and
* memAllocate
*
* Output:
* - pCfg : configuration content
*
* Return value : 0 - Ok
* -1 - Error
*/
int AUP_Analyzer_getStaticCfg(const void* stPtr, Analyzer_StaticCfg* pCfg);
/****************************************************************************
* AUP_Analyzer_proc(...)
*
* process a single frame
*
* Input:
* - stPtr : State Handler which has gone through create and
* memAllocate and reset
* - pCtrl : per-frame variable control parameters
* - pIn : input data stream
*
* Output:
* - pOut : output data (mask, highband time-domain gain etc.)
*
* Return value : 0 - Ok
* -1 - Error
*/
int AUP_Analyzer_proc(void* stPtr, const Analyzer_InputData* pIn,
Analyzer_OutputData* pOut);
#ifdef __cplusplus
}
#endif
#endif // __STFT_H__

View file

@ -1,42 +0,0 @@
//
// Copyright © 2025 Agora
// This file is part of TEN Framework, an open source project.
// Licensed under the Apache License, Version 2.0, with certain conditions.
// Refer to the "LICENSE" file in the root directory for more information.
//
#ifndef __STFT_ST_H__
#define __STFT_ST_H__
#include <stdio.h>
#include "stft.h"
#define AUP_STFT_ALIGN8(o) (((o) + 7) & (~7))
#define AUP_STFT_MAX(x, y) (((x) > (y)) ? (x) : (y))
#define AUP_STFT_MIN(x, y) (((x) > (y)) ? (y) : (x))
typedef struct Analyzer_St_ {
void* dynamMemPtr; // memory pointer holding the dynamic memory
size_t dynamMemSize; // size of the buffer *dynamMemPtr
// ---------------------------------------------------------------
// Static Configuration
Analyzer_StaticCfg stCfg;
// ---------------------------------------------------------------
// Internal Static Config Registers, which are generated from stCfg
int nBins;
float windowCoffCopy[AUP_STFT_MAX_FFTSZ];
// ---------------------------------------------------------------
// Dynamic Configuration
// ---------------------------------------------------------------
// Internal Dynamic Config Registers, which are generated from dynamCfg
// ---------------------------------------------------------------
// Variables
float* inputQ; // [stCfg->win_len + 4]
float* fftInputBuf; // [stCfg->fft_size + 4]
} Analyzer_St;
#endif // __STFT_ST_H__

View file

@ -1,69 +0,0 @@
//
// Copyright © 2025 Agora
// This file is part of TEN Framework, an open source project.
// Licensed under the Apache License, Version 2.0, with certain conditions.
// Refer to the "LICENSE" file in the root directory for more information.
//
#include <cassert>
#include "ten_vad.h"
#include "aed_st.h"
#include "aed.h"
static void int16_to_float(const int16_t* inputs, int inputLen, float* output) {
for (int i = 0; i < inputLen; ++i) {
output[i] = float(inputs[i]);
}
}
int ten_vad_create(ten_vad_handle_t* handle, size_t hop_size, float threshold) {
if (AUP_Aed_create(handle) < 0) {
return -1;
}
Aed_St* stHdl = nullptr;
Aed_StaticCfg aedStCfg;
aedStCfg.enableFlag = 1;
aedStCfg.fftSz = 0;
aedStCfg.hopSz = hop_size;
aedStCfg.anaWindowSz = 0;
aedStCfg.frqInputAvailableFlag = 0;
stHdl = (Aed_St*)(*handle);
stHdl->dynamCfg.extVoiceThr = threshold;
if (AUP_Aed_memAllocate(*handle, &aedStCfg) < 0) {
return -1;
}
if (AUP_Aed_init(*handle) < 0) {
return -1;
}
return 0;
}
int ten_vad_process(ten_vad_handle_t handle, const int16_t* audio_data,
size_t audio_data_length, float* out_probability,
int* out_flag) {
if (handle == nullptr || audio_data == nullptr ||
out_probability == nullptr || out_flag == nullptr) {
return -1;
}
Aed_St* ptr = (Aed_St*)handle;
assert(audio_data_length == ptr->stCfg.hopSz);
int16_to_float(audio_data, audio_data_length, ptr->inputFloatBuff);
Aed_InputData aedInputData;
Aed_OutputData aedOutputData;
aedInputData.binPower = NULL;
aedInputData.hopSz = ptr->stCfg.hopSz;
aedInputData.nBins = -1;
aedInputData.timeSignal = ptr->inputFloatBuff;
int ret = AUP_Aed_proc(handle, &aedInputData, &aedOutputData);
if (ret == 0) {
*out_probability = aedOutputData.voiceProb;
*out_flag = aedOutputData.vadRes;
}
return ret;
}
int ten_vad_destroy(ten_vad_handle_t* handle) {
return AUP_Aed_destroy(handle);
}
const char* ten_vad_get_version(void) { return "1.0"; }

Some files were not shown because too many files have changed in this diff Show more