//- realtime render // NOTE: max gain change per second. 1/0.008 = a full fade takes 8ms, short enough to feel // instant, long enough that pausing/seeking/volume never clicks. #define AUDIO_FADE_PER_SECOND (1.0f / 0.008f) internal void audio_publish_position(AudioOutput *output) { PlaybackPosition position = {}; if(output->has_marker && output->marker.kind == AUDIO_MARKER_TRACK_START) { position.track_key = output->marker.track_key; position.rate = output->marker.rate; position.total_frames = output->marker.track_total_frames; position.frame = output->marker.track_frame + (output->ring->read_frame - output->marker.ring_frame); position.flags = PLAYBACK_HAS_TRACK; } else { position.track_key = TRACK_NONE; } if(output->starved) position.flags |= PLAYBACK_STARVED; if(output->ended) position.flags |= PLAYBACK_ENDED; // NOTE: seqlock: odd while writing. readers retry if they saw odd or the number changed. u32 sequence = output->position_sequence; AtomicStoreRelaxed(&output->position_sequence, sequence + 1); __atomic_thread_fence(__ATOMIC_RELEASE); AtomicStoreRelaxed(&output->position.track_key, position.track_key); AtomicStoreRelaxed(&output->position.rate, position.rate); AtomicStoreRelaxed(&output->position.frame, position.frame); AtomicStoreRelaxed(&output->position.total_frames, position.total_frames); AtomicStoreRelaxed(&output->position.flags, position.flags); AtomicStore(&output->position_sequence, sequence + 2); } // NOTE: apply every marker at or behind the read head internal void audio_apply_markers(AudioOutput *output) { AudioMarker marker; while(audio_ring_peek_marker(output->ring, &marker) && marker.ring_frame <= output->ring->read_frame) { output->marker = marker; output->has_marker = true; output->frames_since_start = 0; output->ended = (marker.kind == AUDIO_MARKER_END_OF_STREAM); audio_ring_pop_marker(output->ring); } } internal void audio_tap_write(AudioOutput *output, const f32 *samples, u64 frames) { u64 write = output->tap_write; u64 slot = write & (AUDIO_TAP_FRAMES - 1); u64 first = Min(frames, AUDIO_TAP_FRAMES - slot); MemCpy(output->tap + slot * 2, samples, first * 2 * sizeof(f32)); if(first < frames) { MemCpy(output->tap, samples + first * 2, (frames - first) * 2 * sizeof(f32)); } AtomicStore(&output->tap_write, write + frames); } internal void audio_render(AudioOutput *output, f32 *dst, u32 frames) { AudioRing *ring = output->ring; u32 flush_request = AtomicLoad(&ring->flush_request); b32 flushing = (flush_request != output->flush_seen); u64 flush_to = AtomicLoadRelaxed(&ring->flush_to_frame); b32 paused = AtomicLoadRelaxed(&output->paused); f32 volume = f32_from_bits(AtomicLoadRelaxed(&output->volume_bits)); f32 target = (paused || flushing) ? 0.0f : volume; f32 max_step = AUDIO_FADE_PER_SECOND * (f32)frames / (f32)Max(output->rate, 1u); f32 g0 = output->gain; f32 g1 = (target > g0) ? Min(target, g0 + max_step) : Max(target, g0 - max_step); u32 written = 0; f32 step = (g1 - g0) / (f32)Max(frames, 1u); // NOTE: when fully faded out and paused we hold the ring where it is, position stays frozen b32 consume = !(paused && g0 == 0.0f) || flushing; while(consume && written < frames) { audio_apply_markers(output); f32 *src = NULL; u64 available = audio_ring_readable(ring, &src); u64 read = ring->read_frame; // NOTE: while flushing, only play out old audio (it's being faded to zero) if(flushing) { available = (flush_to > read) ? Min(available, flush_to - read) : 0; } // NOTE: stop exactly at the next marker so the position math never straddles two tracks AudioMarker next; if(audio_ring_peek_marker(ring, &next) && next.ring_frame > read) { available = Min(available, next.ring_frame - read); } u64 count = Min(available, (u64)(frames - written)); if(count == 0) { break; } // NOTE: copy and gain in one pass, the ramp continues where the last chunk stopped simd_gain_ramp_copy_stereo(dst + written * 2, src, (u32)count, g0 + step * (f32)written, step); if(output->tap) audio_tap_write(output, src, count); // only the headless text spectrum uses it audio_ring_release(ring, count); written += (u32)count; } b32 has_audio = output->has_marker && output->marker.kind == AUDIO_MARKER_TRACK_START; output->starved = (written < frames) && has_audio && !paused && !flushing; output->frames_since_start += written; // NOTE: running dry before a new track's first sample is the switch itself (opening the file, // a seek, the network), not a glitch in playing audio. count those apart. if(output->starved && output->frames_since_start == 0) { ++output->switch_gaps; } else if(output->starved) { ++output->underruns; } if(written < frames) { MemSetZero(dst + written * 2, (frames - written) * 2 * sizeof(f32)); // silence needs no gain } output->gain = g1; if(flushing) { // NOTE: the old audio got faded this buffer, now drop the rest of it. the next buffer // fades in from 0 on the new data. AtomicStore(&ring->read_frame, Max(ring->read_frame, flush_to)); // the producer published flush_to after the writes before it, so this is >= read_frame ring->consumer_cached_write = AtomicLoad(&ring->write_frame); output->flush_seen = flush_request; output->frames_since_start = 0; // whatever comes next is a new start (seek / play) output->gain = 0.0f; audio_apply_markers(output); } audio_publish_position(output); } internal void audio_on_process(void *user) { AudioOutput *output = (AudioOutput *)user; struct pw_buffer *buffer = pw_stream_dequeue_buffer(output->stream); if(!buffer) { return; } struct spa_buffer *spa = buffer->buffer; struct spa_data *data = &spa->datas[0]; f32 *dst = (f32 *)data->data; if(!dst) { pw_stream_queue_buffer(output->stream, buffer); return; } u32 stride = sizeof(f32) * AUDIO_CHANNELS; u32 frames = data->maxsize / stride; if(buffer->requested) { frames = (u32)Min((u64)frames, buffer->requested); } // NOTE: two vdso clock reads per callback (~20ns each, no syscall), nothing else if(!output->rt_registered) { output->rt_registered = true; profile_thread_register("pw realtime"); // once, the first callback } u64 start = time_now_ns(); audio_render(output, dst, frames); u64 spent = time_now_ns() - start; output->callbacks += 1; output->callback_frames = frames; output->callback_ns_total += spent; if(spent > output->callback_ns_max) output->callback_ns_max = spent; data->chunk->offset = 0; data->chunk->stride = (s32)stride; data->chunk->size = frames * stride; pw_stream_queue_buffer(output->stream, buffer); } internal void audio_on_state_changed(void *user, enum pw_stream_state old_state, enum pw_stream_state state, const char *error) { Log("pipewire stream: %s -> %s%s%s", pw_stream_state_as_string(old_state), pw_stream_state_as_string(state), error ? " error: " : "", error ? error : ""); } global_variable struct pw_stream_events audio_stream_events = {}; //- control internal void audio_output_connect(AudioOutput *output) { // NOTE: spa's builder macros take addresses of compound literals, which c++ rejects, so we // fill the structs by hand struct spa_audio_info_raw info = {}; info.format = SPA_AUDIO_FORMAT_F32; info.rate = output->rate; info.channels = AUDIO_CHANNELS; info.position[0] = SPA_AUDIO_CHANNEL_FL; info.position[1] = SPA_AUDIO_CHANNEL_FR; u8 pod_buffer[1024]; struct spa_pod_builder builder = {}; builder.data = pod_buffer; builder.size = sizeof(pod_buffer); const struct spa_pod *params[1]; params[0] = spa_format_audio_raw_build(&builder, SPA_PARAM_EnumFormat, &info); char rate_string[32]; char latency_string[32]; snprintf(rate_string, sizeof(rate_string), "1/%u", output->rate); // NOTE: ~21ms quantum at 48k. music doesn't need low latency, bigger periods = fewer wakeups snprintf(latency_string, sizeof(latency_string), "%u/%u", 1024u, output->rate); struct spa_dict_item items[] = { {PW_KEY_NODE_RATE, rate_string}, {PW_KEY_NODE_LATENCY, latency_string}, }; struct spa_dict dict = SPA_DICT_INIT(items, ArrayCount(items)); pw_stream_update_properties(output->stream, &dict); int result = pw_stream_connect(output->stream, PW_DIRECTION_OUTPUT, PW_ID_ANY, (enum pw_stream_flags)(PW_STREAM_FLAG_AUTOCONNECT | PW_STREAM_FLAG_MAP_BUFFERS | PW_STREAM_FLAG_RT_PROCESS), params, 1); output->connected = (result == 0); output->active = output->connected; if(result != 0) { Log("pw_stream_connect failed: %d", result); } } internal b32 audio_output_init(Arena *arena, AudioOutput *output, AudioRing *ring, u32 rate) { pw_init(NULL, NULL); output->ring = ring; output->rate = rate; output->volume_bits = f32_bits(0.8f); output->tap = NULL; // the spectrum tap is opt in (headless), the rt path skips it otherwise output->position.track_key = TRACK_NONE; audio_stream_events.version = PW_VERSION_STREAM_EVENTS; audio_stream_events.process = audio_on_process; audio_stream_events.state_changed = audio_on_state_changed; output->loop = pw_thread_loop_new("pw audio", NULL); if(!output->loop) { return false; } struct pw_properties *props = pw_properties_new( PW_KEY_MEDIA_TYPE, "Audio", PW_KEY_MEDIA_CATEGORY, "Playback", PW_KEY_MEDIA_ROLE, "Music", PW_KEY_APP_NAME, "mp3_player", PW_KEY_NODE_NAME, "mp3_player", PW_KEY_NODE_DESCRIPTION, "Quran Player", NULL); pw_thread_loop_lock(output->loop); output->stream = pw_stream_new_simple(pw_thread_loop_get_loop(output->loop), "mp3_player", props, &audio_stream_events, output); if(output->stream) { audio_output_connect(output); } pw_thread_loop_unlock(output->loop); if(!output->stream || !output->connected) { return false; } return pw_thread_loop_start(output->loop) == 0; } internal void audio_output_shutdown(AudioOutput *output) { if(!output->loop) { return; } pw_thread_loop_stop(output->loop); if(output->stream) { pw_stream_destroy(output->stream); } pw_thread_loop_destroy(output->loop); pw_deinit(); } internal void audio_output_set_rate(AudioOutput *output, u32 rate) { if(rate == output->rate || rate == 0) { return; } Log("audio: switching stream to %u hz", rate); pw_thread_loop_lock(output->loop); pw_stream_disconnect(output->stream); output->rate = rate; audio_output_connect(output); pw_thread_loop_unlock(output->loop); } internal void audio_output_set_volume(AudioOutput *output, f32 volume) { // NOTE: perceptual curve, the slider is linear in "loudness" not in amplitude volume = Clamp(volume, 0.0f, 1.0f); AtomicStoreRelaxed(&output->volume_bits, f32_bits(volume * volume * volume)); } internal void audio_output_set_paused(AudioOutput *output, b32 paused) { if(!paused && !output->active) { audio_output_set_active(output, true); } AtomicStore(&output->paused, (u32)(paused ? 1 : 0)); } internal void audio_output_set_active(AudioOutput *output, b32 active) { if(output->active == active || !output->connected) { return; } pw_thread_loop_lock(output->loop); pw_stream_set_active(output->stream, active); pw_thread_loop_unlock(output->loop); output->active = active; } internal PlaybackPosition audio_output_position(AudioOutput *output) { PlaybackPosition result = {}; for(;;) { u32 before = AtomicLoad(&output->position_sequence); if(before & 1) { CpuRelax(); continue; } result.track_key = AtomicLoadRelaxed(&output->position.track_key); result.rate = AtomicLoadRelaxed(&output->position.rate); result.frame = AtomicLoadRelaxed(&output->position.frame); result.total_frames = AtomicLoadRelaxed(&output->position.total_frames); result.flags = AtomicLoadRelaxed(&output->position.flags); __atomic_thread_fence(__ATOMIC_ACQUIRE); if(AtomicLoadRelaxed(&output->position_sequence) == before) { return result; } } } internal void audio_output_read_tap(AudioOutput *output, f32 *out_stereo, u32 frames) { Assert(frames <= AUDIO_TAP_FRAMES); u64 end = AtomicLoad(&output->tap_write); u64 start = end - frames; // NOTE: two copies at most because of the wrap u64 slot = start & (AUDIO_TAP_FRAMES - 1); u64 first = Min((u64)frames, AUDIO_TAP_FRAMES - slot); MemCpy(out_stereo, output->tap + slot * 2, first * 2 * sizeof(f32)); if(first < frames) { MemCpy(out_stereo + first * 2, output->tap, (frames - first) * 2 * sizeof(f32)); } }