SoundPlayerWidgetAdvancedView.cpp 12 KB

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