MediaSource.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #include "MediaSource.h"
  2. #include <ranges>
  3. using namespace WallpaperEngine::Media;
  4. MediaSource::MediaSource (std::chrono::milliseconds updateInterval) :
  5. m_aliveFlag (std::make_unique<bool> (true)), m_mediaInfo (
  6. {
  7. .playbackState = PlaybackState::Stopped,
  8. .title = "",
  9. .artist = "",
  10. .url = std::nullopt,
  11. .duration = 0.0f,
  12. .position = 0.0f,
  13. .available = false,
  14. }
  15. ),
  16. m_updateInterval (updateInterval) { }
  17. MediaSource::~MediaSource () {
  18. if (this->m_aliveFlag) {
  19. *m_aliveFlag = false;
  20. }
  21. m_albumArtListeners.clear ();
  22. m_metadataListeners.clear ();
  23. }
  24. void MediaSource::update () {
  25. if (std::chrono::steady_clock::now () <= m_nextUpdate) {
  26. return;
  27. }
  28. this->performUpdate ();
  29. }
  30. std::function<void ()> MediaSource::addMetadataListener (std::function<void (const MediaInfo&)> listener) {
  31. int listenerId = ++m_metadataListenerId;
  32. m_metadataListeners.emplace (listenerId, listener);
  33. auto alive = m_aliveFlag;
  34. return [this, listenerId, alive] () {
  35. if (!alive || !*alive) {
  36. return;
  37. }
  38. m_metadataListeners.erase (listenerId);
  39. };
  40. }
  41. std::function<void ()> MediaSource::addAlbumArtListener (std::function<void (const MediaInfo&)> listener) {
  42. int listenerId = ++m_albumArtListenerId;
  43. m_albumArtListeners.emplace (listenerId, listener);
  44. auto alive = m_aliveFlag;
  45. return [this, listenerId, alive] () {
  46. if (!alive || !*alive) {
  47. return;
  48. }
  49. m_albumArtListeners.erase (listenerId);
  50. };
  51. }
  52. void MediaSource::fireMetadataListeners () {
  53. for (auto& listener : m_metadataListeners | std::views::values) {
  54. listener (m_mediaInfo);
  55. }
  56. }
  57. void MediaSource::fireAlbumArtListeners () {
  58. for (auto& listener : m_albumArtListeners | std::views::values) {
  59. listener (m_mediaInfo);
  60. }
  61. }