Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

9.2 KB
Raw Blame
"""Real capture/sender threads and public start/stop/metadata calls, offline.

The audio is generated bytes in host RAM, never a microphone or network stream.
SANITIZERS=thread also checks cross-task ownership with ThreadSanitizer.
"""
from pathlib import Path
import os
import re
import subprocess
import tempfile
from native_shapes import defines

main=Path(__file__).resolve().parent/'../main'
source=re.sub(r'^#include .*\n','',(main/'audio_client_habitat.c').read_text(),flags=re.M)
code=defines('ID_MAX')+r'''
#include "audio_client.h"
#include "voice_buffer.h"
#include <assert.h>
#include <pthread.h>
#include <sched.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#define CFG_VLANG_MAX 16
#define AUDIO_SAMPLE_RATE 16000
#define CABLE_VOICE_CHUNK 1024
#define pdTRUE 1
#define pdPASS 1
#define portMAX_DELAY (-1)
#define pdMS_TO_TICKS(ms) (ms)
#define portMUX_TYPE pthread_mutex_t
#define portMUX_INITIALIZER_UNLOCKED PTHREAD_MUTEX_INITIALIZER
#define portENTER_CRITICAL(p) assert(!pthread_mutex_lock(p))
#define portEXIT_CRITICAL(p) assert(!pthread_mutex_unlock(p))
typedef int BaseType_t;
typedef struct task {
    pthread_t thread;
    pthread_mutex_t lock;
    pthread_cond_t wake;
    unsigned pending;
    bool quit;
    void (*function)(void *);
} task_t;
typedef task_t *TaskHandle_t;
static _Thread_local task_t *self;
static void log_noop(const char *tag,const char *fmt,...) { (void)tag;(void)fmt; }
#define ESP_LOGI(...) log_noop(__VA_ARGS__)
#define ESP_LOGE(...) log_noop(__VA_ARGS__)
static int64_t esp_timer_get_time(void) {
    struct timespec t;assert(!clock_gettime(CLOCK_MONOTONIC,&t));
    return (int64_t)t.tv_sec*1000000+t.tv_nsec/1000;
}
static uint32_t esp_random(void) { static atomic_uint counter;return atomic_fetch_add(&counter,1)+1; }
static void vTaskDelay(unsigned ms) {
    (void)ms;struct timespec t={0,10000};nanosleep(&t,NULL);
}
static int ulTaskNotifyTake(int clear,int ticks) {
    assert(self&&clear==pdTRUE);assert(!pthread_mutex_lock(&self->lock));
    while(!self->pending&&!self->quit) {
        if(ticks==portMAX_DELAY) assert(!pthread_cond_wait(&self->wake,&self->lock));
        else {
            struct timespec until;clock_gettime(CLOCK_REALTIME,&until);
            until.tv_nsec+=1000000;if(until.tv_nsec>=1000000000){until.tv_nsec-=1000000000;until.tv_sec++;}
            int result=pthread_cond_timedwait(&self->wake,&self->lock,&until);
            assert(!result||result==ETIMEDOUT);if(result==ETIMEDOUT)break;
        }
    }
    unsigned value=self->pending;self->pending=0;bool quit=self->quit;
    assert(!pthread_mutex_unlock(&self->lock));if(quit)pthread_exit(NULL);return (int)value;
}
static void xTaskNotifyGive(TaskHandle_t task) {
    assert(task);assert(!pthread_mutex_lock(&task->lock));task->pending++;
    assert(!pthread_cond_signal(&task->wake));assert(!pthread_mutex_unlock(&task->lock));
}
static unsigned uxTaskGetStackHighWaterMark(TaskHandle_t task) {(void)task;return 4096;}
static void *run_task(void *arg) { self=arg;self->function(NULL);return NULL; }
static BaseType_t xTaskCreatePinnedToCore(void (*f)(void *),const char *name,unsigned stack,void *arg,
                                         unsigned priority,TaskHandle_t *out,int core) {
    (void)name;(void)stack;(void)arg;(void)priority;(void)core;
    task_t *task=calloc(1,sizeof *task);assert(task);
    assert(!pthread_mutex_init(&task->lock,NULL));assert(!pthread_cond_init(&task->wake,NULL));
    task->function=f;*out=task;assert(!pthread_create(&task->thread,NULL,run_task,task));return pdPASS;
}
static void vTaskDelete(TaskHandle_t task) {
    pthread_mutex_lock(&task->lock);task->quit=true;pthread_cond_signal(&task->wake);pthread_mutex_unlock(&task->lock);
    assert(!pthread_join(task->thread,NULL));pthread_cond_destroy(&task->wake);pthread_mutex_destroy(&task->lock);free(task);
}
static void *ram_psram_alloc(size_t bytes,const char *owner) {(void)owner;return calloc(1,bytes);}
static void config_load_voicelang(char *out,size_t n) {snprintf(out,n,"en");}
enum { HEALTHY, BEGIN_FAIL, START_FAIL, READ_FAIL, READ_RECOVER, TX_FAIL, OVERFLOW, DMA_LOSS,
       EXPLICIT_STOP, EXPLICIT_ABORT, MODES };
static unsigned mode,session_number,raw_bytes,reads,sent_bytes,pcm_calls,starts,stops,begins,ends,aborts;
static atomic_uint overruns;
static atomic_bool start_gate,first_read;
static char expected_agent[ID_MAX];
static bool audio_capture_start(void);
static int audio_capture_read(uint8_t *,int);
static void audio_capture_stop(void);
static unsigned audio_capture_overruns(void) {return atomic_load(&overruns);}
static bool audio_stream_begin(const char *,const char *,const char *,int);
static bool audio_stream_pcm(const uint8_t *,size_t);
static void audio_stream_end(void);
static void audio_stream_abort(const char *);
'''
code+=source
code+=r'''
static uint8_t value(unsigned at) {return (uint8_t)((at*29u)^(session_number*17u));}
static bool audio_capture_start(void) {
    starts++;while(!atomic_load(&start_gate))sched_yield();return mode!=START_FAIL;
}
static int audio_capture_read(uint8_t *out,int capacity) {
    assert(capacity==CAPTURE_SAMPLES*2);reads++;
    if(mode==READ_FAIL||(mode==READ_RECOVER&&reads<=2))return -1;
    // Pace synthetic hardware behind the sender except in the dedicated overflow
    // case. This keeps scheduler load from impersonating a broken USB link.
    while(mode!=OVERFLOW&&voice_buffer_used(&buffer)>BUFFER_BYTES-(unsigned)capacity) {
        if(atomic_load(&stop_requested)||atomic_load(&abort_requested))return 0;
        sched_yield();
    }
    for(int i=0;i<capacity;i++)out[i]=value(raw_bytes+(unsigned)i);
    raw_bytes+=(unsigned)capacity;atomic_store(&first_read,true);
    if(mode==DMA_LOSS&&reads==3)atomic_store(&overruns,1);
    if(mode!=OVERFLOW&&mode!=EXPLICIT_STOP&&mode!=EXPLICIT_ABORT&&raw_bytes==64*CAPTURE_SAMPLES*2)
        atomic_store(&stop_requested,true);
    sched_yield();return capacity;
}
static void audio_capture_stop(void) {stops++;}
static bool audio_stream_begin(const char *id,const char *cmd,const char *lang,int rate) {
    assert(id&&!strcmp(id,expected_agent)&&!strcmp(cmd,"")&&!strcmp(lang,"en")&&rate==16000);begins++;
    if(mode==OVERFLOW)while(!atomic_load(&abort_requested))sched_yield();
    return mode!=BEGIN_FAIL;
}
static bool audio_stream_pcm(const uint8_t *bytes,size_t n) {
    assert(begins==1&&n&&n<=CABLE_VOICE_CHUNK);pcm_calls++;
    for(size_t i=0;i<n;i++)assert(bytes[i]==value(sent_bytes+(unsigned)i));
    if(mode==TX_FAIL&&pcm_calls==3)return false;
    sent_bytes+=(unsigned)n;sched_yield();return true;
}
static void audio_stream_end(void) {
    assert(atomic_load(&capture_done)&&!atomic_load(&abort_requested)&&sent_bytes==produced);ends++;
}
static void audio_stream_abort(const char *why) {assert(why&&atomic_load(&capture_done));aborts++;}
static void wait_finished(void) {
    int64_t limit=esp_timer_get_time()+5000000;
    while(audio_client_active()) {assert(esp_timer_get_time()<limit);sched_yield();}
}
int main(void) {
    audio_client_init();assert(storage&&capture_task&&sender_task);
    audio_client_init(); // Idempotent; no extra workers or ring.
    for(unsigned round=0;round<100;round++)for(mode=0;mode<MODES;mode++) {
        assert(!audio_client_active());session_number++;
        raw_bytes=reads=sent_bytes=pcm_calls=starts=stops=begins=ends=aborts=0;
        atomic_store(&overruns,0);atomic_store(&start_gate,false);atomic_store(&first_read,false);
        snprintf(expected_agent,sizeof expected_agent,"offline-agent-%u",session_number);
        audio_client_start_cable(expected_agent,VOICE_CMD_NONE);assert(audio_client_active());
        // A second start while recording cannot redirect this utterance.
        audio_client_start_cable("wrong-agent",VOICE_CMD_GOAL);
        char current[24];audio_client_copy_upload_id(current,sizeof current);
        assert(audio_client_upload_matches(current)&&!audio_client_upload_matches("old-upload"));
        assert(audio_client_recording());
        atomic_store(&start_gate,true);
        if(mode==EXPLICIT_STOP||mode==EXPLICIT_ABORT) {
            while(!atomic_load(&first_read))sched_yield();
            if(mode==EXPLICIT_STOP)audio_client_stop();else audio_client_abort();
        }
        wait_finished();
        assert(!audio_client_recording()&&atomic_load(&capture_done)&&audio_client_input_level()==0);
        assert(begins==1&&starts==1&&stops==(unsigned)(mode!=START_FAIL));
        assert(high_water<=BUFFER_BYTES);
        if(mode==HEALTHY||mode==READ_RECOVER||mode==EXPLICIT_STOP) {
            assert(ends==1&&!aborts&&sent_bytes==produced&&!voice_buffer_used(&buffer));
        } else assert(!ends&&aborts==1);
    }
    vTaskDelete(capture_task);vTaskDelete(sender_task);free(storage);
    puts("Audio threads: 1000 concurrent offline sessions; exact PCM, pinned targets, explicit stop/abort, start/read/USB/overflow failures and immediate restart PASS");
}
'''
with tempfile.TemporaryDirectory(prefix='harness-audio-threads-') as d:
    out=Path(d);(out/'threads.c').write_text(code)
    subprocess.run(['cc','-std=c11','-Wall','-Wextra','-Werror','-O1','-g','-pthread',
        '-fsanitize='+os.environ.get('SANITIZERS','undefined,bounds'),'-I',str(main),
        str(out/'threads.c'),str(main/'voice_buffer.c'),'-o',str(out/'threads')],check=True)
    subprocess.run([str(out/'threads')],check=True,timeout=120)