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