AudioCodecPluginAgnostic.cpp 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. /*
  2. * Copyright (c) 2023, Gregory Bertilson <zaggy1024@gmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/MemoryStream.h>
  7. #include <AK/WeakPtr.h>
  8. #include <LibAudio/Loader.h>
  9. #include <LibCore/EventLoop.h>
  10. #include <LibCore/ThreadedPromise.h>
  11. #include <LibCore/Timer.h>
  12. #include "AudioCodecPluginAgnostic.h"
  13. namespace Web::Platform {
  14. constexpr int update_interval = 50;
  15. static Duration timestamp_from_samples(i64 samples, u32 sample_rate)
  16. {
  17. return Duration::from_milliseconds(samples * 1000 / sample_rate);
  18. }
  19. static Duration get_loader_timestamp(NonnullRefPtr<Audio::Loader> const& loader)
  20. {
  21. return timestamp_from_samples(loader->loaded_samples(), loader->sample_rate());
  22. }
  23. ErrorOr<NonnullOwnPtr<AudioCodecPluginAgnostic>> AudioCodecPluginAgnostic::create(NonnullRefPtr<Audio::Loader> const& loader)
  24. {
  25. auto duration = timestamp_from_samples(loader->total_samples(), loader->sample_rate());
  26. auto update_timer = TRY(Core::Timer::try_create());
  27. update_timer->set_interval(update_interval);
  28. auto plugin = TRY(adopt_nonnull_own_or_enomem(new (nothrow) AudioCodecPluginAgnostic(loader, duration, move(update_timer))));
  29. constexpr u32 latency_ms = 100;
  30. RefPtr<Audio::PlaybackStream> output = TRY(Audio::PlaybackStream::create(
  31. Audio::OutputState::Suspended, loader->sample_rate(), loader->num_channels(), latency_ms,
  32. [&plugin = *plugin, loader](Bytes buffer, Audio::PcmSampleFormat format, size_t sample_count) -> ReadonlyBytes {
  33. VERIFY(format == Audio::PcmSampleFormat::Float32);
  34. auto samples = loader->get_more_samples(sample_count).release_value_but_fixme_should_propagate_errors();
  35. VERIFY(samples.size() <= sample_count);
  36. FixedMemoryStream writing_stream { buffer };
  37. for (auto& sample : samples) {
  38. MUST(writing_stream.write_value(sample.left));
  39. MUST(writing_stream.write_value(sample.right));
  40. }
  41. // FIXME: Check if we have loaded samples past the current known duration, and if so, update it
  42. // and notify the media element.
  43. return buffer.trim(writing_stream.offset());
  44. }));
  45. output->set_underrun_callback([&plugin = *plugin, loader, output]() {
  46. auto new_device_time = output->total_time_played().release_value_but_fixme_should_propagate_errors();
  47. auto new_media_time = timestamp_from_samples(loader->loaded_samples(), loader->sample_rate());
  48. plugin.m_main_thread_event_loop.deferred_invoke([&plugin, new_device_time, new_media_time]() {
  49. plugin.m_last_resume_in_device_time = new_device_time;
  50. plugin.m_last_resume_in_media_time = new_media_time;
  51. });
  52. });
  53. plugin->m_output = move(output);
  54. return plugin;
  55. }
  56. AudioCodecPluginAgnostic::AudioCodecPluginAgnostic(NonnullRefPtr<Audio::Loader> loader, Duration duration, NonnullRefPtr<Core::Timer> update_timer)
  57. : m_loader(move(loader))
  58. , m_duration(duration)
  59. , m_main_thread_event_loop(Core::EventLoop::current())
  60. , m_update_timer(move(update_timer))
  61. {
  62. m_update_timer->on_timeout = [this]() {
  63. update_timestamp();
  64. };
  65. }
  66. void AudioCodecPluginAgnostic::resume_playback()
  67. {
  68. m_paused = false;
  69. m_output->resume()
  70. ->when_resolved([this](Duration new_device_time) {
  71. m_main_thread_event_loop.deferred_invoke([this, new_device_time]() {
  72. m_last_resume_in_device_time = new_device_time;
  73. m_update_timer->start();
  74. });
  75. })
  76. .when_rejected([](Error&&) {
  77. // FIXME: Propagate errors.
  78. });
  79. }
  80. void AudioCodecPluginAgnostic::pause_playback()
  81. {
  82. m_paused = true;
  83. m_output->drain_buffer_and_suspend()
  84. ->when_resolved([this]() -> ErrorOr<void> {
  85. auto new_media_time = timestamp_from_samples(m_loader->loaded_samples(), m_loader->sample_rate());
  86. auto new_device_time = TRY(m_output->total_time_played());
  87. m_main_thread_event_loop.deferred_invoke([this, new_media_time, new_device_time]() {
  88. m_last_resume_in_media_time = new_media_time;
  89. m_last_resume_in_device_time = new_device_time;
  90. m_update_timer->stop();
  91. update_timestamp();
  92. });
  93. return {};
  94. })
  95. .when_rejected([](Error&&) {
  96. // FIXME: Propagate errors.
  97. });
  98. }
  99. void AudioCodecPluginAgnostic::set_volume(double volume)
  100. {
  101. m_output->set_volume(volume)->when_rejected([](Error&&) {
  102. // FIXME: Propagate errors.
  103. });
  104. }
  105. void AudioCodecPluginAgnostic::seek(double position)
  106. {
  107. m_output->discard_buffer_and_suspend()
  108. ->when_resolved([this, position, was_paused = m_paused]() -> ErrorOr<void> {
  109. auto sample_position = static_cast<i32>(position * m_loader->sample_rate());
  110. auto seek_result = m_loader->seek(sample_position);
  111. if (seek_result.is_error())
  112. return Error::from_string_literal("Seeking in audio loader failed");
  113. auto new_media_time = get_loader_timestamp(m_loader);
  114. auto new_device_time = m_output->total_time_played().release_value_but_fixme_should_propagate_errors();
  115. m_main_thread_event_loop.deferred_invoke([this, was_paused, new_device_time, new_media_time]() {
  116. m_last_resume_in_device_time = new_device_time;
  117. m_last_resume_in_media_time = new_media_time;
  118. if (was_paused) {
  119. update_timestamp();
  120. } else {
  121. m_output->resume()->when_rejected([](Error&&) {
  122. // FIXME: Propagate errors.
  123. });
  124. }
  125. });
  126. return {};
  127. })
  128. .when_rejected([](Error&&) {
  129. // FIXME: Propagate errors.
  130. });
  131. }
  132. Duration AudioCodecPluginAgnostic::duration()
  133. {
  134. return m_duration;
  135. }
  136. void AudioCodecPluginAgnostic::update_timestamp()
  137. {
  138. auto current_device_time_result = m_output->total_time_played();
  139. if (!current_device_time_result.is_error())
  140. m_last_good_device_time = current_device_time_result.release_value();
  141. auto current_device_time_delta = m_last_good_device_time - m_last_resume_in_device_time;
  142. auto current_media_time = m_last_resume_in_media_time + current_device_time_delta;
  143. current_media_time = min(current_media_time, m_duration);
  144. on_playback_position_updated(current_media_time);
  145. }
  146. }