SoundPlayerWidgetAdvancedView.cpp 13 KB

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