AudioMixerController.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. /****************************************************************************
  2. Copyright (c) 2016 Chukong Technologies Inc.
  3. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
  4. http://www.cocos2d-x.org
  5. Permission is hereby granted, free of charge, to any person obtaining a copy
  6. of this software and associated documentation files (the "Software"), to deal
  7. in the Software without restriction, including without limitation the rights
  8. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the Software is
  10. furnished to do so, subject to the following conditions:
  11. The above copyright notice and this permission notice shall be included in
  12. all copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. THE SOFTWARE.
  20. ****************************************************************************/
  21. #define LOG_TAG "AudioMixerController"
  22. #include "audio/android/AudioMixerController.h"
  23. #include "audio/android/AudioMixer.h"
  24. #include "audio/android/Track.h"
  25. #include "audio/android/OpenSLHelper.h"
  26. #include <stdlib.h>
  27. #include <algorithm>
  28. namespace cocos2d { namespace experimental {
  29. AudioMixerController::AudioMixerController(int bufferSizeInFrames, int sampleRate, int channelCount)
  30. : _bufferSizeInFrames(bufferSizeInFrames)
  31. , _sampleRate(sampleRate)
  32. , _channelCount(channelCount)
  33. , _mixer(nullptr)
  34. , _isPaused(false)
  35. , _isMixingFrame(false)
  36. {
  37. ALOGV("In the constructor of AudioMixerController!");
  38. _mixingBuffer.size = (size_t) bufferSizeInFrames * 2 * channelCount;
  39. // Don't use posix_memalign since it was added from API 16, it will crash on Android 2.3
  40. // Therefore, for a workaround, we uses memalign here.
  41. _mixingBuffer.buf = memalign(32, _mixingBuffer.size);
  42. memset(_mixingBuffer.buf, 0, _mixingBuffer.size);
  43. }
  44. AudioMixerController::~AudioMixerController()
  45. {
  46. destroy();
  47. if (_mixer != nullptr)
  48. {
  49. delete _mixer;
  50. _mixer = nullptr;
  51. }
  52. free(_mixingBuffer.buf);
  53. }
  54. bool AudioMixerController::init()
  55. {
  56. _mixer = new (std::nothrow) AudioMixer(_bufferSizeInFrames, _sampleRate);
  57. return _mixer != nullptr;
  58. }
  59. bool AudioMixerController::addTrack(Track* track)
  60. {
  61. ALOG_ASSERT(track != nullptr, "Shouldn't pass nullptr to addTrack");
  62. bool ret = false;
  63. std::lock_guard<std::mutex> lk(_activeTracksMutex);
  64. auto iter = std::find(_activeTracks.begin(), _activeTracks.end(), track);
  65. if (iter == _activeTracks.end())
  66. {
  67. _activeTracks.push_back(track);
  68. ret = true;
  69. }
  70. return ret;
  71. }
  72. template <typename T>
  73. static void removeItemFromVector(std::vector<T>& v, T item)
  74. {
  75. auto iter = std::find(v.begin(), v.end(), item);
  76. if (iter != v.end())
  77. {
  78. v.erase(iter);
  79. }
  80. }
  81. void AudioMixerController::initTrack(Track* track, std::vector<Track*>& tracksToRemove)
  82. {
  83. if (track->isInitialized())
  84. return;
  85. uint32_t channelMask = audio_channel_out_mask_from_count(2);
  86. int32_t name = _mixer->getTrackName(channelMask, AUDIO_FORMAT_PCM_16_BIT,
  87. AUDIO_SESSION_OUTPUT_MIX);
  88. if (name < 0)
  89. {
  90. // If we could not get the track name, it means that there're MAX_NUM_TRACKS tracks
  91. // So ignore the new track.
  92. tracksToRemove.push_back(track);
  93. }
  94. else
  95. {
  96. _mixer->setBufferProvider(name, track);
  97. _mixer->setParameter(name, AudioMixer::TRACK, AudioMixer::MAIN_BUFFER,
  98. _mixingBuffer.buf);
  99. _mixer->setParameter(
  100. name,
  101. AudioMixer::TRACK,
  102. AudioMixer::MIXER_FORMAT,
  103. (void *) (uintptr_t) AUDIO_FORMAT_PCM_16_BIT);
  104. _mixer->setParameter(
  105. name,
  106. AudioMixer::TRACK,
  107. AudioMixer::FORMAT,
  108. (void *) (uintptr_t) AUDIO_FORMAT_PCM_16_BIT);
  109. _mixer->setParameter(
  110. name,
  111. AudioMixer::TRACK,
  112. AudioMixer::MIXER_CHANNEL_MASK,
  113. (void *) (uintptr_t) channelMask);
  114. _mixer->setParameter(
  115. name,
  116. AudioMixer::TRACK,
  117. AudioMixer::CHANNEL_MASK,
  118. (void *) (uintptr_t) channelMask);
  119. track->setName(name);
  120. _mixer->enable(name);
  121. std::lock_guard<std::mutex> lk(track->_volumeDirtyMutex);
  122. gain_minifloat_packed_t volume = track->getVolumeLR();
  123. float lVolume = float_from_gain(gain_minifloat_unpack_left(volume));
  124. float rVolume = float_from_gain(gain_minifloat_unpack_right(volume));
  125. _mixer->setParameter(name, AudioMixer::VOLUME, AudioMixer::VOLUME0, &lVolume);
  126. _mixer->setParameter(name, AudioMixer::VOLUME, AudioMixer::VOLUME1, &rVolume);
  127. track->setVolumeDirty(false);
  128. track->setInitialized(true);
  129. }
  130. }
  131. void AudioMixerController::mixOneFrame()
  132. {
  133. _isMixingFrame = true;
  134. _activeTracksMutex.lock();
  135. auto mixStart = clockNow();
  136. std::vector<Track*> tracksToRemove;
  137. tracksToRemove.reserve(_activeTracks.size());
  138. // FOR TESTING BEGIN
  139. // Track* track = _activeTracks[0];
  140. //
  141. // AudioBufferProvider::Buffer buffer;
  142. // buffer.frameCount = _bufferSizeInFrames;
  143. // status_t r = track->getNextBuffer(&buffer);
  144. //// ALOG_ASSERT(buffer.frameCount == _mixing->size / 2, "buffer.frameCount:%d, _mixing->size/2:%d", buffer.frameCount, _mixing->size/2);
  145. // if (r == NO_ERROR)
  146. // {
  147. // ALOGV("getNextBuffer succeed ...");
  148. // memcpy(_mixing->buf, buffer.raw, _mixing->size);
  149. // }
  150. // if (buffer.raw == nullptr)
  151. // {
  152. // ALOGV("Play over ...");
  153. // tracksToRemove.push_back(track);
  154. // }
  155. // else
  156. // {
  157. // track->releaseBuffer(&buffer);
  158. // }
  159. //
  160. // _mixing->state = BufferState::FULL;
  161. // _activeTracksMutex.unlock();
  162. // FOR TESTING END
  163. Track::State state;
  164. // set up the tracks.
  165. for (auto&& track : _activeTracks)
  166. {
  167. state = track->getState();
  168. if (state == Track::State::PLAYING)
  169. {
  170. initTrack(track, tracksToRemove);
  171. int name = track->getName();
  172. ALOG_ASSERT(name >= 0);
  173. std::lock_guard<std::mutex> lk(track->_volumeDirtyMutex);
  174. if (track->isVolumeDirty())
  175. {
  176. gain_minifloat_packed_t volume = track->getVolumeLR();
  177. float lVolume = float_from_gain(gain_minifloat_unpack_left(volume));
  178. float rVolume = float_from_gain(gain_minifloat_unpack_right(volume));
  179. ALOGV("Track (name: %d)'s volume is dirty, update volume to L: %f, R: %f", name, lVolume, rVolume);
  180. _mixer->setParameter(name, AudioMixer::VOLUME, AudioMixer::VOLUME0, &lVolume);
  181. _mixer->setParameter(name, AudioMixer::VOLUME, AudioMixer::VOLUME1, &rVolume);
  182. track->setVolumeDirty(false);
  183. }
  184. }
  185. else if (state == Track::State::RESUMED)
  186. {
  187. initTrack(track, tracksToRemove);
  188. if (track->getPrevState() == Track::State::PAUSED)
  189. {
  190. _mixer->enable(track->getName());
  191. track->setState(Track::State::PLAYING);
  192. }
  193. else
  194. {
  195. ALOGW("Previous state (%d) isn't PAUSED, couldn't resume!", static_cast<int>(track->getPrevState()));
  196. }
  197. }
  198. else if (state == Track::State::PAUSED)
  199. {
  200. initTrack(track, tracksToRemove);
  201. if (track->getPrevState() == Track::State::PLAYING || track->getPrevState() == Track::State::RESUMED)
  202. {
  203. _mixer->disable(track->getName());
  204. }
  205. else
  206. {
  207. ALOGW("Previous state (%d) isn't PLAYING, couldn't pause!", static_cast<int>(track->getPrevState()));
  208. }
  209. }
  210. else if (state == Track::State::STOPPED)
  211. {
  212. if (track->isInitialized())
  213. {
  214. _mixer->deleteTrackName(track->getName());
  215. }
  216. else
  217. {
  218. ALOGV("Track (%p) hasn't been initialized yet!", track);
  219. }
  220. tracksToRemove.push_back(track);
  221. }
  222. if (track->isPlayOver())
  223. {
  224. if (track->isLoop())
  225. {
  226. track->reset();
  227. }
  228. else
  229. {
  230. ALOGV("Play over ...");
  231. _mixer->deleteTrackName(track->getName());
  232. tracksToRemove.push_back(track);
  233. track->setState(Track::State::OVER);
  234. }
  235. }
  236. }
  237. bool hasAvailableTracks = _activeTracks.size() - tracksToRemove.size() > 0;
  238. if (hasAvailableTracks)
  239. {
  240. ALOGV_IF(_activeTracks.size() > 8, "More than 8 active tracks: %d", (int) _activeTracks.size());
  241. _mixer->process(AudioBufferProvider::kInvalidPTS);
  242. }
  243. else
  244. {
  245. ALOGV("Doesn't have enough tracks: %d, %d", (int) _activeTracks.size(), (int) tracksToRemove.size());
  246. }
  247. // Remove stopped or playover tracks for active tracks container
  248. for (auto&& track : tracksToRemove)
  249. {
  250. removeItemFromVector(_activeTracks, track);
  251. if (track != nullptr && track->onStateChanged != nullptr)
  252. {
  253. track->onStateChanged(Track::State::DESTROYED);
  254. }
  255. else
  256. {
  257. ALOGE("track (%p) was released ...", track);
  258. }
  259. }
  260. _activeTracksMutex.unlock();
  261. auto mixEnd = clockNow();
  262. float mixInterval = intervalInMS(mixStart, mixEnd);
  263. ALOGV_IF(mixInterval > 1.0f, "Mix a frame waste: %fms", mixInterval);
  264. _isMixingFrame = false;
  265. }
  266. void AudioMixerController::destroy()
  267. {
  268. while (_isMixingFrame)
  269. {
  270. usleep(10);
  271. }
  272. usleep(2000); // Wait for more 2ms
  273. }
  274. void AudioMixerController::pause()
  275. {
  276. _isPaused = true;
  277. }
  278. void AudioMixerController::resume()
  279. {
  280. _isPaused = false;
  281. }
  282. bool AudioMixerController::hasPlayingTacks()
  283. {
  284. std::lock_guard<std::mutex> lk (_activeTracksMutex);
  285. if (_activeTracks.empty())
  286. return false;
  287. for (auto&& track : _activeTracks)
  288. {
  289. Track::State state = track->getState();
  290. if (state == Track::State::IDLE || state == Track::State::PLAYING || state == Track::State::RESUMED)
  291. {
  292. return true;
  293. }
  294. }
  295. return false;
  296. }
  297. }} // namespace cocos2d { namespace experimental {