AudioCodecPluginAgnostic.cpp 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  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 = 10;
  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. m_update_timer->start();
  66. }
  67. void AudioCodecPluginAgnostic::resume_playback()
  68. {
  69. m_paused = false;
  70. m_output->resume()
  71. ->when_resolved([this](Duration new_device_time) {
  72. m_main_thread_event_loop.deferred_invoke([this, new_device_time]() {
  73. m_last_resume_in_device_time = new_device_time;
  74. m_update_timer->start();
  75. });
  76. })
  77. .when_rejected([](Error&&) {
  78. // FIXME: Propagate errors.
  79. });
  80. }
  81. void AudioCodecPluginAgnostic::pause_playback()
  82. {
  83. m_paused = true;
  84. m_output->drain_buffer_and_suspend()
  85. ->when_resolved([this]() -> ErrorOr<void> {
  86. auto new_media_time = timestamp_from_samples(m_loader->loaded_samples(), m_loader->sample_rate());
  87. auto new_device_time = TRY(m_output->total_time_played());
  88. m_main_thread_event_loop.deferred_invoke([this, new_media_time, new_device_time]() {
  89. m_last_resume_in_media_time = new_media_time;
  90. m_last_resume_in_device_time = new_device_time;
  91. m_update_timer->stop();
  92. update_timestamp();
  93. });
  94. return {};
  95. })
  96. .when_rejected([](Error&&) {
  97. // FIXME: Propagate errors.
  98. });
  99. }
  100. void AudioCodecPluginAgnostic::set_volume(double volume)
  101. {
  102. m_output->set_volume(volume)->when_rejected([](Error&&) {
  103. // FIXME: Propagate errors.
  104. });
  105. }
  106. void AudioCodecPluginAgnostic::seek(double position)
  107. {
  108. m_output->discard_buffer_and_suspend()
  109. ->when_resolved([this, position, was_paused = m_paused]() -> ErrorOr<void> {
  110. auto sample_position = static_cast<i32>(position * m_loader->sample_rate());
  111. auto seek_result = m_loader->seek(sample_position);
  112. if (seek_result.is_error())
  113. return Error::from_string_literal("Seeking in audio loader failed");
  114. auto new_media_time = get_loader_timestamp(m_loader);
  115. auto new_device_time = m_output->total_time_played().release_value_but_fixme_should_propagate_errors();
  116. m_main_thread_event_loop.deferred_invoke([this, was_paused, new_device_time, new_media_time]() {
  117. m_last_resume_in_device_time = new_device_time;
  118. m_last_resume_in_media_time = new_media_time;
  119. if (was_paused) {
  120. update_timestamp();
  121. } else {
  122. m_output->resume()->when_rejected([](Error&&) {
  123. // FIXME: Propagate errors.
  124. });
  125. }
  126. });
  127. return {};
  128. })
  129. .when_rejected([](Error&&) {
  130. // FIXME: Propagate errors.
  131. });
  132. }
  133. Duration AudioCodecPluginAgnostic::duration()
  134. {
  135. return m_duration;
  136. }
  137. void AudioCodecPluginAgnostic::update_timestamp()
  138. {
  139. auto current_device_time_result = m_output->total_time_played();
  140. if (!current_device_time_result.is_error())
  141. m_last_good_device_time = current_device_time_result.release_value();
  142. auto current_device_time_delta = m_last_good_device_time - m_last_resume_in_device_time;
  143. auto current_media_time = m_last_resume_in_media_time + current_device_time_delta;
  144. current_media_time = min(current_media_time, m_duration);
  145. on_playback_position_updated(current_media_time);
  146. }
  147. }