The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

712 lines
27KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE examples.
  4. Copyright (c) 2022 - Raw Material Software Limited
  5. The code included in this file is provided under the terms of the ISC license
  6. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  7. To use, copy, modify, and/or distribute this software for any purpose with or
  8. without fee is hereby granted provided that the above copyright notice and
  9. this permission notice appear in all copies.
  10. THE SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES,
  11. WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR
  12. PURPOSE, ARE DISCLAIMED.
  13. ==============================================================================
  14. */
  15. /*******************************************************************************
  16. The block below describes the properties of this PIP. A PIP is a short snippet
  17. of code that can be read by the Projucer and used to generate a JUCE project.
  18. BEGIN_JUCE_PIP_METADATA
  19. name: VideoDemo
  20. version: 1.0.0
  21. vendor: JUCE
  22. website: http://juce.com
  23. description: Plays video files.
  24. dependencies: juce_core, juce_data_structures, juce_events, juce_graphics,
  25. juce_gui_basics, juce_gui_extra, juce_video
  26. exporters: xcode_mac, vs2022, androidstudio, xcode_iphone
  27. moduleFlags: JUCE_STRICT_REFCOUNTEDPOINTER=1
  28. type: Component
  29. mainClass: VideoDemo
  30. useLocalCopy: 1
  31. END_JUCE_PIP_METADATA
  32. *******************************************************************************/
  33. #pragma once
  34. #include "../Assets/DemoUtilities.h"
  35. #if JUCE_MAC || JUCE_WINDOWS
  36. //==============================================================================
  37. // so that we can easily have two video windows each with a file browser, wrap this up as a class..
  38. class MovieComponentWithFileBrowser final : public Component,
  39. public DragAndDropTarget,
  40. private FilenameComponentListener
  41. {
  42. public:
  43. MovieComponentWithFileBrowser()
  44. : videoComp (true)
  45. {
  46. addAndMakeVisible (videoComp);
  47. addAndMakeVisible (fileChooser);
  48. fileChooser.addListener (this);
  49. fileChooser.setBrowseButtonText ("browse");
  50. }
  51. void setFile (const File& file)
  52. {
  53. fileChooser.setCurrentFile (file, true);
  54. }
  55. void paintOverChildren (Graphics& g) override
  56. {
  57. if (isDragOver)
  58. {
  59. g.setColour (Colours::red);
  60. g.drawRect (fileChooser.getBounds(), 2);
  61. }
  62. }
  63. void resized() override
  64. {
  65. videoComp.setBounds (getLocalBounds().reduced (10));
  66. }
  67. bool isInterestedInDragSource (const SourceDetails&) override { return true; }
  68. void itemDragEnter (const SourceDetails&) override
  69. {
  70. isDragOver = true;
  71. repaint();
  72. }
  73. void itemDragExit (const SourceDetails&) override
  74. {
  75. isDragOver = false;
  76. repaint();
  77. }
  78. void itemDropped (const SourceDetails& dragSourceDetails) override
  79. {
  80. setFile (dragSourceDetails.description.toString());
  81. isDragOver = false;
  82. repaint();
  83. }
  84. private:
  85. VideoComponent videoComp;
  86. bool isDragOver = false;
  87. FilenameComponent fileChooser { "movie", {}, true, false, false, "*", {}, "(choose a video file to play)"};
  88. void filenameComponentChanged (FilenameComponent*) override
  89. {
  90. auto url = URL (fileChooser.getCurrentFile());
  91. // this is called when the user changes the filename in the file chooser box
  92. auto result = videoComp.load (url);
  93. videoLoadingFinished (url, result);
  94. }
  95. void videoLoadingFinished (const URL& url, Result result)
  96. {
  97. ignoreUnused (url);
  98. if (result.wasOk())
  99. {
  100. // loaded the file ok, so let's start it playing..
  101. videoComp.play();
  102. resized(); // update to reflect the video's aspect ratio
  103. }
  104. else
  105. {
  106. auto options = MessageBoxOptions::makeOptionsOk (MessageBoxIconType::WarningIcon,
  107. "Couldn't load the file!",
  108. result.getErrorMessage());
  109. messageBox = AlertWindow::showScopedAsync (options, nullptr);
  110. }
  111. }
  112. ScopedMessageBox messageBox;
  113. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MovieComponentWithFileBrowser)
  114. };
  115. //==============================================================================
  116. class VideoDemo final : public Component,
  117. public DragAndDropContainer,
  118. private FileBrowserListener
  119. {
  120. public:
  121. VideoDemo()
  122. {
  123. setOpaque (true);
  124. movieList.setDirectory (File::getSpecialLocation (File::userMoviesDirectory), true, true);
  125. directoryThread.startThread (Thread::Priority::background);
  126. fileTree.setTitle ("Files");
  127. fileTree.addListener (this);
  128. fileTree.setColour (FileTreeComponent::backgroundColourId, Colours::lightgrey.withAlpha (0.6f));
  129. addAndMakeVisible (fileTree);
  130. addAndMakeVisible (resizerBar);
  131. loadLeftButton .onClick = [this] { movieCompLeft .setFile (fileTree.getSelectedFile (0)); };
  132. loadRightButton.onClick = [this] { movieCompRight.setFile (fileTree.getSelectedFile (0)); };
  133. addAndMakeVisible (loadLeftButton);
  134. addAndMakeVisible (loadRightButton);
  135. addAndMakeVisible (movieCompLeft);
  136. addAndMakeVisible (movieCompRight);
  137. // we have to set up our StretchableLayoutManager so it know the limits and preferred sizes of it's contents
  138. stretchableManager.setItemLayout (0, // for the fileTree
  139. -0.1, -0.9, // must be between 50 pixels and 90% of the available space
  140. -0.3); // and its preferred size is 30% of the total available space
  141. stretchableManager.setItemLayout (1, // for the resize bar
  142. 5, 5, 5); // hard limit to 5 pixels
  143. stretchableManager.setItemLayout (2, // for the movie components
  144. -0.1, -0.9, // size must be between 50 pixels and 90% of the available space
  145. -0.7); // and its preferred size is 70% of the total available space
  146. setSize (500, 500);
  147. }
  148. ~VideoDemo() override
  149. {
  150. fileTree.removeListener (this);
  151. }
  152. void paint (Graphics& g) override
  153. {
  154. g.fillAll (getUIColourIfAvailable (LookAndFeel_V4::ColourScheme::UIColour::windowBackground));
  155. }
  156. void resized() override
  157. {
  158. // make a list of two of our child components that we want to reposition
  159. Component* comps[] = { &fileTree, &resizerBar, nullptr };
  160. // this will position the 3 components, one above the other, to fit
  161. // vertically into the rectangle provided.
  162. stretchableManager.layOutComponents (comps, 3,
  163. 0, 0, getWidth(), getHeight(),
  164. true, true);
  165. // now position out two video components in the space that's left
  166. auto area = getLocalBounds().removeFromBottom (getHeight() - resizerBar.getBottom());
  167. {
  168. auto buttonArea = area.removeFromTop (30);
  169. loadLeftButton .setBounds (buttonArea.removeFromLeft (buttonArea.getWidth() / 2).reduced (5));
  170. loadRightButton.setBounds (buttonArea.reduced (5));
  171. }
  172. movieCompLeft .setBounds (area.removeFromLeft (area.getWidth() / 2).reduced (5));
  173. movieCompRight.setBounds (area.reduced (5));
  174. }
  175. private:
  176. std::unique_ptr<FileChooser> fileChooser;
  177. WildcardFileFilter moviesWildcardFilter { "*", "*", "Movies File Filter" };
  178. TimeSliceThread directoryThread { "Movie File Scanner Thread" };
  179. DirectoryContentsList movieList { &moviesWildcardFilter, directoryThread };
  180. FileTreeComponent fileTree { movieList };
  181. StretchableLayoutManager stretchableManager;
  182. StretchableLayoutResizerBar resizerBar { &stretchableManager, 1, false };
  183. TextButton loadLeftButton { "Load Left" },
  184. loadRightButton { "Load Right" };
  185. MovieComponentWithFileBrowser movieCompLeft, movieCompRight;
  186. void selectionChanged() override
  187. {
  188. // we're just going to update the drag description of out tree so that rows can be dragged onto the file players
  189. fileTree.setDragAndDropDescription (fileTree.getSelectedFile().getFullPathName());
  190. }
  191. void fileClicked (const File&, const MouseEvent&) override {}
  192. void fileDoubleClicked (const File&) override {}
  193. void browserRootChanged (const File&) override {}
  194. void selectVideoFile()
  195. {
  196. fileChooser.reset (new FileChooser ("Choose a file to open...", File::getCurrentWorkingDirectory(),
  197. "*", false));
  198. fileChooser->launchAsync (FileBrowserComponent::openMode | FileBrowserComponent::canSelectFiles,
  199. [this] (const FileChooser& chooser)
  200. {
  201. String chosen;
  202. auto results = chooser.getURLResults();
  203. // TODO: support non local files too
  204. if (results.size() > 0)
  205. movieCompLeft.setFile (results[0].getLocalFile());
  206. });
  207. }
  208. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VideoDemo)
  209. };
  210. #elif JUCE_IOS || JUCE_ANDROID
  211. //==============================================================================
  212. class VideoDemo final : public Component,
  213. private Timer
  214. {
  215. public:
  216. VideoDemo()
  217. : videoCompWithNativeControls (true),
  218. videoCompNoNativeControls (false)
  219. {
  220. loadLocalButton .onClick = [this] { selectVideoFile(); };
  221. loadUrlButton .onClick = [this] { showVideoUrlPrompt(); };
  222. seekToStartButton.onClick = [this] { seekVideoToStart(); };
  223. playButton .onClick = [this] { playVideo(); };
  224. pauseButton .onClick = [this] { pauseVideo(); };
  225. unloadButton .onClick = [this] { unloadVideoFile(); };
  226. volumeLabel .setColour (Label::textColourId, Colours::white);
  227. currentPositionLabel.setColour (Label::textColourId, Colours::white);
  228. volumeLabel .setJustificationType (Justification::right);
  229. currentPositionLabel.setJustificationType (Justification::right);
  230. volumeSlider .setRange (0.0, 1.0);
  231. positionSlider.setRange (0.0, 1.0);
  232. volumeSlider .setSliderSnapsToMousePosition (false);
  233. positionSlider.setSliderSnapsToMousePosition (false);
  234. volumeSlider.setSkewFactor (1.5);
  235. volumeSlider.setValue (1.0, dontSendNotification);
  236. #if JUCE_SYNC_VIDEO_VOLUME_WITH_OS_MEDIA_VOLUME
  237. curVideoComp->onGlobalMediaVolumeChanged = [this]() { volumeSlider.setValue (curVideoComp->getAudioVolume(), dontSendNotification); };
  238. #endif
  239. volumeSlider .onValueChange = [this]() { curVideoComp->setAudioVolume ((float) volumeSlider.getValue()); };
  240. positionSlider.onValueChange = [this]() { seekVideoToNormalisedPosition (positionSlider.getValue()); };
  241. positionSlider.onDragStart = [this]()
  242. {
  243. positionSliderDragging = true;
  244. wasPlayingBeforeDragStart = curVideoComp->isPlaying();
  245. if (wasPlayingBeforeDragStart)
  246. curVideoComp->stop();
  247. };
  248. positionSlider.onDragEnd = [this]()
  249. {
  250. if (wasPlayingBeforeDragStart)
  251. curVideoComp->play();
  252. wasPlayingBeforeDragStart = false;
  253. // Ensure the slider does not temporarily jump back on consecutive timer callback.
  254. Timer::callAfterDelay (500, [this]() { positionSliderDragging = false; });
  255. };
  256. playSpeedComboBox.addItem ("25%", 25);
  257. playSpeedComboBox.addItem ("50%", 50);
  258. playSpeedComboBox.addItem ("100%", 100);
  259. playSpeedComboBox.addItem ("200%", 200);
  260. playSpeedComboBox.addItem ("400%", 400);
  261. playSpeedComboBox.setSelectedId (100, dontSendNotification);
  262. playSpeedComboBox.onChange = [this]() { curVideoComp->setPlaySpeed (playSpeedComboBox.getSelectedId() / 100.0); };
  263. setTransportControlsEnabled (false);
  264. addAndMakeVisible (loadLocalButton);
  265. addAndMakeVisible (loadUrlButton);
  266. addAndMakeVisible (volumeLabel);
  267. addAndMakeVisible (volumeSlider);
  268. addChildComponent (videoCompWithNativeControls);
  269. addChildComponent (videoCompNoNativeControls);
  270. addAndMakeVisible (positionSlider);
  271. addAndMakeVisible (currentPositionLabel);
  272. addAndMakeVisible (playSpeedComboBox);
  273. addAndMakeVisible (seekToStartButton);
  274. addAndMakeVisible (playButton);
  275. addAndMakeVisible (unloadButton);
  276. addChildComponent (pauseButton);
  277. setSize (500, 500);
  278. RuntimePermissions::request (RuntimePermissions::readExternalStorage,
  279. [] (bool granted)
  280. {
  281. if (! granted)
  282. {
  283. AlertWindow::showMessageBoxAsync (MessageBoxIconType::WarningIcon,
  284. "Permissions warning",
  285. "External storage access permission not granted, some files"
  286. " may be inaccessible.");
  287. }
  288. });
  289. setPortraitOrientationEnabled (true);
  290. }
  291. ~VideoDemo() override
  292. {
  293. curVideoComp->onPlaybackStarted = nullptr;
  294. curVideoComp->onPlaybackStopped = nullptr;
  295. curVideoComp->onErrorOccurred = nullptr;
  296. curVideoComp->onGlobalMediaVolumeChanged = nullptr;
  297. setPortraitOrientationEnabled (false);
  298. }
  299. void paint (Graphics& g) override
  300. {
  301. g.fillAll (getUIColourIfAvailable (LookAndFeel_V4::ColourScheme::UIColour::windowBackground));
  302. }
  303. void resized() override
  304. {
  305. auto area = getLocalBounds();
  306. int marginSize = 5;
  307. int buttonHeight = 20;
  308. area.reduce (0, marginSize);
  309. auto topArea = area.removeFromTop (buttonHeight);
  310. loadLocalButton.setBounds (topArea.removeFromLeft (topArea.getWidth() / 6));
  311. loadUrlButton.setBounds (topArea.removeFromLeft (loadLocalButton.getWidth()));
  312. volumeLabel.setBounds (topArea.removeFromLeft (loadLocalButton.getWidth()));
  313. volumeSlider.setBounds (topArea.reduced (10, 0));
  314. auto transportArea = area.removeFromBottom (buttonHeight);
  315. auto positionArea = area.removeFromBottom (buttonHeight).reduced (marginSize, 0);
  316. playSpeedComboBox.setBounds (transportArea.removeFromLeft (jmax (50, transportArea.getWidth() / 5)));
  317. auto controlWidth = transportArea.getWidth() / 3;
  318. currentPositionLabel.setBounds (positionArea.removeFromRight (jmax (150, controlWidth)));
  319. positionSlider.setBounds (positionArea);
  320. seekToStartButton.setBounds (transportArea.removeFromLeft (controlWidth));
  321. playButton .setBounds (transportArea.removeFromLeft (controlWidth));
  322. unloadButton .setBounds (transportArea.removeFromLeft (controlWidth));
  323. pauseButton.setBounds (playButton.getBounds());
  324. area.removeFromTop (marginSize);
  325. area.removeFromBottom (marginSize);
  326. videoCompWithNativeControls.setBounds (area);
  327. videoCompNoNativeControls.setBounds (area);
  328. if (positionSlider.getWidth() > 0)
  329. positionSlider.setMouseDragSensitivity (positionSlider.getWidth());
  330. }
  331. private:
  332. TextButton loadLocalButton { "Load Local" };
  333. TextButton loadUrlButton { "Load URL" };
  334. Label volumeLabel { "volumeLabel", "Vol:" };
  335. Slider volumeSlider { Slider::LinearHorizontal, Slider::NoTextBox };
  336. VideoComponent videoCompWithNativeControls;
  337. VideoComponent videoCompNoNativeControls;
  338. #if JUCE_IOS || JUCE_MAC
  339. VideoComponent* curVideoComp = &videoCompWithNativeControls;
  340. #else
  341. VideoComponent* curVideoComp = &videoCompNoNativeControls;
  342. #endif
  343. bool isFirstSetup = true;
  344. Slider positionSlider { Slider::LinearHorizontal, Slider::NoTextBox };
  345. bool positionSliderDragging = false;
  346. bool wasPlayingBeforeDragStart = false;
  347. Label currentPositionLabel { "currentPositionLabel", "-:- / -:-" };
  348. ComboBox playSpeedComboBox { "playSpeedComboBox" };
  349. TextButton seekToStartButton { "|<" };
  350. TextButton playButton { "Play" };
  351. TextButton pauseButton { "Pause" };
  352. TextButton unloadButton { "Unload" };
  353. std::unique_ptr<FileChooser> fileChooser;
  354. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VideoDemo)
  355. JUCE_DECLARE_WEAK_REFERENCEABLE (VideoDemo)
  356. //==============================================================================
  357. void setPortraitOrientationEnabled (bool shouldBeEnabled)
  358. {
  359. auto allowedOrientations = Desktop::getInstance().getOrientationsEnabled();
  360. if (shouldBeEnabled)
  361. allowedOrientations |= Desktop::upright;
  362. else
  363. allowedOrientations &= ~Desktop::upright;
  364. Desktop::getInstance().setOrientationsEnabled (allowedOrientations);
  365. }
  366. void setTransportControlsEnabled (bool shouldBeEnabled)
  367. {
  368. positionSlider .setEnabled (shouldBeEnabled);
  369. playSpeedComboBox.setEnabled (shouldBeEnabled);
  370. seekToStartButton.setEnabled (shouldBeEnabled);
  371. playButton .setEnabled (shouldBeEnabled);
  372. unloadButton .setEnabled (shouldBeEnabled);
  373. pauseButton .setEnabled (shouldBeEnabled);
  374. }
  375. void selectVideoFile()
  376. {
  377. fileChooser.reset (new FileChooser ("Choose a video file to open...", File::getCurrentWorkingDirectory(),
  378. "*", true));
  379. fileChooser->launchAsync (FileBrowserComponent::openMode | FileBrowserComponent::canSelectFiles,
  380. [this] (const FileChooser& chooser)
  381. {
  382. auto results = chooser.getURLResults();
  383. if (results.size() > 0)
  384. loadVideo (results[0]);
  385. });
  386. }
  387. void loadVideo (const URL& url)
  388. {
  389. unloadVideoFile();
  390. #if JUCE_IOS || JUCE_MAC
  391. askIfUseNativeControls (url);
  392. #else
  393. loadUrl (url);
  394. setupVideoComp (false);
  395. #endif
  396. }
  397. void askIfUseNativeControls (const URL& url)
  398. {
  399. auto* aw = new AlertWindow ("Choose viewer type", {}, MessageBoxIconType::NoIcon);
  400. aw->addButton ("Yes", 1, KeyPress (KeyPress::returnKey));
  401. aw->addButton ("No", 0, KeyPress (KeyPress::escapeKey));
  402. aw->addTextBlock ("Do you want to use the viewer with native controls?");
  403. auto callback = ModalCallbackFunction::forComponent (videoViewerTypeChosen, this, url);
  404. aw->enterModalState (true, callback, true);
  405. }
  406. static void videoViewerTypeChosen (int result, VideoDemo* owner, URL url)
  407. {
  408. if (owner != nullptr)
  409. {
  410. owner->setupVideoComp (result != 0);
  411. owner->loadUrl (url);
  412. }
  413. }
  414. void setupVideoComp (bool useNativeViewerWithNativeControls)
  415. {
  416. auto* oldVideoComp = curVideoComp;
  417. if (useNativeViewerWithNativeControls)
  418. curVideoComp = &videoCompWithNativeControls;
  419. else
  420. curVideoComp = &videoCompNoNativeControls;
  421. if (isFirstSetup || oldVideoComp != curVideoComp)
  422. {
  423. oldVideoComp->onPlaybackStarted = nullptr;
  424. oldVideoComp->onPlaybackStopped = nullptr;
  425. oldVideoComp->onErrorOccurred = nullptr;
  426. oldVideoComp->setVisible (false);
  427. curVideoComp->onPlaybackStarted = [this]() { processPlaybackStarted(); };
  428. curVideoComp->onPlaybackStopped = [this]() { processPlaybackPaused(); };
  429. curVideoComp->onErrorOccurred = [this] (const String& errorMessage) { errorOccurred (errorMessage); };
  430. curVideoComp->setVisible (true);
  431. #if JUCE_SYNC_VIDEO_VOLUME_WITH_OS_MEDIA_VOLUME
  432. oldVideoComp->onGlobalMediaVolumeChanged = nullptr;
  433. curVideoComp->onGlobalMediaVolumeChanged = [this]() { volumeSlider.setValue (curVideoComp->getAudioVolume(), dontSendNotification); };
  434. #endif
  435. }
  436. isFirstSetup = false;
  437. }
  438. void loadUrl (const URL& url)
  439. {
  440. curVideoComp->loadAsync (url, [this] (const URL& u, Result r) { videoLoadingFinished (u, r); });
  441. }
  442. void showVideoUrlPrompt()
  443. {
  444. auto* aw = new AlertWindow ("Enter URL for video to load", {}, MessageBoxIconType::NoIcon);
  445. aw->addButton ("OK", 1, KeyPress (KeyPress::returnKey));
  446. aw->addButton ("Cancel", 0, KeyPress (KeyPress::escapeKey));
  447. aw->addTextEditor ("videoUrlTextEditor", "https://www.rmp-streaming.com/media/bbb-360p.mp4");
  448. auto callback = ModalCallbackFunction::forComponent (videoUrlPromptClosed, this, Component::SafePointer<AlertWindow> (aw));
  449. aw->enterModalState (true, callback, true);
  450. }
  451. static void videoUrlPromptClosed (int result, VideoDemo* owner, Component::SafePointer<AlertWindow> aw)
  452. {
  453. if (result != 0 && owner != nullptr && aw != nullptr)
  454. {
  455. auto url = aw->getTextEditorContents ("videoUrlTextEditor");
  456. if (url.isNotEmpty())
  457. owner->loadVideo (url);
  458. }
  459. }
  460. void videoLoadingFinished (const URL& url, Result result)
  461. {
  462. ignoreUnused (url);
  463. if (result.wasOk())
  464. {
  465. resized(); // update to reflect the video's aspect ratio
  466. setTransportControlsEnabled (true);
  467. currentPositionLabel.setText (getPositionString (0.0, curVideoComp->getVideoDuration()), sendNotification);
  468. positionSlider.setValue (0.0, dontSendNotification);
  469. playSpeedComboBox.setSelectedId (100, dontSendNotification);
  470. }
  471. else
  472. {
  473. AlertWindow::showMessageBoxAsync (MessageBoxIconType::WarningIcon,
  474. "Couldn't load the file!",
  475. result.getErrorMessage());
  476. }
  477. }
  478. static String getPositionString (double playPositionSeconds, double durationSeconds)
  479. {
  480. auto positionMs = static_cast<int> (1000 * playPositionSeconds);
  481. int posMinutes = positionMs / 60000;
  482. int posSeconds = (positionMs % 60000) / 1000;
  483. int posMillis = positionMs % 1000;
  484. auto totalMs = static_cast<int> (1000 * durationSeconds);
  485. int totMinutes = totalMs / 60000;
  486. int totSeconds = (totalMs % 60000) / 1000;
  487. int totMillis = totalMs % 1000;
  488. return String::formatted ("%02d:%02d:%03d / %02d:%02d:%03d",
  489. posMinutes, posSeconds, posMillis,
  490. totMinutes, totSeconds, totMillis);
  491. }
  492. void updatePositionSliderAndLabel()
  493. {
  494. auto position = curVideoComp->getPlayPosition();
  495. auto duration = curVideoComp->getVideoDuration();
  496. currentPositionLabel.setText (getPositionString (position, duration), sendNotification);
  497. if (! positionSliderDragging)
  498. positionSlider.setValue (approximatelyEqual (duration, 0.0) ? 0.0 : (position / duration), dontSendNotification);
  499. }
  500. void seekVideoToStart()
  501. {
  502. seekVideoToNormalisedPosition (0.0);
  503. }
  504. void seekVideoToNormalisedPosition (double normalisedPos)
  505. {
  506. normalisedPos = jlimit (0.0, 1.0, normalisedPos);
  507. auto duration = curVideoComp->getVideoDuration();
  508. auto newPos = jlimit (0.0, duration, duration * normalisedPos);
  509. curVideoComp->setPlayPosition (newPos);
  510. currentPositionLabel.setText (getPositionString (newPos, curVideoComp->getVideoDuration()), sendNotification);
  511. positionSlider.setValue (normalisedPos, dontSendNotification);
  512. }
  513. void playVideo()
  514. {
  515. curVideoComp->play();
  516. }
  517. void processPlaybackStarted()
  518. {
  519. playButton.setVisible (false);
  520. pauseButton.setVisible (true);
  521. startTimer (20);
  522. }
  523. void pauseVideo()
  524. {
  525. curVideoComp->stop();
  526. }
  527. void processPlaybackPaused()
  528. {
  529. // On seeking to a new pos, the playback may be temporarily paused.
  530. if (positionSliderDragging)
  531. return;
  532. pauseButton.setVisible (false);
  533. playButton.setVisible (true);
  534. }
  535. void errorOccurred (const String& errorMessage)
  536. {
  537. AlertWindow::showMessageBoxAsync (MessageBoxIconType::InfoIcon,
  538. "An error has occurred",
  539. errorMessage + ", video will be unloaded.");
  540. unloadVideoFile();
  541. }
  542. void unloadVideoFile()
  543. {
  544. curVideoComp->closeVideo();
  545. setTransportControlsEnabled (false);
  546. stopTimer();
  547. pauseButton.setVisible (false);
  548. playButton.setVisible (true);
  549. currentPositionLabel.setText ("-:- / -:-", sendNotification);
  550. positionSlider.setValue (0.0, dontSendNotification);
  551. }
  552. void timerCallback() override
  553. {
  554. updatePositionSliderAndLabel();
  555. }
  556. };
  557. #elif JUCE_LINUX || JUCE_BSD
  558. #error "This demo is not supported on Linux!"
  559. #endif