AudioMixer.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. /*
  2. **
  3. ** Copyright 2007, The Android Open Source Project
  4. **
  5. ** Licensed under the Apache License, Version 2.0 (the "License");
  6. ** you may not use this file except in compliance with the License.
  7. ** You may obtain a copy of the License at
  8. **
  9. ** http://www.apache.org/licenses/LICENSE-2.0
  10. **
  11. ** Unless required by applicable law or agreed to in writing, software
  12. ** distributed under the License is distributed on an "AS IS" BASIS,
  13. ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. ** See the License for the specific language governing permissions and
  15. ** limitations under the License.
  16. */
  17. #pragma once
  18. #include <stdint.h>
  19. #include <sys/types.h>
  20. #include <pthread.h>
  21. #include "audio/android/AudioBufferProvider.h"
  22. #include "audio/android/AudioResamplerPublic.h"
  23. #include "audio/android/AudioResampler.h"
  24. #include "audio/android/audio.h"
  25. // FIXME This is actually unity gain, which might not be max in future, expressed in U.12
  26. #define MAX_GAIN_INT AudioMixer::UNITY_GAIN_INT
  27. namespace cocos2d { namespace experimental {
  28. // ----------------------------------------------------------------------------
  29. class AudioMixer
  30. {
  31. public:
  32. AudioMixer(size_t frameCount, uint32_t sampleRate,
  33. uint32_t maxNumTracks = MAX_NUM_TRACKS);
  34. /*virtual*/ ~AudioMixer(); // non-virtual saves a v-table, restore if sub-classed
  35. // This mixer has a hard-coded upper limit of 32 active track inputs.
  36. // Adding support for > 32 tracks would require more than simply changing this value.
  37. static const uint32_t MAX_NUM_TRACKS = 32;
  38. // maximum number of channels supported by the mixer
  39. // This mixer has a hard-coded upper limit of 8 channels for output.
  40. static const uint32_t MAX_NUM_CHANNELS = 8;
  41. static const uint32_t MAX_NUM_VOLUMES = 2; // stereo volume only
  42. // maximum number of channels supported for the content
  43. static const uint32_t MAX_NUM_CHANNELS_TO_DOWNMIX = AUDIO_CHANNEL_COUNT_MAX;
  44. static const uint16_t UNITY_GAIN_INT = 0x1000;
  45. static const CONSTEXPR float UNITY_GAIN_FLOAT = 1.0f;
  46. enum { // names
  47. // track names (MAX_NUM_TRACKS units)
  48. TRACK0 = 0x1000,
  49. // 0x2000 is unused
  50. // setParameter targets
  51. TRACK = 0x3000,
  52. RESAMPLE = 0x3001,
  53. RAMP_VOLUME = 0x3002, // ramp to new volume
  54. VOLUME = 0x3003, // don't ramp
  55. TIMESTRETCH = 0x3004,
  56. // set Parameter names
  57. // for target TRACK
  58. CHANNEL_MASK = 0x4000,
  59. FORMAT = 0x4001,
  60. MAIN_BUFFER = 0x4002,
  61. AUX_BUFFER = 0x4003,
  62. DOWNMIX_TYPE = 0X4004,
  63. MIXER_FORMAT = 0x4005, // AUDIO_FORMAT_PCM_(FLOAT|16_BIT)
  64. MIXER_CHANNEL_MASK = 0x4006, // Channel mask for mixer output
  65. // for target RESAMPLE
  66. SAMPLE_RATE = 0x4100, // Configure sample rate conversion on this track name;
  67. // parameter 'value' is the new sample rate in Hz.
  68. // Only creates a sample rate converter the first time that
  69. // the track sample rate is different from the mix sample rate.
  70. // If the new sample rate is the same as the mix sample rate,
  71. // and a sample rate converter already exists,
  72. // then the sample rate converter remains present but is a no-op.
  73. RESET = 0x4101, // Reset sample rate converter without changing sample rate.
  74. // This clears out the resampler's input buffer.
  75. REMOVE = 0x4102, // Remove the sample rate converter on this track name;
  76. // the track is restored to the mix sample rate.
  77. // for target RAMP_VOLUME and VOLUME (8 channels max)
  78. // FIXME use float for these 3 to improve the dynamic range
  79. VOLUME0 = 0x4200,
  80. VOLUME1 = 0x4201,
  81. AUXLEVEL = 0x4210,
  82. // for target TIMESTRETCH
  83. PLAYBACK_RATE = 0x4300, // Configure timestretch on this track name;
  84. // parameter 'value' is a pointer to the new playback rate.
  85. };
  86. // For all APIs with "name": TRACK0 <= name < TRACK0 + MAX_NUM_TRACKS
  87. // Allocate a track name. Returns new track name if successful, -1 on failure.
  88. // The failure could be because of an invalid channelMask or format, or that
  89. // the track capacity of the mixer is exceeded.
  90. int getTrackName(audio_channel_mask_t channelMask,
  91. audio_format_t format, int sessionId);
  92. // Free an allocated track by name
  93. void deleteTrackName(int name);
  94. // Enable or disable an allocated track by name
  95. void enable(int name);
  96. void disable(int name);
  97. void setParameter(int name, int target, int param, void *value);
  98. void setBufferProvider(int name, AudioBufferProvider* bufferProvider);
  99. void process(int64_t pts);
  100. uint32_t trackNames() const { return mTrackNames; }
  101. size_t getUnreleasedFrames(int name) const;
  102. static inline bool isValidPcmTrackFormat(audio_format_t format) {
  103. switch (format) {
  104. case AUDIO_FORMAT_PCM_8_BIT:
  105. case AUDIO_FORMAT_PCM_16_BIT:
  106. case AUDIO_FORMAT_PCM_24_BIT_PACKED:
  107. case AUDIO_FORMAT_PCM_32_BIT:
  108. case AUDIO_FORMAT_PCM_FLOAT:
  109. return true;
  110. default:
  111. return false;
  112. }
  113. }
  114. private:
  115. enum {
  116. // FIXME this representation permits up to 8 channels
  117. NEEDS_CHANNEL_COUNT__MASK = 0x00000007,
  118. };
  119. enum {
  120. NEEDS_CHANNEL_1 = 0x00000000, // mono
  121. NEEDS_CHANNEL_2 = 0x00000001, // stereo
  122. // sample format is not explicitly specified, and is assumed to be AUDIO_FORMAT_PCM_16_BIT
  123. NEEDS_MUTE = 0x00000100,
  124. NEEDS_RESAMPLE = 0x00001000,
  125. NEEDS_AUX = 0x00010000,
  126. };
  127. struct state_t;
  128. struct track_t;
  129. typedef void (*hook_t)(track_t* t, int32_t* output, size_t numOutFrames, int32_t* temp,
  130. int32_t* aux);
  131. static const int BLOCKSIZE = 16; // 4 cache lines
  132. struct track_t {
  133. uint32_t needs;
  134. // TODO: Eventually remove legacy integer volume settings
  135. union {
  136. int16_t volume[MAX_NUM_VOLUMES]; // U4.12 fixed point (top bit should be zero)
  137. int32_t volumeRL;
  138. };
  139. int32_t prevVolume[MAX_NUM_VOLUMES];
  140. // 16-byte boundary
  141. int32_t volumeInc[MAX_NUM_VOLUMES];
  142. int32_t auxInc;
  143. int32_t prevAuxLevel;
  144. // 16-byte boundary
  145. int16_t auxLevel; // 0 <= auxLevel <= MAX_GAIN_INT, but signed for mul performance
  146. uint16_t frameCount;
  147. uint8_t channelCount; // 1 or 2, redundant with (needs & NEEDS_CHANNEL_COUNT__MASK)
  148. uint8_t unused_padding; // formerly format, was always 16
  149. uint16_t enabled; // actually bool
  150. audio_channel_mask_t channelMask;
  151. // actual buffer provider used by the track hooks, see DownmixerBufferProvider below
  152. // for how the Track buffer provider is wrapped by another one when dowmixing is required
  153. AudioBufferProvider* bufferProvider;
  154. // 16-byte boundary
  155. mutable AudioBufferProvider::Buffer buffer; // 8 bytes
  156. hook_t hook;
  157. const void* in; // current location in buffer
  158. // 16-byte boundary
  159. AudioResampler* resampler;
  160. uint32_t sampleRate;
  161. int32_t* mainBuffer;
  162. int32_t* auxBuffer;
  163. // 16-byte boundary
  164. /* Buffer providers are constructed to translate the track input data as needed.
  165. *
  166. * TODO: perhaps make a single PlaybackConverterProvider class to move
  167. * all pre-mixer track buffer conversions outside the AudioMixer class.
  168. *
  169. * 1) mInputBufferProvider: The AudioTrack buffer provider.
  170. * 2) mReformatBufferProvider: If not NULL, performs the audio reformat to
  171. * match either mMixerInFormat or mDownmixRequiresFormat, if the downmixer
  172. * requires reformat. For example, it may convert floating point input to
  173. * PCM_16_bit if that's required by the downmixer.
  174. * 3) downmixerBufferProvider: If not NULL, performs the channel remixing to match
  175. * the number of channels required by the mixer sink.
  176. * 4) mPostDownmixReformatBufferProvider: If not NULL, performs reformatting from
  177. * the downmixer requirements to the mixer engine input requirements.
  178. * 5) mTimestretchBufferProvider: Adds timestretching for playback rate
  179. */
  180. AudioBufferProvider* mInputBufferProvider; // externally provided buffer provider.
  181. //cjh PassthruBufferProvider* mReformatBufferProvider; // provider wrapper for reformatting.
  182. // PassthruBufferProvider* downmixerBufferProvider; // wrapper for channel conversion.
  183. // PassthruBufferProvider* mPostDownmixReformatBufferProvider;
  184. // PassthruBufferProvider* mTimestretchBufferProvider;
  185. int32_t sessionId;
  186. audio_format_t mMixerFormat; // output mix format: AUDIO_FORMAT_PCM_(FLOAT|16_BIT)
  187. audio_format_t mFormat; // input track format
  188. audio_format_t mMixerInFormat; // mix internal format AUDIO_FORMAT_PCM_(FLOAT|16_BIT)
  189. // each track must be converted to this format.
  190. audio_format_t mDownmixRequiresFormat; // required downmixer format
  191. // AUDIO_FORMAT_PCM_16_BIT if 16 bit necessary
  192. // AUDIO_FORMAT_INVALID if no required format
  193. float mVolume[MAX_NUM_VOLUMES]; // floating point set volume
  194. float mPrevVolume[MAX_NUM_VOLUMES]; // floating point previous volume
  195. float mVolumeInc[MAX_NUM_VOLUMES]; // floating point volume increment
  196. float mAuxLevel; // floating point set aux level
  197. float mPrevAuxLevel; // floating point prev aux level
  198. float mAuxInc; // floating point aux increment
  199. audio_channel_mask_t mMixerChannelMask;
  200. uint32_t mMixerChannelCount;
  201. AudioPlaybackRate mPlaybackRate;
  202. bool needsRamp() { return (volumeInc[0] | volumeInc[1] | auxInc) != 0; }
  203. bool setResampler(uint32_t trackSampleRate, uint32_t devSampleRate);
  204. bool doesResample() const { return resampler != NULL; }
  205. void resetResampler() { if (resampler != NULL) resampler->reset(); }
  206. void adjustVolumeRamp(bool aux, bool useFloat = false);
  207. size_t getUnreleasedFrames() const { return resampler != NULL ?
  208. resampler->getUnreleasedFrames() : 0; };
  209. status_t prepareForDownmix();
  210. void unprepareForDownmix();
  211. status_t prepareForReformat();
  212. void unprepareForReformat();
  213. bool setPlaybackRate(const AudioPlaybackRate &playbackRate);
  214. void reconfigureBufferProviders();
  215. };
  216. typedef void (*process_hook_t)(state_t* state, int64_t pts);
  217. // pad to 32-bytes to fill cache line
  218. struct state_t {
  219. uint32_t enabledTracks;
  220. uint32_t needsChanged;
  221. size_t frameCount;
  222. process_hook_t hook; // one of process__*, never NULL
  223. int32_t *outputTemp;
  224. int32_t *resampleTemp;
  225. //cjh NBLog::Writer* mLog;
  226. int32_t reserved[1];
  227. // FIXME allocate dynamically to save some memory when maxNumTracks < MAX_NUM_TRACKS
  228. track_t tracks[MAX_NUM_TRACKS] __attribute__((aligned(32)));
  229. };
  230. // bitmask of allocated track names, where bit 0 corresponds to TRACK0 etc.
  231. uint32_t mTrackNames;
  232. // bitmask of configured track names; ~0 if maxNumTracks == MAX_NUM_TRACKS,
  233. // but will have fewer bits set if maxNumTracks < MAX_NUM_TRACKS
  234. const uint32_t mConfiguredNames;
  235. const uint32_t mSampleRate;
  236. //cjh NBLog::Writer mDummyLog;
  237. public:
  238. //cjh void setLog(NBLog::Writer* log);
  239. private:
  240. state_t mState __attribute__((aligned(32)));
  241. // Call after changing either the enabled status of a track, or parameters of an enabled track.
  242. // OK to call more often than that, but unnecessary.
  243. void invalidateState(uint32_t mask);
  244. bool setChannelMasks(int name,
  245. audio_channel_mask_t trackChannelMask, audio_channel_mask_t mixerChannelMask);
  246. static void track__genericResample(track_t* t, int32_t* out, size_t numFrames, int32_t* temp,
  247. int32_t* aux);
  248. static void track__nop(track_t* t, int32_t* out, size_t numFrames, int32_t* temp, int32_t* aux);
  249. static void track__16BitsStereo(track_t* t, int32_t* out, size_t numFrames, int32_t* temp,
  250. int32_t* aux);
  251. static void track__16BitsMono(track_t* t, int32_t* out, size_t numFrames, int32_t* temp,
  252. int32_t* aux);
  253. static void volumeRampStereo(track_t* t, int32_t* out, size_t frameCount, int32_t* temp,
  254. int32_t* aux);
  255. static void volumeStereo(track_t* t, int32_t* out, size_t frameCount, int32_t* temp,
  256. int32_t* aux);
  257. static void process__validate(state_t* state, int64_t pts);
  258. static void process__nop(state_t* state, int64_t pts);
  259. static void process__genericNoResampling(state_t* state, int64_t pts);
  260. static void process__genericResampling(state_t* state, int64_t pts);
  261. static void process__OneTrack16BitsStereoNoResampling(state_t* state,
  262. int64_t pts);
  263. static int64_t calculateOutputPTS(const track_t& t, int64_t basePTS,
  264. int outputFrameIndex);
  265. static uint64_t sLocalTimeFreq;
  266. static pthread_once_t sOnceControl;
  267. static void sInitRoutine();
  268. /* multi-format volume mixing function (calls template functions
  269. * in AudioMixerOps.h). The template parameters are as follows:
  270. *
  271. * MIXTYPE (see AudioMixerOps.h MIXTYPE_* enumeration)
  272. * USEFLOATVOL (set to true if float volume is used)
  273. * ADJUSTVOL (set to true if volume ramp parameters needs adjustment afterwards)
  274. * TO: int32_t (Q4.27) or float
  275. * TI: int32_t (Q4.27) or int16_t (Q0.15) or float
  276. * TA: int32_t (Q4.27)
  277. */
  278. template <int MIXTYPE, bool USEFLOATVOL, bool ADJUSTVOL,
  279. typename TO, typename TI, typename TA>
  280. static void volumeMix(TO *out, size_t outFrames,
  281. const TI *in, TA *aux, bool ramp, AudioMixer::track_t *t);
  282. // multi-format process hooks
  283. template <int MIXTYPE, typename TO, typename TI, typename TA>
  284. static void process_NoResampleOneTrack(state_t* state, int64_t pts);
  285. // multi-format track hooks
  286. template <int MIXTYPE, typename TO, typename TI, typename TA>
  287. static void track__Resample(track_t* t, TO* out, size_t frameCount,
  288. TO* temp __unused, TA* aux);
  289. template <int MIXTYPE, typename TO, typename TI, typename TA>
  290. static void track__NoResample(track_t* t, TO* out, size_t frameCount,
  291. TO* temp __unused, TA* aux);
  292. static void convertMixerFormat(void *out, audio_format_t mixerOutFormat,
  293. void *in, audio_format_t mixerInFormat, size_t sampleCount);
  294. // hook types
  295. enum {
  296. PROCESSTYPE_NORESAMPLEONETRACK,
  297. };
  298. enum {
  299. TRACKTYPE_NOP,
  300. TRACKTYPE_RESAMPLE,
  301. TRACKTYPE_NORESAMPLE,
  302. TRACKTYPE_NORESAMPLEMONO,
  303. };
  304. // functions for determining the proper process and track hooks.
  305. static process_hook_t getProcessHook(int processType, uint32_t channelCount,
  306. audio_format_t mixerInFormat, audio_format_t mixerOutFormat);
  307. static hook_t getTrackHook(int trackType, uint32_t channelCount,
  308. audio_format_t mixerInFormat, audio_format_t mixerOutFormat);
  309. };
  310. // ----------------------------------------------------------------------------
  311. }} // namespace cocos2d { namespace experimental {