SoundPlayerWidgetAdvancedView.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. /*
  2. * Copyright (c) 2021, Cesar Torres <shortanemoia@protonmail.com>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include "SoundPlayerWidgetAdvancedView.h"
  27. #include "BarsVisualizationWidget.h"
  28. #include "Common.h"
  29. #include "M3UParser.h"
  30. #include "PlaybackManager.h"
  31. #include <AK/LexicalPath.h>
  32. #include <AK/SIMD.h>
  33. #include <LibGUI/Action.h>
  34. #include <LibGUI/BoxLayout.h>
  35. #include <LibGUI/Button.h>
  36. #include <LibGUI/Label.h>
  37. #include <LibGUI/MessageBox.h>
  38. #include <LibGUI/Slider.h>
  39. #include <LibGUI/ToolBar.h>
  40. #include <LibGUI/ToolBarContainer.h>
  41. #include <LibGUI/Window.h>
  42. #include <LibGfx/Bitmap.h>
  43. SoundPlayerWidgetAdvancedView::SoundPlayerWidgetAdvancedView(GUI::Window& window, PlayerState& state)
  44. : Player(state)
  45. , m_window(window)
  46. {
  47. window.resize(455, 350);
  48. window.set_minimum_size(600, 130);
  49. window.set_resizable(true);
  50. set_fill_with_background_color(true);
  51. set_layout<GUI::VerticalBoxLayout>();
  52. m_splitter = add<GUI::HorizontalSplitter>();
  53. m_player_view = m_splitter->add<GUI::Widget>();
  54. m_playlist_model = adopt(*new PlaylistModel());
  55. m_player_view->set_layout<GUI::VerticalBoxLayout>();
  56. m_play_icon = Gfx::Bitmap::load_from_file("/res/icons/16x16/play.png");
  57. m_pause_icon = Gfx::Bitmap::load_from_file("/res/icons/16x16/pause.png");
  58. m_stop_icon = Gfx::Bitmap::load_from_file("/res/icons/16x16/stop.png");
  59. m_back_icon = Gfx::Bitmap::load_from_file("/res/icons/16x16/go-back.png");
  60. m_next_icon = Gfx::Bitmap::load_from_file("/res/icons/16x16/go-forward.png");
  61. m_visualization = m_player_view->add<BarsVisualizationWidget>();
  62. m_playback_progress_slider = m_player_view->add<AutoSlider>(Orientation::Horizontal);
  63. m_playback_progress_slider->set_fixed_height(20);
  64. m_playback_progress_slider->set_min(0);
  65. m_playback_progress_slider->set_max(this->manager().total_length() * 44100); //this value should be set when we load a new file
  66. m_playback_progress_slider->on_knob_released = [&](int value) {
  67. this->manager().seek(value);
  68. };
  69. auto& toolbar_container = m_player_view->add<GUI::ToolBarContainer>();
  70. auto& menubar = toolbar_container.add<GUI::ToolBar>();
  71. m_play_button = menubar.add<GUI::Button>();
  72. m_play_button->set_icon(is_paused() ? (!has_loaded_file() ? *m_play_icon : *m_pause_icon) : *m_pause_icon);
  73. m_play_button->set_fixed_width(50);
  74. m_play_button->set_enabled(has_loaded_file());
  75. m_play_button->on_click = [&](unsigned) {
  76. bool paused = this->manager().toggle_pause();
  77. set_paused(paused);
  78. m_play_button->set_icon(paused ? *m_play_icon : *m_pause_icon);
  79. };
  80. m_stop_button = menubar.add<GUI::Button>();
  81. m_stop_button->set_icon(*m_stop_icon);
  82. m_stop_button->set_fixed_width(50);
  83. m_stop_button->set_enabled(has_loaded_file());
  84. m_stop_button->on_click = [&](unsigned) {
  85. this->manager().stop();
  86. set_stopped(true);
  87. m_play_button->set_icon(*m_play_icon);
  88. m_stop_button->set_enabled(false);
  89. };
  90. auto& timestamp_label = menubar.add<GUI::Label>();
  91. timestamp_label.set_fixed_width(110);
  92. timestamp_label.set_text("Elapsed: 00:00:00");
  93. // filler_label
  94. menubar.add<GUI::Label>();
  95. m_back_button = menubar.add<GUI::Button>();
  96. m_back_button->set_fixed_width(50);
  97. m_back_button->set_icon(*m_back_icon);
  98. m_back_button->set_enabled(has_loaded_file());
  99. m_back_button->on_click = [&](unsigned) {
  100. if (!m_playlist_model.is_null()) {
  101. auto it = m_playlist_model->items().find_if([&](const M3UEntry& e) { return e.path == loaded_filename(); });
  102. if (it.index() == 0) {
  103. open_file(m_playlist_model->items().at(m_playlist_model->items().size() - 1).path);
  104. } else
  105. open_file((it - 1)->path);
  106. play();
  107. }
  108. };
  109. m_next_button = menubar.add<GUI::Button>();
  110. m_next_button->set_fixed_width(50);
  111. m_next_button->set_icon(*m_next_icon);
  112. m_next_button->set_enabled(has_loaded_file());
  113. m_next_button->on_click = [&](unsigned) {
  114. if (!m_playlist_model.is_null()) {
  115. auto it = m_playlist_model->items().find_if([&](const M3UEntry& e) { return e.path == loaded_filename(); });
  116. if (it.index() + 1 == m_playlist_model->items().size()) {
  117. open_file(m_playlist_model->items().at(0).path);
  118. } else
  119. open_file((it + 1)->path);
  120. play();
  121. }
  122. };
  123. m_volume_label = &menubar.add<GUI::Label>();
  124. m_volume_label->set_fixed_width(30);
  125. m_volume_label->set_text("100%");
  126. auto& volume_slider = menubar.add<GUI::HorizontalSlider>();
  127. volume_slider.set_fixed_width(95);
  128. volume_slider.set_min(0);
  129. volume_slider.set_max(150);
  130. volume_slider.set_value(100);
  131. volume_slider.on_change = [&](int value) {
  132. double volume = m_nonlinear_volume_slider ? (double)(value * value) / (100 * 100) : value / 100.;
  133. m_volume_label->set_text(String::formatted("{}%", (int)(volume * 100)));
  134. set_volume(volume);
  135. };
  136. set_volume(1.);
  137. set_nonlinear_volume_slider(false);
  138. manager().on_update = [&]() {
  139. //TODO: make this program support other sample rates
  140. int samples_played = client_connection().get_played_samples() + this->manager().last_seek();
  141. int current_second = samples_played / 44100;
  142. timestamp_label.set_text(String::formatted("Elapsed: {:02}:{:02}:{:02}", current_second / 3600, current_second / 60, current_second % 60));
  143. m_playback_progress_slider->set_value(samples_played);
  144. dynamic_cast<Visualization*>(m_visualization.ptr())->set_buffer(this->manager().current_buffer());
  145. dynamic_cast<Visualization*>(m_visualization.ptr())->set_samplerate(loaded_file_samplerate());
  146. };
  147. manager().on_load_sample_buffer = [&](Audio::Buffer&) {
  148. //TODO: Implement an equalizer
  149. return;
  150. };
  151. manager().on_finished_playing = [&] {
  152. m_play_button->set_icon(*m_play_icon);
  153. if (looping()) {
  154. open_file(loaded_filename());
  155. return;
  156. }
  157. if (!m_playlist_model.is_null() && !m_playlist_model->items().is_empty()) {
  158. auto it = m_playlist_model->items().find_if([&](const M3UEntry& e) { return e.path == loaded_filename(); });
  159. if (it.index() + 1 == m_playlist_model->items().size()) {
  160. if (looping_playlist()) {
  161. open_file(m_playlist_model->items().at(0).path);
  162. return;
  163. }
  164. } else
  165. open_file((it + 1)->path);
  166. }
  167. };
  168. }
  169. void SoundPlayerWidgetAdvancedView::open_file(StringView path)
  170. {
  171. if (!Core::File::exists(path)) {
  172. GUI::MessageBox::show(window(), String::formatted("File \"{}\" does not exist", path), "Error opening file", GUI::MessageBox::Type::Error);
  173. return;
  174. }
  175. if (path.ends_with(".m3u", AK::CaseSensitivity::CaseInsensitive) || path.ends_with(".m3u8", AK::CaseSensitivity::CaseInsensitive)) {
  176. read_playlist(path);
  177. return;
  178. }
  179. NonnullRefPtr<Audio::Loader> loader = Audio::Loader::create(path);
  180. if (loader->has_error() || !loader->sample_rate()) {
  181. const String error_string = loader->error_string();
  182. GUI::MessageBox::show(&m_window, String::formatted("Failed to load audio file: {} ({})", path, error_string.is_null() ? "Unknown error" : error_string),
  183. "Filetype error", GUI::MessageBox::Type::Error);
  184. return;
  185. }
  186. m_window.set_title(String::formatted("{} - SoundPlayer", loader->file()->filename()));
  187. m_playback_progress_slider->set_max(loader->total_samples());
  188. m_playback_progress_slider->set_enabled(true);
  189. m_play_button->set_enabled(true);
  190. m_stop_button->set_enabled(true);
  191. manager().set_loader(move(loader));
  192. set_has_loaded_file(true);
  193. set_loaded_filename(path);
  194. }
  195. void SoundPlayerWidgetAdvancedView::set_nonlinear_volume_slider(bool nonlinear)
  196. {
  197. m_nonlinear_volume_slider = nonlinear;
  198. }
  199. void SoundPlayerWidgetAdvancedView::drop_event(GUI::DropEvent& event)
  200. {
  201. event.accept();
  202. window()->move_to_front();
  203. if (event.mime_data().has_urls()) {
  204. auto urls = event.mime_data().urls();
  205. if (urls.is_empty())
  206. return;
  207. open_file(urls.first().path());
  208. }
  209. }
  210. SoundPlayerWidgetAdvancedView::~SoundPlayerWidgetAdvancedView()
  211. {
  212. manager().on_load_sample_buffer = nullptr;
  213. manager().on_update = nullptr;
  214. }
  215. void SoundPlayerWidgetAdvancedView::play()
  216. {
  217. manager().play();
  218. set_paused(false);
  219. set_stopped(false);
  220. }
  221. void SoundPlayerWidgetAdvancedView::read_playlist(StringView path)
  222. {
  223. auto parser = M3UParser::from_file(path);
  224. auto items = parser->parse(true);
  225. VERIFY(items->size() > 0);
  226. try_fill_missing_info(*items, path);
  227. for (auto& item : *items)
  228. m_playlist_model->items().append(item);
  229. set_playlist_visible(true);
  230. m_playlist_model->update();
  231. open_file(items->at(0).path);
  232. if (items->size() > 1) {
  233. m_back_button->set_enabled(true);
  234. m_next_button->set_enabled(true);
  235. } else {
  236. m_back_button->set_enabled(false);
  237. m_next_button->set_enabled(false);
  238. }
  239. }
  240. void SoundPlayerWidgetAdvancedView::set_playlist_visible(bool visible)
  241. {
  242. if (visible) {
  243. m_playlist_widget = m_player_view->parent_widget()->add<PlaylistWidget>();
  244. m_playlist_widget->set_data_model(m_playlist_model);
  245. m_playlist_widget->set_fixed_width(150);
  246. } else {
  247. m_playlist_widget->remove_from_parent();
  248. m_player_view->set_max_width(window()->width());
  249. }
  250. }
  251. void SoundPlayerWidgetAdvancedView::try_fill_missing_info(Vector<M3UEntry>& entries, StringView playlist_p)
  252. {
  253. LexicalPath playlist_path(playlist_p);
  254. Vector<M3UEntry*> to_delete;
  255. for (auto& entry : entries) {
  256. LexicalPath entry_path(entry.path);
  257. if (!entry_path.is_absolute()) {
  258. entry.path = String::formatted("{}/{}", playlist_path.dirname(), entry_path.basename());
  259. }
  260. if (!Core::File::exists(entry.path)) {
  261. 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.basename()), "Error reading playlist", GUI::MessageBox::Type::Warning);
  262. to_delete.append(&entry);
  263. continue;
  264. }
  265. if (!entry.extended_info->track_display_title.has_value())
  266. entry.extended_info->track_display_title = LexicalPath(entry.path).title();
  267. if (!entry.extended_info->track_length_in_seconds.has_value()) {
  268. if (entry_path.has_extension("wav")) {
  269. auto wav_reader = Audio::Loader::create(entry.path);
  270. entry.extended_info->track_length_in_seconds = wav_reader->total_samples() / wav_reader->sample_rate();
  271. }
  272. //TODO: Implement embedded metadata extractor for other audio formats
  273. }
  274. //TODO: Implement a metadata parser for the uncomfortably numerous popular embedded metadata formats
  275. if (!entry.extended_info->file_size_in_bytes.has_value()) {
  276. FILE* f = fopen(entry.path.characters(), "r");
  277. VERIFY(f != nullptr);
  278. fseek(f, 0, SEEK_END);
  279. entry.extended_info->file_size_in_bytes = ftell(f);
  280. fclose(f);
  281. }
  282. }
  283. for (M3UEntry* entry : to_delete)
  284. entries.remove_first_matching([&](M3UEntry& e) { return &e == entry; });
  285. }