SoundPlayerWidgetAdvancedView.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. /*
  2. * Copyright (c) 2021, Cesar Torres <shortanemoia@protonmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "SoundPlayerWidgetAdvancedView.h"
  7. #include "BarsVisualizationWidget.h"
  8. #include "Common.h"
  9. #include "M3UParser.h"
  10. #include "PlaybackManager.h"
  11. #include <AK/LexicalPath.h>
  12. #include <AK/SIMD.h>
  13. #include <LibGUI/Action.h>
  14. #include <LibGUI/BoxLayout.h>
  15. #include <LibGUI/Button.h>
  16. #include <LibGUI/Label.h>
  17. #include <LibGUI/MessageBox.h>
  18. #include <LibGUI/Slider.h>
  19. #include <LibGUI/Splitter.h>
  20. #include <LibGUI/Toolbar.h>
  21. #include <LibGUI/ToolbarContainer.h>
  22. #include <LibGUI/Window.h>
  23. #include <LibGfx/Bitmap.h>
  24. SoundPlayerWidgetAdvancedView::SoundPlayerWidgetAdvancedView(GUI::Window& window, PlayerState& state)
  25. : Player(state)
  26. , m_window(window)
  27. {
  28. window.resize(455, 350);
  29. window.set_minimum_size(600, 130);
  30. window.set_resizable(true);
  31. set_fill_with_background_color(true);
  32. set_layout<GUI::VerticalBoxLayout>();
  33. m_splitter = add<GUI::HorizontalSplitter>();
  34. m_player_view = m_splitter->add<GUI::Widget>();
  35. m_playlist_model = adopt_ref(*new PlaylistModel());
  36. m_player_view->set_layout<GUI::VerticalBoxLayout>();
  37. m_play_icon = Gfx::Bitmap::try_load_from_file("/res/icons/16x16/play.png");
  38. m_pause_icon = Gfx::Bitmap::try_load_from_file("/res/icons/16x16/pause.png");
  39. m_stop_icon = Gfx::Bitmap::try_load_from_file("/res/icons/16x16/stop.png");
  40. m_back_icon = Gfx::Bitmap::try_load_from_file("/res/icons/16x16/go-back.png");
  41. m_next_icon = Gfx::Bitmap::try_load_from_file("/res/icons/16x16/go-forward.png");
  42. m_visualization = m_player_view->add<BarsVisualizationWidget>();
  43. // Set a temporary value for total samples.
  44. // This value will be set properly when we load a new file.
  45. const int total_samples = this->manager().total_length() * this->manager().device_sample_rate();
  46. m_playback_progress_slider = m_player_view->add<AutoSlider>(Orientation::Horizontal);
  47. m_playback_progress_slider->set_fixed_height(20);
  48. m_playback_progress_slider->set_jump_to_cursor(true);
  49. m_playback_progress_slider->set_min(0);
  50. m_playback_progress_slider->set_max(total_samples);
  51. m_playback_progress_slider->set_page_step(total_samples / 10);
  52. m_playback_progress_slider->on_knob_released = [&](int value) {
  53. this->manager().seek(value);
  54. };
  55. auto& toolbar_container = m_player_view->add<GUI::ToolbarContainer>();
  56. auto& menubar = toolbar_container.add<GUI::Toolbar>();
  57. m_play_button = menubar.add<GUI::Button>();
  58. m_play_button->set_icon(is_paused() ? (!has_loaded_file() ? *m_play_icon : *m_pause_icon) : *m_pause_icon);
  59. m_play_button->set_fixed_width(50);
  60. m_play_button->set_enabled(has_loaded_file());
  61. m_play_button->on_click = [&](unsigned) {
  62. bool paused = this->manager().toggle_pause();
  63. set_paused(paused);
  64. m_play_button->set_icon(paused ? *m_play_icon : *m_pause_icon);
  65. m_stop_button->set_enabled(has_loaded_file());
  66. };
  67. m_stop_button = menubar.add<GUI::Button>();
  68. m_stop_button->set_icon(*m_stop_icon);
  69. m_stop_button->set_fixed_width(50);
  70. m_stop_button->set_enabled(has_loaded_file());
  71. m_stop_button->on_click = [&](unsigned) {
  72. this->manager().stop();
  73. set_stopped(true);
  74. m_play_button->set_icon(*m_play_icon);
  75. m_stop_button->set_enabled(false);
  76. };
  77. auto& timestamp_label = menubar.add<GUI::Label>();
  78. timestamp_label.set_fixed_width(110);
  79. timestamp_label.set_text("Elapsed: 00:00:00");
  80. // filler_label
  81. menubar.add<GUI::Label>();
  82. m_back_button = menubar.add<GUI::Button>();
  83. m_back_button->set_fixed_width(50);
  84. m_back_button->set_icon(*m_back_icon);
  85. m_back_button->set_enabled(has_loaded_file());
  86. m_back_button->on_click = [&](unsigned) {
  87. if (!m_playlist_model.is_null()) {
  88. auto it = m_playlist_model->items().find_if([&](const M3UEntry& e) { return e.path == loaded_filename(); });
  89. if (it.index() == 0) {
  90. open_file(m_playlist_model->items().at(m_playlist_model->items().size() - 1).path);
  91. } else
  92. open_file((it - 1)->path);
  93. play();
  94. }
  95. };
  96. m_next_button = menubar.add<GUI::Button>();
  97. m_next_button->set_fixed_width(50);
  98. m_next_button->set_icon(*m_next_icon);
  99. m_next_button->set_enabled(has_loaded_file());
  100. m_next_button->on_click = [&](unsigned) {
  101. if (!m_playlist_model.is_null()) {
  102. auto it = m_playlist_model->items().find_if([&](const M3UEntry& e) { return e.path == loaded_filename(); });
  103. if (it.index() + 1 == m_playlist_model->items().size()) {
  104. open_file(m_playlist_model->items().at(0).path);
  105. } else
  106. open_file((it + 1)->path);
  107. play();
  108. }
  109. };
  110. m_volume_label = &menubar.add<GUI::Label>();
  111. m_volume_label->set_fixed_width(30);
  112. m_volume_label->set_text("100%");
  113. auto& volume_slider = menubar.add<GUI::HorizontalSlider>();
  114. volume_slider.set_fixed_width(95);
  115. volume_slider.set_min(0);
  116. volume_slider.set_max(150);
  117. volume_slider.set_value(100);
  118. volume_slider.on_change = [&](int value) {
  119. double volume = m_nonlinear_volume_slider ? (double)(value * value) / (100 * 100) : value / 100.;
  120. m_volume_label->set_text(String::formatted("{}%", (int)(volume * 100)));
  121. set_volume(volume);
  122. };
  123. set_volume(1.);
  124. set_nonlinear_volume_slider(false);
  125. manager().on_update = [&]() {
  126. // Determine how many of the source file samples have played.
  127. int samples_played = client_connection().get_played_samples();
  128. float source_to_dest_ratio = static_cast<float>(loaded_file_samplerate()) / manager().device_sample_rate();
  129. samples_played *= source_to_dest_ratio;
  130. samples_played += this->manager().last_seek();
  131. int current_second = samples_played / loaded_file_samplerate();
  132. timestamp_label.set_text(String::formatted("Elapsed: {:02}:{:02}:{:02}", current_second / 3600, current_second / 60, current_second % 60));
  133. if (!m_playback_progress_slider->mouse_is_down()) {
  134. m_playback_progress_slider->set_value(samples_played);
  135. }
  136. dynamic_cast<Visualization*>(m_visualization.ptr())->set_buffer(this->manager().current_buffer());
  137. dynamic_cast<Visualization*>(m_visualization.ptr())->set_samplerate(manager().device_sample_rate());
  138. };
  139. manager().on_load_sample_buffer = [&](Audio::Buffer&) {
  140. //TODO: Implement an equalizer
  141. return;
  142. };
  143. manager().on_finished_playing = [&] {
  144. m_play_button->set_icon(*m_play_icon);
  145. if (looping()) {
  146. open_file(loaded_filename());
  147. return;
  148. }
  149. if (!m_playlist_model.is_null() && !m_playlist_model->items().is_empty()) {
  150. auto it = m_playlist_model->items().find_if([&](const M3UEntry& e) { return e.path == loaded_filename(); });
  151. if (it.index() + 1 == m_playlist_model->items().size()) {
  152. if (looping_playlist()) {
  153. open_file(m_playlist_model->items().at(0).path);
  154. return;
  155. }
  156. } else
  157. open_file((it + 1)->path);
  158. }
  159. m_stop_button->set_enabled(false);
  160. };
  161. }
  162. void SoundPlayerWidgetAdvancedView::open_file(StringView path)
  163. {
  164. if (!Core::File::exists(path)) {
  165. GUI::MessageBox::show(window(), String::formatted("File \"{}\" does not exist", path), "Error opening file", GUI::MessageBox::Type::Error);
  166. return;
  167. }
  168. if (path.ends_with(".m3u", AK::CaseSensitivity::CaseInsensitive) || path.ends_with(".m3u8", AK::CaseSensitivity::CaseInsensitive)) {
  169. read_playlist(path);
  170. return;
  171. }
  172. NonnullRefPtr<Audio::Loader> loader = Audio::Loader::create(path);
  173. if (loader->has_error() || !loader->sample_rate()) {
  174. const String error_string = loader->error_string();
  175. GUI::MessageBox::show(&m_window, String::formatted("Failed to load audio file: {} ({})", path, error_string.is_null() ? "Unknown error" : error_string),
  176. "Filetype error", GUI::MessageBox::Type::Error);
  177. return;
  178. }
  179. m_window.set_title(String::formatted("{} - Sound Player", loader->file()->filename()));
  180. m_playback_progress_slider->set_max(loader->total_samples());
  181. m_playback_progress_slider->set_page_step(loader->total_samples() / 10);
  182. m_playback_progress_slider->set_enabled(true);
  183. m_play_button->set_enabled(true);
  184. m_play_button->set_icon(*m_pause_icon);
  185. m_stop_button->set_enabled(true);
  186. manager().set_loader(move(loader));
  187. set_has_loaded_file(true);
  188. set_loaded_file_samplerate(loader->sample_rate());
  189. set_loaded_filename(path);
  190. play();
  191. }
  192. void SoundPlayerWidgetAdvancedView::set_nonlinear_volume_slider(bool nonlinear)
  193. {
  194. m_nonlinear_volume_slider = nonlinear;
  195. }
  196. void SoundPlayerWidgetAdvancedView::drop_event(GUI::DropEvent& event)
  197. {
  198. event.accept();
  199. if (event.mime_data().has_urls()) {
  200. auto urls = event.mime_data().urls();
  201. if (urls.is_empty())
  202. return;
  203. window()->move_to_front();
  204. open_file(urls.first().path());
  205. }
  206. }
  207. SoundPlayerWidgetAdvancedView::~SoundPlayerWidgetAdvancedView()
  208. {
  209. manager().on_load_sample_buffer = nullptr;
  210. manager().on_update = nullptr;
  211. }
  212. void SoundPlayerWidgetAdvancedView::play()
  213. {
  214. manager().play();
  215. set_paused(false);
  216. set_stopped(false);
  217. }
  218. void SoundPlayerWidgetAdvancedView::read_playlist(StringView path)
  219. {
  220. auto parser = M3UParser::from_file(path);
  221. auto items = parser->parse(true);
  222. VERIFY(items->size() > 0);
  223. try_fill_missing_info(*items, path);
  224. for (auto& item : *items)
  225. m_playlist_model->items().append(item);
  226. set_playlist_visible(true);
  227. m_playlist_model->invalidate();
  228. open_file(items->at(0).path);
  229. if (items->size() > 1) {
  230. m_back_button->set_enabled(true);
  231. m_next_button->set_enabled(true);
  232. } else {
  233. m_back_button->set_enabled(false);
  234. m_next_button->set_enabled(false);
  235. }
  236. }
  237. void SoundPlayerWidgetAdvancedView::set_playlist_visible(bool visible)
  238. {
  239. if (visible) {
  240. m_playlist_widget = m_player_view->parent_widget()->add<PlaylistWidget>();
  241. m_playlist_widget->set_data_model(m_playlist_model);
  242. m_playlist_widget->set_fixed_width(150);
  243. } else {
  244. m_playlist_widget->remove_from_parent();
  245. m_player_view->set_max_width(window()->width());
  246. }
  247. }
  248. void SoundPlayerWidgetAdvancedView::try_fill_missing_info(Vector<M3UEntry>& entries, StringView playlist_p)
  249. {
  250. LexicalPath playlist_path(playlist_p);
  251. Vector<M3UEntry*> to_delete;
  252. for (auto& entry : entries) {
  253. if (!LexicalPath(entry.path).is_absolute()) {
  254. entry.path = String::formatted("{}/{}", playlist_path.dirname(), entry.path);
  255. }
  256. if (!Core::File::exists(entry.path)) {
  257. GUI::MessageBox::show(window(), String::formatted("The file \"{}\" present in the playlist does not exist or was not found. This file will be ignored.", entry.path), "Error reading playlist", GUI::MessageBox::Type::Warning);
  258. to_delete.append(&entry);
  259. continue;
  260. }
  261. if (!entry.extended_info->track_display_title.has_value())
  262. entry.extended_info->track_display_title = LexicalPath::title(entry.path);
  263. if (!entry.extended_info->track_length_in_seconds.has_value()) {
  264. if (auto reader = Audio::Loader::create(entry.path); !reader->has_error())
  265. entry.extended_info->track_length_in_seconds = reader->total_samples() / reader->sample_rate();
  266. //TODO: Implement embedded metadata extractor for other audio formats
  267. }
  268. //TODO: Implement a metadata parser for the uncomfortably numerous popular embedded metadata formats
  269. if (!entry.extended_info->file_size_in_bytes.has_value()) {
  270. FILE* f = fopen(entry.path.characters(), "r");
  271. VERIFY(f != nullptr);
  272. fseek(f, 0, SEEK_END);
  273. entry.extended_info->file_size_in_bytes = ftell(f);
  274. fclose(f);
  275. }
  276. }
  277. for (M3UEntry* entry : to_delete)
  278. entries.remove_first_matching([&](M3UEntry& e) { return &e == entry; });
  279. }