CMusicHandler.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746
  1. /*
  2. * CMusicHandler.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include <SDL_mixer.h>
  12. #include <SDL_timer.h>
  13. #include "CMusicHandler.h"
  14. #include "CGameInfo.h"
  15. #include "renderSDL/SDLRWwrapper.h"
  16. #include "eventsSDL/InputHandler.h"
  17. #include "gui/CGuiHandler.h"
  18. #include "../lib/JsonNode.h"
  19. #include "../lib/GameConstants.h"
  20. #include "../lib/filesystem/Filesystem.h"
  21. #include "../lib/constants/StringConstants.h"
  22. #include "../lib/CRandomGenerator.h"
  23. #include "../lib/VCMIDirs.h"
  24. #include "../lib/TerrainHandler.h"
  25. #define VCMI_SOUND_NAME(x)
  26. #define VCMI_SOUND_FILE(y) #y,
  27. // sounds mapped to soundBase enum
  28. static std::string sounds[] = {
  29. "", // invalid
  30. "", // todo
  31. VCMI_SOUND_LIST
  32. };
  33. #undef VCMI_SOUND_NAME
  34. #undef VCMI_SOUND_FILE
  35. void CAudioBase::init()
  36. {
  37. if (initialized)
  38. return;
  39. if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 1024)==-1)
  40. {
  41. logGlobal->error("Mix_OpenAudio error: %s", Mix_GetError());
  42. return;
  43. }
  44. initialized = true;
  45. }
  46. void CAudioBase::release()
  47. {
  48. if(!(CCS->soundh->initialized && CCS->musich->initialized))
  49. Mix_CloseAudio();
  50. initialized = false;
  51. }
  52. void CAudioBase::setVolume(ui32 percent)
  53. {
  54. if (percent > 100)
  55. percent = 100;
  56. volume = percent;
  57. }
  58. void CSoundHandler::onVolumeChange(const JsonNode &volumeNode)
  59. {
  60. setVolume((ui32)volumeNode.Float());
  61. }
  62. CSoundHandler::CSoundHandler():
  63. listener(settings.listen["general"]["sound"]),
  64. ambientConfig(JsonPath::builtin("config/ambientSounds.json"))
  65. {
  66. listener(std::bind(&CSoundHandler::onVolumeChange, this, _1));
  67. battleIntroSounds =
  68. {
  69. soundBase::battle00, soundBase::battle01,
  70. soundBase::battle02, soundBase::battle03, soundBase::battle04,
  71. soundBase::battle05, soundBase::battle06, soundBase::battle07
  72. };
  73. }
  74. void CSoundHandler::init()
  75. {
  76. CAudioBase::init();
  77. if(ambientConfig["allocateChannels"].isNumber())
  78. Mix_AllocateChannels((int)ambientConfig["allocateChannels"].Integer());
  79. if (initialized)
  80. {
  81. Mix_ChannelFinished([](int channel)
  82. {
  83. CCS->soundh->soundFinishedCallback(channel);
  84. });
  85. }
  86. }
  87. void CSoundHandler::release()
  88. {
  89. if (initialized)
  90. {
  91. Mix_HaltChannel(-1);
  92. for (auto &chunk : soundChunks)
  93. {
  94. if (chunk.second.first)
  95. Mix_FreeChunk(chunk.second.first);
  96. }
  97. }
  98. CAudioBase::release();
  99. }
  100. // Allocate an SDL chunk and cache it.
  101. Mix_Chunk *CSoundHandler::GetSoundChunk(const AudioPath & sound, bool cache)
  102. {
  103. try
  104. {
  105. if (cache && soundChunks.find(sound) != soundChunks.end())
  106. return soundChunks[sound].first;
  107. auto data = CResourceHandler::get()->load(sound.addPrefix("SOUNDS/"))->readAll();
  108. SDL_RWops *ops = SDL_RWFromMem(data.first.get(), (int)data.second);
  109. Mix_Chunk *chunk = Mix_LoadWAV_RW(ops, 1); // will free ops
  110. if (cache)
  111. soundChunks.insert({sound, std::make_pair (chunk, std::move (data.first))});
  112. return chunk;
  113. }
  114. catch(std::exception &e)
  115. {
  116. logGlobal->warn("Cannot get sound %s chunk: %s", sound.getOriginalName(), e.what());
  117. return nullptr;
  118. }
  119. }
  120. Mix_Chunk *CSoundHandler::GetSoundChunk(std::pair<std::unique_ptr<ui8 []>, si64> & data, bool cache)
  121. {
  122. try
  123. {
  124. std::vector<ui8> startBytes = std::vector<ui8>(data.first.get(), data.first.get() + std::min((si64)100, data.second));
  125. if (cache && soundChunksRaw.find(startBytes) != soundChunksRaw.end())
  126. return soundChunksRaw[startBytes].first;
  127. SDL_RWops *ops = SDL_RWFromMem(data.first.get(), (int)data.second);
  128. Mix_Chunk *chunk = Mix_LoadWAV_RW(ops, 1); // will free ops
  129. if (cache)
  130. soundChunksRaw.insert({startBytes, std::make_pair (chunk, std::move (data.first))});
  131. return chunk;
  132. }
  133. catch(std::exception &e)
  134. {
  135. logGlobal->warn("Cannot get sound chunk: %s", e.what());
  136. return nullptr;
  137. }
  138. }
  139. int CSoundHandler::ambientDistToVolume(int distance) const
  140. {
  141. const auto & distancesVector = ambientConfig["distances"].Vector();
  142. if(distance >= distancesVector.size())
  143. return 0;
  144. int volume = static_cast<int>(distancesVector[distance].Integer());
  145. return volume * (int)ambientConfig["volume"].Integer() / 100;
  146. }
  147. void CSoundHandler::ambientStopSound(const AudioPath & soundId)
  148. {
  149. stopSound(ambientChannels[soundId]);
  150. setChannelVolume(ambientChannels[soundId], volume);
  151. }
  152. double CSoundHandler::getSoundDuration(const AudioPath & sound)
  153. {
  154. if (!initialized || sound.empty())
  155. return 0.0;
  156. auto data = CResourceHandler::get()->load(sound.addPrefix("SOUNDS/"))->readAll();
  157. SDL_AudioSpec spec;
  158. uint32_t audioLen;
  159. uint8_t *audioBuf;
  160. double seconds = 0.0;
  161. if(SDL_LoadWAV_RW(SDL_RWFromMem(data.first.get(), (int)data.second), 1, &spec, &audioBuf, &audioLen) != nullptr)
  162. {
  163. SDL_FreeWAV(audioBuf);
  164. uint32_t sampleSize = SDL_AUDIO_BITSIZE(spec.format) / 8;
  165. uint32_t sampleCount = audioLen / sampleSize;
  166. uint32_t sampleLen = 0;
  167. if(spec.channels)
  168. sampleLen = sampleCount / spec.channels;
  169. else
  170. sampleLen = sampleCount;
  171. seconds = (double)sampleLen / (double)spec.freq;
  172. }
  173. return seconds;
  174. }
  175. // Plays a sound, and return its channel so we can fade it out later
  176. int CSoundHandler::playSound(soundBase::soundID soundID, int repeats)
  177. {
  178. assert(soundID < soundBase::sound_after_last);
  179. auto sound = AudioPath::builtin(sounds[soundID]);
  180. logGlobal->trace("Attempt to play sound %d with file name %s with cache", soundID, sound.getOriginalName());
  181. return playSound(sound, repeats, true);
  182. }
  183. int CSoundHandler::playSound(const AudioPath & sound, int repeats, bool cache)
  184. {
  185. if (!initialized || sound.empty())
  186. return -1;
  187. int channel;
  188. Mix_Chunk *chunk = GetSoundChunk(sound, cache);
  189. if (chunk)
  190. {
  191. channel = Mix_PlayChannel(-1, chunk, repeats);
  192. if (channel == -1)
  193. {
  194. logGlobal->error("Unable to play sound file %s , error %s", sound.getOriginalName(), Mix_GetError());
  195. if (!cache)
  196. Mix_FreeChunk(chunk);
  197. }
  198. else if (cache)
  199. initCallback(channel);
  200. else
  201. initCallback(channel, [chunk](){ Mix_FreeChunk(chunk);});
  202. }
  203. else
  204. channel = -1;
  205. return channel;
  206. }
  207. int CSoundHandler::playSound(std::pair<std::unique_ptr<ui8 []>, si64> & data, int repeats, bool cache)
  208. {
  209. int channel = -1;
  210. if (Mix_Chunk *chunk = GetSoundChunk(data, cache))
  211. {
  212. channel = Mix_PlayChannel(-1, chunk, repeats);
  213. if (channel == -1)
  214. {
  215. logGlobal->error("Unable to play sound, error %s", Mix_GetError());
  216. if (!cache)
  217. Mix_FreeChunk(chunk);
  218. }
  219. else if (cache)
  220. initCallback(channel);
  221. else
  222. initCallback(channel, [chunk](){ Mix_FreeChunk(chunk);});
  223. }
  224. return channel;
  225. }
  226. // Helper. Randomly select a sound from an array and play it
  227. int CSoundHandler::playSoundFromSet(std::vector<soundBase::soundID> &sound_vec)
  228. {
  229. return playSound(*RandomGeneratorUtil::nextItem(sound_vec, CRandomGenerator::getDefault()));
  230. }
  231. void CSoundHandler::stopSound(int handler)
  232. {
  233. if (initialized && handler != -1)
  234. Mix_HaltChannel(handler);
  235. }
  236. // Sets the sound volume, from 0 (mute) to 100
  237. void CSoundHandler::setVolume(ui32 percent)
  238. {
  239. CAudioBase::setVolume(percent);
  240. if (initialized)
  241. {
  242. setChannelVolume(-1, volume);
  243. for (auto const & channel : channelVolumes)
  244. updateChannelVolume(channel.first);
  245. }
  246. }
  247. void CSoundHandler::updateChannelVolume(int channel)
  248. {
  249. if (channelVolumes.count(channel))
  250. setChannelVolume(channel, getVolume() * channelVolumes[channel] / 100);
  251. else
  252. setChannelVolume(channel, getVolume());
  253. }
  254. // Sets the sound volume, from 0 (mute) to 100
  255. void CSoundHandler::setChannelVolume(int channel, ui32 percent)
  256. {
  257. Mix_Volume(channel, (MIX_MAX_VOLUME * percent)/100);
  258. }
  259. void CSoundHandler::setCallback(int channel, std::function<void()> function)
  260. {
  261. boost::mutex::scoped_lock lockGuard(mutexCallbacks);
  262. auto iter = callbacks.find(channel);
  263. //channel not found. It may have finished so fire callback now
  264. if(iter == callbacks.end())
  265. function();
  266. else
  267. iter->second.push_back(function);
  268. }
  269. void CSoundHandler::soundFinishedCallback(int channel)
  270. {
  271. boost::mutex::scoped_lock lockGuard(mutexCallbacks);
  272. if (callbacks.count(channel) == 0)
  273. return;
  274. // store callbacks from container locally - SDL might reuse this channel for another sound
  275. // but do actualy execution in separate thread, to avoid potential deadlocks in case if callback requires locks of its own
  276. auto callback = callbacks.at(channel);
  277. callbacks.erase(channel);
  278. if (!callback.empty())
  279. {
  280. GH.dispatchMainThread([callback](){
  281. for (auto entry : callback)
  282. entry();
  283. });
  284. }
  285. }
  286. void CSoundHandler::initCallback(int channel)
  287. {
  288. boost::mutex::scoped_lock lockGuard(mutexCallbacks);
  289. assert(callbacks.count(channel) == 0);
  290. callbacks[channel] = {};
  291. }
  292. void CSoundHandler::initCallback(int channel, const std::function<void()> & function)
  293. {
  294. boost::mutex::scoped_lock lockGuard(mutexCallbacks);
  295. assert(callbacks.count(channel) == 0);
  296. callbacks[channel].push_back(function);
  297. }
  298. int CSoundHandler::ambientGetRange() const
  299. {
  300. return static_cast<int>(ambientConfig["range"].Integer());
  301. }
  302. void CSoundHandler::ambientUpdateChannels(std::map<AudioPath, int> soundsArg)
  303. {
  304. boost::mutex::scoped_lock guard(mutex);
  305. std::vector<AudioPath> stoppedSounds;
  306. for(auto & pair : ambientChannels)
  307. {
  308. const auto & soundId = pair.first;
  309. const int channel = pair.second;
  310. if(!vstd::contains(soundsArg, soundId))
  311. {
  312. ambientStopSound(soundId);
  313. stoppedSounds.push_back(soundId);
  314. }
  315. else
  316. {
  317. int volume = ambientDistToVolume(soundsArg[soundId]);
  318. channelVolumes[channel] = volume;
  319. updateChannelVolume(channel);
  320. }
  321. }
  322. for(auto soundId : stoppedSounds)
  323. {
  324. channelVolumes.erase(ambientChannels[soundId]);
  325. ambientChannels.erase(soundId);
  326. }
  327. for(auto & pair : soundsArg)
  328. {
  329. const auto & soundId = pair.first;
  330. const int distance = pair.second;
  331. if(!vstd::contains(ambientChannels, soundId))
  332. {
  333. int channel = playSound(soundId, -1);
  334. int volume = ambientDistToVolume(distance);
  335. channelVolumes[channel] = volume;
  336. updateChannelVolume(channel);
  337. ambientChannels[soundId] = channel;
  338. }
  339. }
  340. }
  341. void CSoundHandler::ambientStopAllChannels()
  342. {
  343. boost::mutex::scoped_lock guard(mutex);
  344. for(auto ch : ambientChannels)
  345. {
  346. ambientStopSound(ch.first);
  347. }
  348. channelVolumes.clear();
  349. ambientChannels.clear();
  350. }
  351. void CMusicHandler::onVolumeChange(const JsonNode &volumeNode)
  352. {
  353. setVolume((ui32)volumeNode.Float());
  354. }
  355. CMusicHandler::CMusicHandler():
  356. listener(settings.listen["general"]["music"])
  357. {
  358. listener(std::bind(&CMusicHandler::onVolumeChange, this, _1));
  359. auto mp3files = CResourceHandler::get()->getFilteredFiles([](const ResourcePath & id) -> bool
  360. {
  361. if(id.getType() != EResType::SOUND)
  362. return false;
  363. if(!boost::algorithm::istarts_with(id.getName(), "MUSIC/"))
  364. return false;
  365. logGlobal->trace("Found music file %s", id.getName());
  366. return true;
  367. });
  368. for(const ResourcePath & file : mp3files)
  369. {
  370. if(boost::algorithm::istarts_with(file.getName(), "MUSIC/Combat"))
  371. addEntryToSet("battle", AudioPath::fromResource(file));
  372. else if(boost::algorithm::istarts_with(file.getName(), "MUSIC/AITheme"))
  373. addEntryToSet("enemy-turn", AudioPath::fromResource(file));
  374. }
  375. }
  376. void CMusicHandler::loadTerrainMusicThemes()
  377. {
  378. for (const auto & terrain : CGI->terrainTypeHandler->objects)
  379. {
  380. addEntryToSet("terrain_" + terrain->getJsonKey(), terrain->musicFilename);
  381. }
  382. }
  383. void CMusicHandler::addEntryToSet(const std::string & set, const AudioPath & musicURI)
  384. {
  385. musicsSet[set].push_back(musicURI);
  386. }
  387. void CMusicHandler::init()
  388. {
  389. CAudioBase::init();
  390. if (initialized)
  391. {
  392. Mix_HookMusicFinished([]()
  393. {
  394. CCS->musich->musicFinishedCallback();
  395. });
  396. }
  397. }
  398. void CMusicHandler::release()
  399. {
  400. if (initialized)
  401. {
  402. boost::mutex::scoped_lock guard(mutex);
  403. Mix_HookMusicFinished(nullptr);
  404. current->stop();
  405. current.reset();
  406. next.reset();
  407. }
  408. CAudioBase::release();
  409. }
  410. void CMusicHandler::playMusic(const AudioPath & musicURI, bool loop, bool fromStart)
  411. {
  412. boost::mutex::scoped_lock guard(mutex);
  413. if (current && current->isPlaying() && current->isTrack(musicURI))
  414. return;
  415. queueNext(this, "", musicURI, loop, fromStart);
  416. }
  417. void CMusicHandler::playMusicFromSet(const std::string & musicSet, const std::string & entryID, bool loop, bool fromStart)
  418. {
  419. playMusicFromSet(musicSet + "_" + entryID, loop, fromStart);
  420. }
  421. void CMusicHandler::playMusicFromSet(const std::string & whichSet, bool loop, bool fromStart)
  422. {
  423. boost::mutex::scoped_lock guard(mutex);
  424. auto selectedSet = musicsSet.find(whichSet);
  425. if (selectedSet == musicsSet.end())
  426. {
  427. logGlobal->error("Error: playing music from non-existing set: %s", whichSet);
  428. return;
  429. }
  430. if (current && current->isPlaying() && current->isSet(whichSet))
  431. return;
  432. // in this mode - play random track from set
  433. queueNext(this, whichSet, AudioPath(), loop, fromStart);
  434. }
  435. void CMusicHandler::queueNext(std::unique_ptr<MusicEntry> queued)
  436. {
  437. if (!initialized)
  438. return;
  439. next = std::move(queued);
  440. if (current.get() == nullptr || !current->stop(1000))
  441. {
  442. current.reset(next.release());
  443. current->play();
  444. }
  445. }
  446. void CMusicHandler::queueNext(CMusicHandler *owner, const std::string & setName, const AudioPath & musicURI, bool looped, bool fromStart)
  447. {
  448. queueNext(std::make_unique<MusicEntry>(owner, setName, musicURI, looped, fromStart));
  449. }
  450. void CMusicHandler::stopMusic(int fade_ms)
  451. {
  452. if (!initialized)
  453. return;
  454. boost::mutex::scoped_lock guard(mutex);
  455. if (current.get() != nullptr)
  456. current->stop(fade_ms);
  457. next.reset();
  458. }
  459. void CMusicHandler::setVolume(ui32 percent)
  460. {
  461. CAudioBase::setVolume(percent);
  462. if (initialized)
  463. Mix_VolumeMusic((MIX_MAX_VOLUME * volume)/100);
  464. }
  465. void CMusicHandler::musicFinishedCallback()
  466. {
  467. // call music restart in separate thread to avoid deadlock in some cases
  468. // It is possible for:
  469. // 1) SDL thread to call this method on end of playback
  470. // 2) VCMI code to call queueNext() method to queue new file
  471. // this leads to:
  472. // 1) SDL thread waiting to acquire music lock in this method (while keeping internal SDL mutex locked)
  473. // 2) VCMI thread waiting to acquire internal SDL mutex (while keeping music mutex locked)
  474. GH.dispatchMainThread([this]()
  475. {
  476. boost::unique_lock lockGuard(mutex);
  477. if (current.get() != nullptr)
  478. {
  479. // if music is looped, play it again
  480. if (current->play())
  481. return;
  482. else
  483. current.reset();
  484. }
  485. if (current.get() == nullptr && next.get() != nullptr)
  486. {
  487. current.reset(next.release());
  488. current->play();
  489. }
  490. });
  491. }
  492. MusicEntry::MusicEntry(CMusicHandler *owner, std::string setName, const AudioPath & musicURI, bool looped, bool fromStart):
  493. owner(owner),
  494. music(nullptr),
  495. playing(false),
  496. startTime(uint32_t(-1)),
  497. startPosition(0),
  498. loop(looped ? -1 : 1),
  499. fromStart(fromStart),
  500. setName(std::move(setName))
  501. {
  502. if (!musicURI.empty())
  503. load(std::move(musicURI));
  504. }
  505. MusicEntry::~MusicEntry()
  506. {
  507. if (playing && loop > 0)
  508. {
  509. assert(0);
  510. logGlobal->error("Attempt to delete music while playing!");
  511. Mix_HaltMusic();
  512. }
  513. if (loop == 0 && Mix_FadingMusic() != MIX_NO_FADING)
  514. {
  515. assert(0);
  516. logGlobal->error("Attempt to delete music while fading out!");
  517. Mix_HaltMusic();
  518. }
  519. logGlobal->trace("Del-ing music file %s", currentName.getOriginalName());
  520. if (music)
  521. Mix_FreeMusic(music);
  522. }
  523. void MusicEntry::load(const AudioPath & musicURI)
  524. {
  525. if (music)
  526. {
  527. logGlobal->trace("Del-ing music file %s", currentName.getOriginalName());
  528. Mix_FreeMusic(music);
  529. music = nullptr;
  530. }
  531. if (CResourceHandler::get()->existsResource(musicURI))
  532. currentName = musicURI;
  533. else
  534. currentName = musicURI.addPrefix("MUSIC/");
  535. music = nullptr;
  536. logGlobal->trace("Loading music file %s", currentName.getOriginalName());
  537. try
  538. {
  539. auto musicFile = MakeSDLRWops(CResourceHandler::get()->load(currentName));
  540. music = Mix_LoadMUS_RW(musicFile, SDL_TRUE);
  541. }
  542. catch(std::exception &e)
  543. {
  544. logGlobal->error("Failed to load music. setName=%s\tmusicURI=%s", setName, currentName.getOriginalName());
  545. logGlobal->error("Exception: %s", e.what());
  546. }
  547. if(!music)
  548. {
  549. logGlobal->warn("Warning: Cannot open %s: %s", currentName.getOriginalName(), Mix_GetError());
  550. return;
  551. }
  552. }
  553. bool MusicEntry::play()
  554. {
  555. if (!(loop--) && music) //already played once - return
  556. return false;
  557. if (!setName.empty())
  558. {
  559. const auto & set = owner->musicsSet[setName];
  560. const auto & iter = RandomGeneratorUtil::nextItem(set, CRandomGenerator::getDefault());
  561. load(*iter);
  562. }
  563. logGlobal->trace("Playing music file %s", currentName.getOriginalName());
  564. if (!fromStart && owner->trackPositions.count(currentName) > 0 && owner->trackPositions[currentName] > 0)
  565. {
  566. float timeToStart = owner->trackPositions[currentName];
  567. startPosition = std::round(timeToStart * 1000);
  568. // erase stored position:
  569. // if music track will be interrupted again - new position will be written in stop() method
  570. // if music track is not interrupted and will finish by timeout/end of file - it will restart from begginning as it should
  571. owner->trackPositions.erase(owner->trackPositions.find(currentName));
  572. if (Mix_FadeInMusicPos(music, 1, 1000, timeToStart) == -1)
  573. {
  574. logGlobal->error("Unable to play music (%s)", Mix_GetError());
  575. return false;
  576. }
  577. }
  578. else
  579. {
  580. startPosition = 0;
  581. if(Mix_PlayMusic(music, 1) == -1)
  582. {
  583. logGlobal->error("Unable to play music (%s)", Mix_GetError());
  584. return false;
  585. }
  586. }
  587. startTime = GH.input().getTicks();
  588. playing = true;
  589. return true;
  590. }
  591. bool MusicEntry::stop(int fade_ms)
  592. {
  593. if (Mix_PlayingMusic())
  594. {
  595. playing = false;
  596. loop = 0;
  597. uint32_t endTime = GH.input().getTicks();
  598. assert(startTime != uint32_t(-1));
  599. float playDuration = (endTime - startTime + startPosition) / 1000.f;
  600. owner->trackPositions[currentName] = playDuration;
  601. logGlobal->trace("Stopping music file %s at %f", currentName.getOriginalName(), playDuration);
  602. Mix_FadeOutMusic(fade_ms);
  603. return true;
  604. }
  605. return false;
  606. }
  607. bool MusicEntry::isPlaying()
  608. {
  609. return playing;
  610. }
  611. bool MusicEntry::isSet(std::string set)
  612. {
  613. return !setName.empty() && set == setName;
  614. }
  615. bool MusicEntry::isTrack(const AudioPath & track)
  616. {
  617. return setName.empty() && track == currentName;
  618. }