ConnectionToServer.cpp 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2022, kleines Filmröllchen <filmroellchen@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/Atomic.h>
  8. #include <AK/Debug.h>
  9. #include <AK/Format.h>
  10. #include <AK/OwnPtr.h>
  11. #include <AK/Time.h>
  12. #include <AK/Types.h>
  13. #include <LibAudio/ConnectionToServer.h>
  14. #include <LibAudio/Queue.h>
  15. #include <LibAudio/UserSampleQueue.h>
  16. #include <LibCore/Event.h>
  17. #include <LibThreading/Mutex.h>
  18. #include <Userland/Services/AudioServer/AudioClientEndpoint.h>
  19. #include <sched.h>
  20. #include <time.h>
  21. namespace Audio {
  22. ConnectionToServer::ConnectionToServer(NonnullOwnPtr<Core::LocalSocket> socket)
  23. : IPC::ConnectionToServer<AudioClientEndpoint, AudioServerEndpoint>(*this, move(socket))
  24. , m_buffer(make<AudioQueue>(MUST(AudioQueue::create())))
  25. , m_user_queue(make<UserSampleQueue>())
  26. , m_background_audio_enqueuer(Threading::Thread::construct([this]() {
  27. // All the background thread does is run an event loop.
  28. Core::EventLoop enqueuer_loop;
  29. m_enqueuer_loop = &enqueuer_loop;
  30. enqueuer_loop.exec();
  31. {
  32. Threading::MutexLocker const locker(m_enqueuer_loop_destruction);
  33. m_enqueuer_loop = nullptr;
  34. }
  35. return (intptr_t) nullptr;
  36. }))
  37. {
  38. update_good_sleep_time();
  39. async_pause_playback();
  40. set_buffer(*m_buffer);
  41. }
  42. ConnectionToServer::~ConnectionToServer()
  43. {
  44. die();
  45. }
  46. void ConnectionToServer::die()
  47. {
  48. {
  49. Threading::MutexLocker const locker(m_enqueuer_loop_destruction);
  50. // We're sometimes getting here after the other thread has already exited and its event loop does no longer exist.
  51. if (m_enqueuer_loop != nullptr) {
  52. m_enqueuer_loop->wake();
  53. m_enqueuer_loop->quit(0);
  54. }
  55. }
  56. if (m_background_audio_enqueuer->is_started())
  57. (void)m_background_audio_enqueuer->join();
  58. }
  59. ErrorOr<void> ConnectionToServer::async_enqueue(FixedArray<Sample>&& samples)
  60. {
  61. if (!m_background_audio_enqueuer->is_started()) {
  62. m_background_audio_enqueuer->start();
  63. // Wait until the enqueuer has constructed its loop. A pseudo-spinlock is fine since this happens as soon as the other thread gets scheduled.
  64. while (!m_enqueuer_loop)
  65. usleep(1);
  66. TRY(m_background_audio_enqueuer->set_priority(THREAD_PRIORITY_MAX));
  67. }
  68. m_user_queue->append(move(samples));
  69. // Wake the background thread to make sure it starts enqueuing audio.
  70. m_enqueuer_loop->post_event(*this, make<Core::CustomEvent>(0));
  71. m_enqueuer_loop->wake();
  72. async_start_playback();
  73. return {};
  74. }
  75. void ConnectionToServer::clear_client_buffer()
  76. {
  77. m_user_queue->clear();
  78. }
  79. void ConnectionToServer::update_good_sleep_time()
  80. {
  81. auto sample_rate = static_cast<double>(get_self_sample_rate());
  82. auto buffer_play_time_ns = 1'000'000'000.0 / (sample_rate / static_cast<double>(AUDIO_BUFFER_SIZE));
  83. // A factor of 1 should be good for now.
  84. m_good_sleep_time = Duration::from_nanoseconds(static_cast<unsigned>(buffer_play_time_ns)).to_timespec();
  85. }
  86. void ConnectionToServer::set_self_sample_rate(u32 sample_rate)
  87. {
  88. IPC::ConnectionToServer<AudioClientEndpoint, AudioServerEndpoint>::set_self_sample_rate(sample_rate);
  89. update_good_sleep_time();
  90. }
  91. // Non-realtime audio writing loop
  92. void ConnectionToServer::custom_event(Core::CustomEvent&)
  93. {
  94. Array<Sample, AUDIO_BUFFER_SIZE> next_chunk;
  95. while (true) {
  96. if (m_user_queue->is_empty()) {
  97. dbgln_if(AUDIO_DEBUG, "Reached end of provided audio data, going to sleep");
  98. break;
  99. }
  100. auto available_samples = min(AUDIO_BUFFER_SIZE, m_user_queue->size());
  101. for (size_t i = 0; i < available_samples; ++i)
  102. next_chunk[i] = (*m_user_queue)[i];
  103. m_user_queue->discard_samples(available_samples);
  104. // FIXME: Could we receive interrupts in a good non-IPC way instead?
  105. auto result = m_buffer->blocking_enqueue(next_chunk, [this]() {
  106. nanosleep(&m_good_sleep_time, nullptr);
  107. });
  108. if (result.is_error())
  109. dbgln("Error while writing samples to shared buffer: {}", result.error());
  110. }
  111. }
  112. ErrorOr<void, AudioQueue::QueueStatus> ConnectionToServer::realtime_enqueue(Array<Sample, AUDIO_BUFFER_SIZE> samples)
  113. {
  114. return m_buffer->enqueue(samples);
  115. }
  116. ErrorOr<void> ConnectionToServer::blocking_realtime_enqueue(Array<Sample, AUDIO_BUFFER_SIZE> samples, Function<void()> wait_function)
  117. {
  118. return m_buffer->blocking_enqueue(samples, move(wait_function));
  119. }
  120. unsigned ConnectionToServer::total_played_samples() const
  121. {
  122. return m_buffer->weak_tail() * AUDIO_BUFFER_SIZE;
  123. }
  124. unsigned ConnectionToServer::remaining_samples()
  125. {
  126. return static_cast<unsigned>(m_user_queue->remaining_samples());
  127. }
  128. size_t ConnectionToServer::remaining_buffers() const
  129. {
  130. return m_buffer->size() - m_buffer->weak_remaining_capacity();
  131. }
  132. void ConnectionToServer::client_volume_changed(double volume)
  133. {
  134. if (on_client_volume_change)
  135. on_client_volume_change(volume);
  136. }
  137. }