Skip to content

Truly independent web browser

2.4 KB
Raw Blame
/*
 * Copyright (c) 2023-2025, Gregory Bertilson <[email protected]>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <LibAudio/ClientConnection.h>
#include <LibAudio/NullPlaybackStream.h>

namespace Audio {

// The null fallback needs the callback the failed AudioServer stream was given, and a callback is not copyable. Only
// one of the two ever calls it.
struct SharedDataRequestCallback : public AtomicRefCounted<SharedDataRequestCallback> {
    explicit SharedDataRequestCallback(PlaybackStream::AudioDataRequestCallback callback)
        : callback(move(callback))
    {
    }
    PlaybackStream::AudioDataRequestCallback callback;
};

NonnullRefPtr<PlaybackStream::CreatePromise> PlaybackStream::create(OutputState initial_output_state, u32 target_latency_ms, NonnullRefPtr<OutputSession> session, AudioDataRequestCallback data_request_callback)
{
    auto promise = PlaybackStream::CreatePromise::construct();
    auto shared_callback = make_ref_counted<SharedDataRequestCallback>(move(data_request_callback));
    auto make_data_request_callback = [shared_callback] {
        return [shared_callback](Span<float> buffer, MonotonicTime buffer_starts_playing_at) {
            return shared_callback->callback(buffer, buffer_starts_playing_at);
        };
    };

    auto fall_back_to_null = [promise, make_data_request_callback, initial_output_state, target_latency_ms](Error& error) {
        warnln("Failed to create playback stream: {}; falling back to null output", error);
        promise->resolve(NullPlaybackStream::create(initial_output_state, target_latency_ms, make_data_request_callback()));
    };

    // Only the AudioServer opens devices. A process with no server to reach plays into nothing.
    if (!ClientConnection::has_transport_factory()) {
        auto no_server = Error::from_string_literal("No AudioServer to reach");
        fall_back_to_null(no_server);
        return promise;
    }

    auto connection = ClientConnection::acquire();
    if (connection.is_error()) {
        fall_back_to_null(connection.error());
        return promise;
    }
    auto remote_promise = connection.value()->create_stream(initial_output_state, target_latency_ms, move(session), make_data_request_callback());
    remote_promise->when_resolved([promise](NonnullRefPtr<PlaybackStream>& stream) {
        promise->resolve(stream);
    });
    remote_promise->when_rejected(move(fall_back_to_null));
    return promise;
}

}