aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


client/runtime/linux_audio.c (42287B)


      1 #include "browser_profile.h"
      2 #include "linux_path.h"
      3 #include "linux_audio.h"
      4 #include "guest_heap.h"
      5 #include <SDL2/SDL.h>
      6 #include <pthread.h>
      7 #include <strings.h>
      8 #include <sndfile.h>
      9 #include <limits.h>
     10 #include <math.h>
     11 #include <stdatomic.h>
     12 
     13 #ifdef __EMSCRIPTEN__
     14 #include "browser_audio.h"
     15 #else
     16 #define audio_output_close SDL_CloseAudioDevice
     17 #define audio_output_lock SDL_LockAudioDevice
     18 #define audio_output_unlock SDL_UnlockAudioDevice
     19 #define audio_output_pause SDL_PauseAudioDevice
     20 #endif
     21 
     22 static pthread_once_t audio_once = PTHREAD_ONCE_INIT;
     23 static int audio_available;
     24 static pthread_mutex_t audio_mutex = PTHREAD_MUTEX_INITIALIZER;
     25 static int miles_started, sample_capacity = 64;
     26 static uint32_t redist_directory, next_driver = 0xf6000000;
     27 static uint32_t next_stream = 0xf6800000;
     28 static uint32_t next_sample = 0xf7000000;
     29 /* Immutable decoded assets outlive both queued work and individual voices. */
     30 struct audio_asset {
     31     uint32_t handle, frames;
     32     unsigned references;
     33     int channels;
     34     _Atomic int state;
     35     char *filename;
     36     float *samples;
     37     struct audio_asset *next, *queued;
     38 };
     39 static struct audio_asset *assets, *load_head, *load_tail;
     40 static uint32_t next_asset = 0xf7800000;
     41 static pthread_cond_t load_condition = PTHREAD_COND_INITIALIZER;
     42 static pthread_once_t loader_once = PTHREAD_ONCE_INIT;
     43 
     44 struct audio_sample {
     45     uint32_t handle, frames;
     46     int status, volume, rate, channels, loops;
     47     double position;
     48     float *samples;
     49     struct audio_asset *asset;
     50     struct audio_sample *next;
     51 };
     52 struct audio_stream {
     53     uint32_t handle, frames, position;
     54     uint32_t seek_position;
     55     int seek_pending;
     56     int status, volume;
     57     float *samples;
     58     struct audio_stream *next;
     59 };
     60 static struct audio_driver {
     61     struct audio_driver *next;
     62     uint32_t handle;
     63     SDL_AudioDeviceID device;
     64     int sample_capacity, volume, latency, closing, music_muted;
     65     uint32_t music_generation;
     66     unsigned references;
     67     SDL_AudioSpec format;
     68     struct audio_stream *streams;
     69     struct audio_sample *samples;
     70 } *drivers;
     71 
     72 /* Callers hold audio_mutex; the worker owns a reference until publication. */
     73 static void release_asset_locked(struct audio_asset *asset)
     74 {
     75     if (--asset->references) return;
     76     struct audio_asset **link = &assets;
     77     while (*link != asset) link = &(*link)->next;
     78     *link = asset->next;
     79     free(asset->samples);
     80     free(asset->filename);
     81     free(asset);
     82 }
     83 
     84 static void *load_audio(void *unused)
     85 {
     86     for (;;) {
     87         if (pthread_mutex_lock(&audio_mutex)) abort();
     88         while (!load_head)
     89             if (pthread_cond_wait(&load_condition, &audio_mutex)) abort();
     90         struct audio_asset *asset = load_head;
     91         load_head = asset->queued;
     92         if (!load_head) load_tail = NULL;
     93         int canceled = asset->references == 1;
     94         if (pthread_mutex_unlock(&audio_mutex)) abort();
     95 
     96         /* File access, decoding and resampling never hold a playback lock. */
     97         int state = -1;
     98         if (!canceled) {
     99             double profile_start = ao_profile_begin("sound load/decode");
    100             char *path = linux_path(asset->filename);
    101             SF_INFO info = {0};
    102             SNDFILE *file = sf_open(path, SFM_READ, &info);
    103             if (file) {
    104                 if (info.frames < 0 || info.channels < 1 || info.channels > 2 ||
    105                     info.frames > INT_MAX / (int)sizeof(float) / info.channels) abort();
    106                 float *decoded = malloc(info.frames ? info.frames * info.channels * sizeof(float) : 1);
    107                 if (!decoded) abort();
    108                 sf_count_t frames = sf_readf_float(file, decoded, info.frames);
    109                 int error = sf_error(file);
    110                 if (sf_close(file)) abort();
    111                 if (frames > 0 && !error) {
    112                     /* A fixed base rate lets pitch changes work before decoding completes. */
    113                     if (info.samplerate == 44100) {
    114                         asset->samples = decoded;
    115                         asset->frames = frames;
    116                         decoded = NULL;
    117                     } else {
    118                         SDL_AudioStream *conversion = SDL_NewAudioStream(AUDIO_F32SYS, info.channels, info.samplerate,
    119                             AUDIO_F32SYS, info.channels, 44100);
    120                         if (!conversion || SDL_AudioStreamPut(conversion, decoded, frames * info.channels * sizeof(float)) ||
    121                             SDL_AudioStreamFlush(conversion)) abort();
    122                         int size = SDL_AudioStreamAvailable(conversion);
    123                         if (size < 0 || size % (sizeof(float) * info.channels)) abort();
    124                         asset->samples = malloc(size ? size : 1);
    125                         if (!asset->samples || SDL_AudioStreamGet(conversion, asset->samples, size) != size) abort();
    126                         SDL_FreeAudioStream(conversion);
    127                         asset->frames = size / sizeof(float) / info.channels;
    128                     }
    129                     asset->channels = info.channels;
    130                     state = asset->frames ? 1 : -1;
    131                 }
    132                 free(decoded);
    133             } else fprintf(stderr, "[linux-audio] sound %s: %s\n", path, sf_strerror(NULL));
    134             ao_profile_end("sound load/decode", profile_start, asset->filename);
    135             free(path);
    136         }
    137 
    138         atomic_store_explicit(&asset->state, state, memory_order_release);
    139         if (pthread_mutex_lock(&audio_mutex)) abort();
    140         release_asset_locked(asset);
    141         if (pthread_mutex_unlock(&audio_mutex)) abort();
    142     }
    143     return NULL;
    144 }
    145 
    146 static void start_audio_loader(void)
    147 {
    148     pthread_t thread;
    149     if (pthread_create(&thread, NULL, load_audio, NULL) || pthread_detach(thread)) abort();
    150 }
    151 
    152 /* mmr.dll sub_3A008430: return the ordinary 20-byte sound object immediately.
    153    Its data and allocation slots carry a host asset handle, never a partial RIFF. */
    154 void linux_audio_load_sound(void)
    155 {
    156     uint32_t output = MEM32(g_esp + 4), filename = MEM32(g_esp + 8);
    157     unsigned priority = MEM8(g_esp + 12);
    158     MEM32(output) = 0;
    159     g_esp += 16;
    160     if (!MEM8(g_ecx + 0x10) || !MEM32(g_ecx + 0xc)) return;
    161     uint32_t sound = guest_malloc(20);
    162     if (!sound) abort();
    163     struct audio_asset *asset = calloc(1, sizeof(*asset));
    164     if (!asset) abort();
    165     asset->filename = strdup((const char *)ADDR(filename));
    166     if (!asset->filename) abort();
    167     atomic_init(&asset->state, 0);
    168     if (pthread_once(&loader_once, start_audio_loader)) abort();
    169     if (pthread_mutex_lock(&audio_mutex)) abort();
    170     if (next_asset >= 0xf8000000u) abort();
    171     asset->handle = next_asset++;
    172     asset->references = 2;
    173     asset->next = assets;
    174     assets = asset;
    175     if (load_tail) load_tail->queued = asset;
    176     else load_head = asset;
    177     load_tail = asset;
    178     if (pthread_cond_signal(&load_condition)) abort();
    179     if (pthread_mutex_unlock(&audio_mutex)) abort();
    180     MEM32(sound) = 0;
    181     MEM32(sound + 4) = MEM32(sound + 8) = asset->handle;
    182     MEM32(sound + 12) = priority;
    183     MEM32(sound + 16) = 44100;
    184     MEM32(output) = sound;
    185 }
    186 
    187 /* The device lock protects voice state; publication does not touch voices. */
    188 static void adopt_sample_locked(struct audio_sample *sample)
    189 {
    190     if (!sample->asset || sample->samples) return;
    191     int state = atomic_load_explicit(&sample->asset->state, memory_order_acquire);
    192     if (state < 0) { if (sample->status == 4) sample->status = 2; }
    193     else if (state > 0) {
    194         sample->samples = sample->asset->samples;
    195         sample->frames = sample->asset->frames;
    196         sample->channels = sample->asset->channels;
    197     }
    198 }
    199 
    200 /* The output worker holds its device lock; this callback never enters guest code. */
    201 static void render_audio(void *userdata, Uint8 *output, int length)
    202 {
    203     struct audio_driver *driver = userdata;
    204     int bytes = SDL_AUDIO_BITSIZE(driver->format.format) / 8;
    205     int frames = length / (bytes * driver->format.channels);
    206     for (struct audio_sample *voice = driver->samples; voice; voice = voice->next)
    207         adopt_sample_locked(voice);
    208     for (int frame = 0; frame < frames; ++frame) {
    209         for (int channel = 0; channel < driver->format.channels; ++channel) {
    210             float sample = 0;
    211             for (struct audio_stream *stream = driver->streams; stream; stream = stream->next)
    212                 if (stream->status == 4 && !driver->music_muted && !driver->closing)
    213                     sample += stream->samples[stream->position * driver->format.channels + channel] *
    214                               (stream->volume / 127.0f) * (driver->volume / 127.0f);
    215             for (struct audio_sample *voice = driver->samples; voice; voice = voice->next) {
    216                 if (voice->status != 4 || !voice->frames || driver->closing) continue;
    217                 unsigned index = voice->position;
    218                 unsigned next = index + 1 < voice->frames ? index + 1 : index;
    219                 float fraction = voice->position - index;
    220                 float value = 0;
    221                 for (int source = 0; source < voice->channels; ++source) {
    222                     if (driver->format.channels == 2 && voice->channels == 2 && source != channel) continue;
    223                     float first = voice->samples[index * voice->channels + source];
    224                     value += first + (voice->samples[next * voice->channels + source] - first) * fraction;
    225                 }
    226                 if (driver->format.channels == 1 && voice->channels == 2) value *= 0.5f;
    227                 sample += value * (voice->volume / 127.0f) * (driver->volume / 127.0f);
    228             }
    229             if (sample < -1) sample = -1;
    230             if (sample > 1) sample = 1;
    231             int index = frame * driver->format.channels + channel;
    232             if (bytes == 2) {
    233                 int value = lrintf(sample * 32768);
    234                 if (value > 32767) value = 32767;
    235                 output[index * 2] = value;
    236                 output[index * 2 + 1] = (unsigned)value >> 8;
    237             } else {
    238                 int value = lrintf(sample * 128) + 128;
    239                 output[index] = value > 255 ? 255 : value;
    240             }
    241         }
    242         for (struct audio_stream *stream = driver->streams; stream; stream = stream->next)
    243             if (stream->status == 4 && ++stream->position == stream->frames) stream->status = 2;
    244         for (struct audio_sample *voice = driver->samples; voice; voice = voice->next) {
    245             if (voice->status != 4 || !voice->frames || driver->closing) continue;
    246             voice->position += (double)voice->rate / driver->format.freq;
    247             while (voice->position >= voice->frames) {
    248                 if (voice->loops == 1) { voice->status = 2; voice->position = voice->frames; break; }
    249                 if (voice->loops > 1) --voice->loops;
    250                 voice->position -= voice->frames;
    251             }
    252         }
    253     }
    254 }
    255 
    256 static void destroy_driver(struct audio_driver *driver)
    257 {
    258     /* Joining the output worker must not hold a lock used by the game loop. */
    259     audio_output_close(driver->device);
    260     if (pthread_mutex_lock(&audio_mutex)) abort();
    261     while (driver->streams) {
    262         struct audio_stream *stream = driver->streams;
    263         driver->streams = stream->next;
    264         free(stream->samples);
    265         free(stream);
    266     }
    267     while (driver->samples) {
    268         struct audio_sample *sample = driver->samples;
    269         driver->samples = sample->next;
    270         if (sample->asset) release_asset_locked(sample->asset);
    271         else free(sample->samples);
    272         free(sample);
    273     }
    274     free(driver);
    275     if (pthread_mutex_unlock(&audio_mutex)) abort();
    276 }
    277 
    278 static void initialize_audio(void)
    279 {
    280     audio_available = SDL_InitSubSystem(SDL_INIT_AUDIO) == 0;
    281     if (!audio_available) fprintf(stderr, "[linux-audio] %s\n", SDL_GetError());
    282 }
    283 
    284 static void wave_out_get_num_devs(void)
    285 {
    286     if (pthread_once(&audio_once, initialize_audio)) abort();
    287     int count = audio_available ? SDL_GetNumAudioDevices(0) : 0;
    288     if (count < 0) {
    289         fprintf(stderr, "[linux-audio] enumerate: %s\n", SDL_GetError());
    290         count = 0;
    291     }
    292     g_eax = count;
    293     g_esp += 4;
    294 }
    295 
    296 static void set_redist_directory(void)
    297 {
    298     uint32_t path = MEM32(g_esp + 4);
    299     const char *text = path ? (const char *)ADDR(path) : "";
    300     size_t length = strlen(text);
    301     if (length > 258) abort();
    302     if (pthread_mutex_lock(&audio_mutex)) abort();
    303     if (!redist_directory) redist_directory = guest_malloc(260);
    304     if (!redist_directory) abort();
    305     char *destination = (char *)ADDR(redist_directory);
    306     memmove(destination, text, length + 1);
    307     if (length && destination[length - 1] != '\\' && destination[length - 1] != ':') {
    308         destination[length] = '\\';
    309         destination[length + 1] = 0;
    310     }
    311     g_eax = redist_directory;
    312     if (pthread_mutex_unlock(&audio_mutex)) abort();
    313     g_esp += 8;
    314 }
    315 
    316 static void miles_startup(void)
    317 {
    318     if (pthread_once(&audio_once, initialize_audio)) abort();
    319     if (pthread_mutex_lock(&audio_mutex)) abort();
    320     g_eax = !miles_started;
    321     if (!miles_started) sample_capacity = 64;
    322     miles_started = 1;
    323     if (pthread_mutex_unlock(&audio_mutex)) abort();
    324     g_esp += 4;
    325 }
    326 
    327 static void set_preference(void)
    328 {
    329     uint32_t preference = MEM32(g_esp + 4);
    330     if (preference != 1) {
    331         fprintf(stderr, "Unsupported Miles preference %u\n", preference);
    332         abort();
    333     }
    334     if (pthread_mutex_lock(&audio_mutex)) abort();
    335     g_eax = sample_capacity;
    336     sample_capacity = (int32_t)MEM32(g_esp + 8);
    337     if (pthread_mutex_unlock(&audio_mutex)) abort();
    338     g_esp += 12;
    339 }
    340 
    341 static void wave_out_open(void)
    342 {
    343     uint32_t output = MEM32(g_esp + 4), wave = MEM32(g_esp + 8);
    344     uint32_t index = MEM32(g_esp + 12), format = MEM32(g_esp + 16);
    345     if (wave || !format) {
    346         fprintf(stderr, "Unsupported Miles waveOut handle/default-format request\n");
    347         abort();
    348     }
    349     unsigned channels = MEM16(format + 2), bits = MEM16(format + 14);
    350     g_eax = 1; /* MMSYSERR_ERROR: Miles rejects non-PCM/unsupported PCM formats. */
    351     if (MEM16(format) != 1 || channels < 1 || channels > 2 || (bits != 8 && bits != 16)) {
    352         g_esp += 20;
    353         return;
    354     }
    355     if (pthread_once(&audio_once, initialize_audio)) abort();
    356     if (pthread_mutex_lock(&audio_mutex)) abort();
    357     if (!audio_available) g_eax = 6; /* MMSYSERR_NODRIVER */
    358     else if (index != UINT32_MAX && index >= (unsigned)SDL_GetNumAudioDevices(0)) g_eax = 2;
    359     else {
    360         struct audio_driver *driver = calloc(1, sizeof(*driver));
    361         if (!driver) abort();
    362         SDL_AudioSpec desired = {0};
    363         desired.freq = MEM32(format + 4);
    364         desired.channels = channels;
    365         desired.format = bits == 16 ? AUDIO_S16LSB : AUDIO_U8;
    366         desired.samples = 512;
    367         desired.callback = render_audio;
    368         desired.userdata = driver;
    369 #ifdef __EMSCRIPTEN__
    370         SDL_AudioDeviceID device = audio_output_open(&desired, &driver->format);
    371 #else
    372         SDL_AudioDeviceID device = SDL_OpenAudioDevice(index == UINT32_MAX ? NULL :
    373             SDL_GetAudioDeviceName(index, 0), 0, &desired, &driver->format, 0);
    374 #endif
    375         if (device) {
    376             driver->handle = next_driver++;
    377             driver->references = 1;
    378             driver->device = device;
    379             driver->sample_capacity = sample_capacity;
    380             driver->volume = 127;
    381             driver->latency = (unsigned)driver->format.samples * 1000 / driver->format.freq;
    382             driver->next = drivers;
    383             drivers = driver;
    384             MEM32(output) = driver->handle;
    385             g_eax = 0;
    386             fprintf(stderr, "[linux-audio] %s: %d Hz, %u channels, %u bits\n",
    387 #ifdef __EMSCRIPTEN__
    388                     "Web Audio",
    389 #else
    390                     SDL_GetCurrentAudioDriver(),
    391 #endif
    392                     desired.freq, channels, bits);
    393         } else {
    394             fprintf(stderr, "[linux-audio] open: %s\n", SDL_GetError());
    395             free(driver);
    396         }
    397     }
    398     if (pthread_mutex_unlock(&audio_mutex)) abort();
    399     g_esp += 20;
    400 }
    401 
    402 /* A queued music command and the music owner each retain their driver. */
    403 void linux_audio_retain_driver(uint32_t handle)
    404 {
    405     if (pthread_mutex_lock(&audio_mutex)) abort();
    406     struct audio_driver *driver = drivers;
    407     while (driver && driver->handle != handle) driver = driver->next;
    408     if (!driver) abort();
    409     ++driver->references;
    410     if (pthread_mutex_unlock(&audio_mutex)) abort();
    411 }
    412 
    413 static struct audio_driver *release_driver_locked(struct audio_driver **link)
    414 {
    415     struct audio_driver *driver = *link;
    416     if (--driver->references) return NULL;
    417     *link = driver->next;
    418     return driver;
    419 }
    420 
    421 void linux_audio_release_driver(uint32_t handle)
    422 {
    423     if (pthread_mutex_lock(&audio_mutex)) abort();
    424     struct audio_driver **link = &drivers;
    425     while (*link && (*link)->handle != handle) link = &(*link)->next;
    426     if (!*link) abort();
    427     struct audio_driver *closed = release_driver_locked(link);
    428     if (pthread_mutex_unlock(&audio_mutex)) abort();
    429     if (closed) destroy_driver(closed);
    430 }
    431 
    432 uint32_t linux_audio_mute_music(uint32_t handle, int muted)
    433 {
    434     if (pthread_mutex_lock(&audio_mutex)) abort();
    435     struct audio_driver *driver = drivers;
    436     while (driver && driver->handle != handle) driver = driver->next;
    437     if (!driver) abort();
    438     audio_output_lock(driver->device);
    439     /* Unmute alone must not revive a play submitted before the last mute. */
    440     if (muted) {
    441         driver->music_muted = 1;
    442         ++driver->music_generation;
    443     }
    444     uint32_t generation = driver->music_generation;
    445     audio_output_unlock(driver->device);
    446     if (pthread_mutex_unlock(&audio_mutex)) abort();
    447     return generation;
    448 }
    449 
    450 void linux_audio_enable_music(uint32_t handle, uint32_t generation)
    451 {
    452     if (pthread_mutex_lock(&audio_mutex)) abort();
    453     struct audio_driver *driver = drivers;
    454     while (driver && driver->handle != handle) driver = driver->next;
    455     if (!driver) abort();
    456     audio_output_lock(driver->device);
    457     if (generation == driver->music_generation) driver->music_muted = 0;
    458     audio_output_unlock(driver->device);
    459     if (pthread_mutex_unlock(&audio_mutex)) abort();
    460 }
    461 
    462 static void wave_out_close(void)
    463 {
    464     uint32_t handle = MEM32(g_esp + 4);
    465     if (pthread_mutex_lock(&audio_mutex)) abort();
    466     struct audio_driver **link = &drivers;
    467     while (*link && (*link)->handle != handle) link = &(*link)->next;
    468     if (!*link || (*link)->closing) abort();
    469     audio_output_lock((*link)->device);
    470     (*link)->closing = 1;
    471     audio_output_unlock((*link)->device);
    472     struct audio_driver *closed = release_driver_locked(link);
    473     if (pthread_mutex_unlock(&audio_mutex)) abort();
    474     if (closed) destroy_driver(closed);
    475     g_esp += 8;
    476 }
    477 
    478 static void set_digital_master_volume(void)
    479 {
    480     uint32_t handle = MEM32(g_esp + 4);
    481     if (pthread_mutex_lock(&audio_mutex)) abort();
    482     struct audio_driver *driver = drivers;
    483     while (driver && driver->handle != handle) driver = driver->next;
    484     if (!driver) abort();
    485     audio_output_lock(driver->device);
    486     driver->volume = (int32_t)MEM32(g_esp + 8);
    487     audio_output_unlock(driver->device);
    488     if (pthread_mutex_unlock(&audio_mutex)) abort();
    489     g_esp += 12;
    490 }
    491 
    492 static void miles_shutdown(void)
    493 {
    494     if (pthread_mutex_lock(&audio_mutex)) abort();
    495     struct audio_driver *closed = NULL, **link = &drivers;
    496     while (*link) {
    497         struct audio_driver *driver = *link;
    498         if (!driver->closing) {
    499             audio_output_lock(driver->device);
    500             driver->closing = 1;
    501             audio_output_unlock(driver->device);
    502             struct audio_driver *released = release_driver_locked(link);
    503             if (released) {
    504                 released->next = closed;
    505                 closed = released;
    506                 continue;
    507             }
    508         }
    509         link = &driver->next;
    510     }
    511     miles_started = 0;
    512     if (pthread_mutex_unlock(&audio_mutex)) abort();
    513     while (closed) {
    514         struct audio_driver *next = closed->next;
    515         destroy_driver(closed);
    516         closed = next;
    517     }
    518     g_esp += 4;
    519 }
    520 
    521 static void quick_shutdown(void)
    522 {
    523     /* Mss32.dll FUN_21120b70 only releases AIL_quick_startup-owned handles.
    524        AO uses waveOutOpen directly, so this must leave ordinary drivers alone. */
    525     g_esp += 4;
    526 }
    527 
    528 static void digital_latency(void)
    529 {
    530     uint32_t handle = MEM32(g_esp + 4);
    531     g_eax = 0;
    532     if (pthread_mutex_lock(&audio_mutex)) abort();
    533     if (handle) {
    534         struct audio_driver *driver = drivers;
    535         while (driver && driver->handle != handle) driver = driver->next;
    536         if (!driver) abort();
    537         /* SDL exposes its buffer duration, not the downstream hardware delay. */
    538         g_eax = driver->latency;
    539     }
    540     if (pthread_mutex_unlock(&audio_mutex)) abort();
    541     g_esp += 8;
    542 }
    543 
    544 static void open_stream(void)
    545 {
    546     uint32_t handle = MEM32(g_esp + 4), filename = MEM32(g_esp + 8), memory = MEM32(g_esp + 12);
    547     g_esp += 16;
    548     g_eax = 0;
    549     if (!handle || !filename) return;
    550     if (memory) { fprintf(stderr, "Explicit Miles stream memory limits are not implemented\n"); abort(); }
    551     if (pthread_mutex_lock(&audio_mutex)) abort();
    552     struct audio_driver *driver = drivers;
    553     while (driver && driver->handle != handle) driver = driver->next;
    554     if (!driver) abort();
    555     int channels = driver->format.channels, rate = driver->format.freq;
    556     if (pthread_mutex_unlock(&audio_mutex)) abort();
    557 
    558     double profile_start = ao_profile_begin("music load/decode");
    559     /* Retain decoded floats directly when they already match the mixer. */
    560     char *path = linux_path((const char *)ADDR(filename));
    561     SF_INFO info = {0};
    562     SNDFILE *file = sf_open(path, SFM_READ, &info);
    563     if (file) {
    564         if (info.frames < 0 || info.channels < 1 || info.channels > 2 ||
    565             info.frames > INT_MAX / (int)sizeof(float) / info.channels) abort();
    566         float *decoded = malloc(info.frames ? info.frames * info.channels * sizeof(float) : 1);
    567         if (!decoded) abort();
    568         sf_count_t frames = sf_readf_float(file, decoded, info.frames);
    569         if (frames < 0 || sf_error(file)) abort();
    570         if (sf_close(file)) abort();
    571         struct audio_stream *stream = calloc(1, sizeof(*stream));
    572         if (!stream) abort();
    573         if (info.channels == channels && info.samplerate == rate) {
    574             stream->samples = decoded;
    575             stream->frames = frames;
    576         } else {
    577             SDL_AudioStream *conversion = SDL_NewAudioStream(AUDIO_F32SYS, info.channels, info.samplerate,
    578                 AUDIO_F32SYS, channels, rate);
    579             if (!conversion || SDL_AudioStreamPut(conversion, decoded, frames * info.channels * sizeof(float)) ||
    580                 SDL_AudioStreamFlush(conversion)) abort();
    581             free(decoded);
    582             int size = SDL_AudioStreamAvailable(conversion);
    583             if (size < 0 || size % (sizeof(float) * channels)) abort();
    584             stream->samples = malloc(size ? size : 1);
    585             if (!stream->samples || SDL_AudioStreamGet(conversion, stream->samples, size) != size) abort();
    586             SDL_FreeAudioStream(conversion);
    587             stream->frames = size / sizeof(float) / channels;
    588         }
    589         stream->status = 2;
    590         stream->volume = 127;
    591         fprintf(stderr, "[linux-audio] decoded %s: %u frames\n", path, stream->frames);
    592         /* The driver may have closed while file I/O ran independently. */
    593         if (pthread_mutex_lock(&audio_mutex)) abort();
    594         driver = drivers;
    595         while (driver && driver->handle != handle) driver = driver->next;
    596         if (driver) {
    597             if (next_stream >= 0xf7000000u) abort();
    598             stream->handle = next_stream++;
    599             audio_output_lock(driver->device);
    600             stream->next = driver->streams;
    601             driver->streams = stream;
    602             audio_output_unlock(driver->device);
    603             g_eax = stream->handle;
    604         } else {
    605             free(stream->samples);
    606             free(stream);
    607         }
    608         if (pthread_mutex_unlock(&audio_mutex)) abort();
    609     } else fprintf(stderr, "[linux-audio] stream %s: %s\n", path, sf_strerror(NULL));
    610     ao_profile_end("music load/decode", profile_start, path);
    611     free(path);
    612 }
    613 
    614 static void file_read(void)
    615 {
    616     uint32_t filename = MEM32(g_esp + 4), destination = MEM32(g_esp + 8);
    617     g_esp += 12;
    618     g_eax = 0;
    619     char *path = linux_path((const char *)ADDR(filename));
    620     FILE *file = fopen(path, "rb");
    621     free(path);
    622     if (!file) return;
    623 
    624     /* Miles allocates four extra bytes; -1 requests a leading file length. */
    625     if (fseek(file, 0, SEEK_END)) { fclose(file); return; }
    626     long size = ftell(file);
    627     if (size < 0 || size > UINT32_MAX - 4 || fseek(file, 0, SEEK_SET)) {
    628         fclose(file);
    629         return;
    630     }
    631     int allocated = !destination || destination == UINT32_MAX;
    632     uint32_t result = allocated ? guest_malloc(size + 4) : destination;
    633     if (!result) { fclose(file); return; }
    634     uint32_t data = result;
    635     if (destination == UINT32_MAX) {
    636         MEM32(data) = size;
    637         data += 4;
    638     }
    639     size_t count = fread((void *)ADDR(data), 1, size, file);
    640     fclose(file);
    641     if (count != (size_t)size) {
    642         if (allocated) guest_free(result);
    643         return;
    644     }
    645     g_eax = result;
    646 }
    647 
    648 static void file_type(void)
    649 {
    650     uint32_t data = MEM32(g_esp + 4), size = MEM32(g_esp + 8);
    651     g_esp += 12;
    652     g_eax = 0;
    653     if (!data || size < 8) return;
    654 
    655     /* RIFF chunks identify PCM/IMA WAV or the embedded MPEG payload. */
    656     if (size >= 12 && MEM32(data) == 0x46464952 && MEM32(data + 8) == 0x45564157) {
    657         uint32_t format = 0, payload = 0, length = 0;
    658         for (uint32_t offset = 12; offset <= size - 8;) {
    659             uint32_t chunk = MEM32(data + offset + 4);
    660             if (chunk > size - offset - 8) return;
    661             if (MEM32(data + offset) == 0x20746d66 && chunk >= 16) format = data + offset + 8;
    662             if (MEM32(data + offset) == 0x61746164) { payload = data + offset + 8; length = chunk; }
    663             uint64_t next = (uint64_t)offset + 8 + chunk + (chunk & 1);
    664             if (next > size) break;
    665             offset = next;
    666         }
    667         if (format && payload) {
    668             uint16_t tag = MEM16(format);
    669             if (tag == 1) { g_eax = 1; return; }
    670             if (tag == 17) { g_eax = MEM16(format + 14) == 4 ? 2 : 3; return; }
    671             if (tag != 85) { g_eax = 3; return; }
    672             data = payload;
    673             size = length;
    674         }
    675     }
    676 
    677     /* Miles recognizes MPEG layers from the first 3072 bytes of frame headers. */
    678     if (size > 3072) size = 3072;
    679     for (uint32_t offset = 0; offset + 4 <= size; ++offset) {
    680         uint32_t header = MEM32(data + offset);
    681         if ((header & 0xf0ff) != 0xf0ff) continue;
    682         unsigned layer = (header >> 9) & 3;
    683         if (header != UINT32_MAX && (header & 0xfc0000) != 0xfc0000 && layer) {
    684             g_eax = 14 - layer;
    685             return;
    686         }
    687         offset += 3;
    688     }
    689 }
    690 
    691 static void mem_free_lock(void)
    692 {
    693     uint32_t handle = MEM32(g_esp + 4);
    694     if (handle >= 0xf7800000u && handle < 0xf8000000u) {
    695         if (pthread_mutex_lock(&audio_mutex)) abort();
    696         struct audio_asset *asset = assets;
    697         while (asset && asset->handle != handle) asset = asset->next;
    698         if (!asset) abort();
    699         release_asset_locked(asset);
    700         if (pthread_mutex_unlock(&audio_mutex)) abort();
    701     } else guest_free(handle);
    702     g_esp += 8;
    703 }
    704 
    705 /* libsndfile reads guest RIFF data through a bounded, read-only view. */
    706 struct audio_memory { const unsigned char *data; sf_count_t size, position; };
    707 static sf_count_t audio_length(void *context) { return ((struct audio_memory *)context)->size; }
    708 static sf_count_t audio_tell(void *context) { return ((struct audio_memory *)context)->position; }
    709 static sf_count_t audio_seek(sf_count_t offset, int whence, void *context)
    710 {
    711     struct audio_memory *memory = context;
    712     sf_count_t position = offset + (whence == SEEK_CUR ? memory->position : whence == SEEK_END ? memory->size : 0);
    713     if (position < 0 || position > memory->size) return -1;
    714     return memory->position = position;
    715 }
    716 static sf_count_t audio_read(void *output, sf_count_t count, void *context)
    717 {
    718     struct audio_memory *memory = context;
    719     if (count > memory->size - memory->position) count = memory->size - memory->position;
    720     memcpy(output, memory->data + memory->position, count);
    721     memory->position += count;
    722     return count;
    723 }
    724 
    725 static void decompress_asi(void)
    726 {
    727     uint32_t data = MEM32(g_esp + 4), size = MEM32(g_esp + 8), filename = MEM32(g_esp + 12);
    728     uint32_t output = MEM32(g_esp + 16), output_size = MEM32(g_esp + 20), callback = MEM32(g_esp + 24);
    729     g_esp += 28;
    730     g_eax = 0;
    731     if (!data || !size || !filename || !output) return;
    732     if (callback) { fprintf(stderr, "Miles decompression callbacks are not implemented\n"); abort(); }
    733 
    734     /* mmr.dll sub_3A008430 requests MPEG layer III, with no callback.
    735        Miles selects this codec by extension; a .wav filename is not accepted. */
    736     const char *extension = strrchr((const char *)ADDR(filename), '.');
    737     if (!extension || strcasecmp(extension, ".mp3")) return;
    738     struct audio_memory memory = {(const unsigned char *)ADDR(data), size, 0};
    739     SF_VIRTUAL_IO io = {audio_length, audio_seek, audio_read, NULL, audio_tell};
    740     SF_INFO info = {0};
    741     SNDFILE *file = sf_open_virtual(&io, SFM_READ, &info, &memory);
    742     if (!file) return;
    743     if ((info.format & SF_FORMAT_SUBMASK) != SF_FORMAT_MPEG_LAYER_III || info.frames <= 0 ||
    744         info.channels < 1 || info.channels > 2 || info.frames > (INT_MAX - 44) / (2 * info.channels)) {
    745         sf_close(file);
    746         return;
    747     }
    748 
    749     /* Return an owned PCM16 RIFF buffer, released by AIL_mem_free_lock. */
    750     uint32_t wave = guest_malloc(44 + info.frames * info.channels * 2);
    751     if (!wave) { sf_close(file); return; }
    752     sf_count_t frames = sf_readf_short(file, (short *)ADDR(wave + 44), info.frames);
    753     int error = sf_error(file);
    754     if (sf_close(file) || error || frames <= 0) { guest_free(wave); return; }
    755     uint32_t bytes = frames * info.channels * 2;
    756     memcpy((void *)ADDR(wave), "RIFF", 4);
    757     MEM32(wave + 4) = bytes + 36;
    758     memcpy((void *)ADDR(wave + 8), "WAVEfmt ", 8);
    759     MEM32(wave + 16) = 16;
    760     MEM16(wave + 20) = 1;
    761     MEM16(wave + 22) = info.channels;
    762     MEM32(wave + 24) = info.samplerate;
    763     MEM32(wave + 28) = info.samplerate * info.channels * 2;
    764     MEM16(wave + 32) = info.channels * 2;
    765     MEM16(wave + 34) = 16;
    766     memcpy((void *)ADDR(wave + 36), "data", 4);
    767     MEM32(wave + 40) = bytes;
    768     MEM32(output) = wave;
    769     if (output_size) MEM32(output_size) = bytes + 44;
    770     g_eax = 1;
    771 }
    772 
    773 static void init_sample_locked(struct audio_sample *sample)
    774 {
    775     if (sample->asset) release_asset_locked(sample->asset);
    776     else free(sample->samples);
    777     sample->asset = NULL;
    778     sample->samples = NULL;
    779     sample->frames = 0;
    780     sample->position = 0;
    781     sample->status = 2;
    782     sample->volume = 127;
    783     sample->rate = 11025;
    784     sample->loops = 1;
    785 }
    786 
    787 static void allocate_sample_handle(void)
    788 {
    789     uint32_t handle = MEM32(g_esp + 4);
    790     g_esp += 8;
    791     g_eax = 0;
    792     if (!handle) return;
    793     if (pthread_mutex_lock(&audio_mutex)) abort();
    794     struct audio_driver *driver = drivers;
    795     while (driver && driver->handle != handle) driver = driver->next;
    796     if (!driver) abort();
    797     audio_output_lock(driver->device);
    798     unsigned used = 0;
    799     struct audio_sample *available = NULL;
    800     for (struct audio_sample *sample = driver->samples; sample; sample = sample->next) {
    801         if (sample->status == 1) available = sample;
    802         else ++used;
    803     }
    804     for (struct audio_stream *stream = driver->streams; stream; stream = stream->next) ++used;
    805     if (used < (unsigned)driver->sample_capacity) {
    806         if (!available) {
    807             available = calloc(1, sizeof(*available));
    808             if (!available || next_sample >= 0xf7800000u) abort();
    809             available->handle = next_sample++;
    810             available->next = driver->samples;
    811             driver->samples = available;
    812         }
    813         init_sample_locked(available);
    814         g_eax = available->handle;
    815     }
    816     audio_output_unlock(driver->device);
    817     if (pthread_mutex_unlock(&audio_mutex)) abort();
    818 }
    819 
    820 enum sample_operation { SAMPLE_INIT, SAMPLE_RELEASE, SAMPLE_STATUS, SAMPLE_FILE, SAMPLE_START,
    821     SAMPLE_END, SAMPLE_VOLUME, SAMPLE_LOOPS, SAMPLE_RATE, SAMPLE_GET_RATE };
    822 
    823 static void sample_control(enum sample_operation operation, unsigned arguments)
    824 {
    825     uint32_t handle = MEM32(g_esp + 4), value = arguments > 1 ? MEM32(g_esp + 8) : 0;
    826     g_esp += 4 + arguments * 4;
    827     g_eax = 0;
    828     if (!handle) return;
    829     if (pthread_mutex_lock(&audio_mutex)) abort();
    830     struct audio_driver *driver = drivers;
    831     struct audio_sample *sample = NULL;
    832     for (; driver; driver = driver->next) {
    833         for (sample = driver->samples; sample && sample->handle != handle; sample = sample->next) {}
    834         if (sample) break;
    835     }
    836     if (!sample) abort();
    837     audio_output_lock(driver->device);
    838     adopt_sample_locked(sample);
    839     if (operation == SAMPLE_INIT) init_sample_locked(sample);
    840     else if (operation == SAMPLE_RELEASE) { init_sample_locked(sample); sample->status = 1; }
    841     else if (operation == SAMPLE_STATUS) g_eax = sample->status;
    842     else if (operation == SAMPLE_GET_RATE) g_eax = sample->rate;
    843     else if (operation == SAMPLE_RATE) {
    844         if ((int32_t)value <= 0) abort();
    845         sample->rate = value;
    846     } else if (operation == SAMPLE_VOLUME) sample->volume = (int32_t)value < 0 ? 0 : value > 127 ? 127 : value;
    847     else if (operation == SAMPLE_LOOPS) sample->loops = value;
    848     else if (operation == SAMPLE_END) { if (sample->status != 1) sample->status = 2; }
    849     else if (operation == SAMPLE_START) {
    850         if (sample->status != 1 && (sample->frames || sample->asset)) {
    851             sample->position = 0;
    852             sample->status = 4;
    853             adopt_sample_locked(sample);
    854         }
    855     } else if (operation == SAMPLE_FILE) {
    856         if (value >= 0xf7800000u && value < 0xf8000000u) {
    857             struct audio_asset *asset = assets;
    858             while (asset && asset->handle != value) asset = asset->next;
    859             if (!asset) abort();
    860             ++asset->references;
    861             if (sample->asset) release_asset_locked(sample->asset);
    862             else free(sample->samples);
    863             sample->asset = asset;
    864             sample->samples = NULL;
    865             sample->frames = 0;
    866             sample->position = 0;
    867             sample->rate = 44100;
    868             sample->status = 2;
    869             adopt_sample_locked(sample);
    870             g_eax = 1;
    871         } else if (value && MEM32(value) == 0x46464952 && MEM32(value + 8) == 0x45564157) {
    872             struct audio_memory memory = {(const unsigned char *)ADDR(value), (uint64_t)MEM32(value + 4) + 8, 0};
    873             SF_VIRTUAL_IO io = {audio_length, audio_seek, audio_read, NULL, audio_tell};
    874             SF_INFO info = {0};
    875             SNDFILE *file = sf_open_virtual(&io, SFM_READ, &info, &memory);
    876             if (file) {
    877                 if (info.frames < 0 || info.channels < 1 || info.channels > 2 ||
    878                     info.frames > INT_MAX / (int)sizeof(float) / info.channels) abort();
    879                 float *decoded = malloc(info.frames ? info.frames * info.channels * sizeof(float) : 1);
    880                 if (!decoded) abort();
    881                 sf_count_t frames = sf_readf_float(file, decoded, info.frames);
    882                 if (frames > 0 && !sf_error(file)) {
    883                     if (sample->asset) release_asset_locked(sample->asset);
    884                     else free(sample->samples);
    885                     sample->asset = NULL;
    886                     sample->samples = decoded;
    887                     sample->frames = frames;
    888                     sample->channels = info.channels;
    889                     sample->rate = info.samplerate;
    890                     sample->position = 0;
    891                     sample->status = 2;
    892                     g_eax = 1;
    893                 } else free(decoded);
    894                 if (sf_close(file)) abort();
    895             }
    896         }
    897     } else abort();
    898     audio_output_unlock(driver->device);
    899     if (operation == SAMPLE_START) audio_output_pause(driver->device, 0);
    900     if (pthread_mutex_unlock(&audio_mutex)) abort();
    901 }
    902 
    903 static void init_sample(void) { sample_control(SAMPLE_INIT, 1); }
    904 static void release_sample_handle(void) { sample_control(SAMPLE_RELEASE, 1); }
    905 static void sample_status(void) { sample_control(SAMPLE_STATUS, 1); }
    906 static void set_sample_file(void) { sample_control(SAMPLE_FILE, 3); }
    907 static void start_sample(void) { sample_control(SAMPLE_START, 1); }
    908 static void end_sample(void) { sample_control(SAMPLE_END, 1); }
    909 static void set_sample_volume(void) { sample_control(SAMPLE_VOLUME, 2); }
    910 static void set_sample_loop_count(void) { sample_control(SAMPLE_LOOPS, 2); }
    911 static void set_sample_playback_rate(void) { sample_control(SAMPLE_RATE, 2); }
    912 static void sample_playback_rate(void) { sample_control(SAMPLE_GET_RATE, 1); }
    913 
    914 enum stream_operation { STREAM_STATUS, STREAM_VOLUME, STREAM_START, STREAM_PAUSE, STREAM_CLOSE, STREAM_POSITION, STREAM_SEEK };
    915 
    916 static void stream_control(enum stream_operation operation, unsigned arguments)
    917 {
    918     uint32_t handle = MEM32(g_esp + 4), value = arguments > 1 ? MEM32(g_esp + 8) : 0;
    919     uint32_t position = arguments == 3 ? MEM32(g_esp + 12) : 0;
    920     g_esp += 4 + arguments * 4;
    921     g_eax = UINT32_MAX;
    922     if (!handle) return;
    923     if (pthread_mutex_lock(&audio_mutex)) abort();
    924     struct audio_driver *driver = drivers;
    925     struct audio_stream **link = NULL;
    926     for (; driver; driver = driver->next) {
    927         link = &driver->streams;
    928         while (*link && (*link)->handle != handle) link = &(*link)->next;
    929         if (*link) break;
    930     }
    931     if (!driver) abort();
    932     audio_output_lock(driver->device);
    933     struct audio_stream *stream = *link;
    934     if (operation == STREAM_STATUS) g_eax = stream->status;
    935     else if (operation == STREAM_POSITION) {
    936         if (value) MEM32(value) = llrint((double)stream->frames * 1000 / driver->format.freq);
    937         if (position) MEM32(position) = llrint((double)stream->position * 1000 / driver->format.freq);
    938     }
    939     else if (operation == STREAM_VOLUME) stream->volume = (int32_t)value;
    940     else if (operation == STREAM_SEEK) {
    941         uint64_t frame = llrint((double)driver->format.freq * (int32_t)value * 0.001);
    942         stream->seek_position = frame < stream->frames ? frame : stream->frames;
    943         stream->seek_pending = 1;
    944         if (stream->status == 4) {
    945             stream->position = stream->seek_position;
    946             stream->seek_pending = 0;
    947             if (stream->position == stream->frames) stream->status = 2;
    948         } else stream->status = 2;
    949     }
    950     else if (operation == STREAM_START) {
    951         stream->position = stream->seek_pending ? stream->seek_position : 0;
    952         stream->seek_pending = 0;
    953         stream->status = stream->position < stream->frames ? 4 : 2;
    954     }
    955     else if (operation == STREAM_PAUSE) {
    956         if (value) { if (stream->status == 4) stream->status = 8; }
    957         else {
    958             if (stream->seek_pending) {
    959                 stream->position = stream->seek_position;
    960                 stream->seek_pending = 0;
    961             }
    962             if (stream->position < stream->frames) stream->status = 4;
    963         }
    964     } else if (operation == STREAM_CLOSE) {
    965         *link = stream->next;
    966         free(stream->samples);
    967         free(stream);
    968     } else abort();
    969     audio_output_unlock(driver->device);
    970     if (operation == STREAM_START || (operation == STREAM_PAUSE && !value))
    971         audio_output_pause(driver->device, 0);
    972     if (pthread_mutex_unlock(&audio_mutex)) abort();
    973 }
    974 
    975 static void start_stream(void) { stream_control(STREAM_START, 1); }
    976 static void pause_stream(void) { stream_control(STREAM_PAUSE, 2); }
    977 static void close_stream(void) { stream_control(STREAM_CLOSE, 1); }
    978 static void stream_status(void) { stream_control(STREAM_STATUS, 1); }
    979 static void set_stream_volume(void) { stream_control(STREAM_VOLUME, 2); }
    980 static void stream_ms_position(void) { stream_control(STREAM_POSITION, 3); }
    981 static void set_stream_ms_position(void) { stream_control(STREAM_SEEK, 2); }
    982 
    983 recomp_func_t linux_audio_lookup(const char *dll, const char *name)
    984 {
    985     if (!strcasecmp(dll, "winmm.dll") && !strcmp(name, "waveOutGetNumDevs"))
    986         return wave_out_get_num_devs;
    987     if (strcasecmp(dll, "mss32.dll")) return NULL;
    988     static const struct { const char *name; recomp_func_t function; } functions[] = {
    989         {"_AIL_set_redist_directory@4", set_redist_directory},
    990         {"_AIL_startup@0", miles_startup},
    991         {"_AIL_set_preference@8", set_preference},
    992         {"_AIL_waveOutOpen@16", wave_out_open},
    993         {"_AIL_waveOutClose@4", wave_out_close},
    994         {"_AIL_set_digital_master_volume@8", set_digital_master_volume},
    995         {"_AIL_shutdown@0", miles_shutdown},
    996         {"_AIL_quick_shutdown@0", quick_shutdown},
    997         {"_AIL_digital_latency@4", digital_latency},
    998         {"_AIL_open_stream@12", open_stream},
    999         {"_AIL_file_read@8", file_read},
   1000         {"_AIL_file_type@8", file_type},
   1001         {"_AIL_decompress_ASI@24", decompress_asi},
   1002         {"_AIL_allocate_sample_handle@4", allocate_sample_handle},
   1003         {"_AIL_init_sample@4", init_sample},
   1004         {"_AIL_release_sample_handle@4", release_sample_handle},
   1005         {"_AIL_sample_status@4", sample_status},
   1006         {"_AIL_set_sample_file@12", set_sample_file},
   1007         {"_AIL_start_sample@4", start_sample},
   1008         {"_AIL_end_sample@4", end_sample},
   1009         {"_AIL_set_sample_volume@8", set_sample_volume},
   1010         {"_AIL_set_sample_loop_count@8", set_sample_loop_count},
   1011         {"_AIL_set_sample_playback_rate@8", set_sample_playback_rate},
   1012         {"_AIL_sample_playback_rate@4", sample_playback_rate},
   1013         {"_AIL_mem_free_lock@4", mem_free_lock},
   1014         {"_AIL_start_stream@4", start_stream},
   1015         {"_AIL_pause_stream@8", pause_stream},
   1016         {"_AIL_close_stream@4", close_stream},
   1017         {"_AIL_stream_status@4", stream_status},
   1018         {"_AIL_set_stream_volume@8", set_stream_volume},
   1019         {"_AIL_stream_ms_position@12", stream_ms_position},
   1020         {"_AIL_set_stream_ms_position@8", set_stream_ms_position},
   1021     };
   1022     for (unsigned i = 0; i < sizeof(functions) / sizeof(functions[0]); ++i)
   1023         if (!strcmp(name, functions[i].name)) return functions[i].function;
   1024     return NULL;
   1025 }