2
0

audio_stream_wav.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233
  1. /**************************************************************************/
  2. /* audio_stream_wav.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "audio_stream_wav.h"
  31. #include "core/io/file_access_memory.h"
  32. #include "core/io/marshalls.h"
  33. const float TRIM_DB_LIMIT = -50;
  34. const int TRIM_FADE_OUT_FRAMES = 500;
  35. void AudioStreamPlaybackWAV::start(double p_from_pos) {
  36. if (base->format == AudioStreamWAV::FORMAT_IMA_ADPCM) {
  37. //no seeking in IMA_ADPCM
  38. for (int i = 0; i < 2; i++) {
  39. ima_adpcm[i].step_index = 0;
  40. ima_adpcm[i].predictor = 0;
  41. ima_adpcm[i].loop_step_index = 0;
  42. ima_adpcm[i].loop_predictor = 0;
  43. ima_adpcm[i].last_nibble = -1;
  44. ima_adpcm[i].loop_pos = 0x7FFFFFFF;
  45. ima_adpcm[i].window_ofs = 0;
  46. }
  47. offset = 0;
  48. } else {
  49. seek(p_from_pos);
  50. }
  51. sign = 1;
  52. active = true;
  53. }
  54. void AudioStreamPlaybackWAV::stop() {
  55. active = false;
  56. }
  57. bool AudioStreamPlaybackWAV::is_playing() const {
  58. return active;
  59. }
  60. int AudioStreamPlaybackWAV::get_loop_count() const {
  61. return 0;
  62. }
  63. double AudioStreamPlaybackWAV::get_playback_position() const {
  64. return float(offset >> MIX_FRAC_BITS) / base->mix_rate;
  65. }
  66. void AudioStreamPlaybackWAV::seek(double p_time) {
  67. if (base->format == AudioStreamWAV::FORMAT_IMA_ADPCM) {
  68. return; //no seeking in ima-adpcm
  69. }
  70. double max = base->get_length();
  71. if (p_time < 0) {
  72. p_time = 0;
  73. } else if (p_time >= max) {
  74. p_time = max - 0.001;
  75. }
  76. offset = uint64_t(p_time * base->mix_rate) << MIX_FRAC_BITS;
  77. }
  78. template <typename Depth, bool is_stereo, bool is_ima_adpcm, bool is_qoa>
  79. void AudioStreamPlaybackWAV::do_resample(const Depth *p_src, AudioFrame *p_dst, int64_t &p_offset, int32_t &p_increment, uint32_t p_amount, IMA_ADPCM_State *p_ima_adpcm, QOA_State *p_qoa) {
  80. // this function will be compiled branchless by any decent compiler
  81. int32_t final = 0, final_r = 0, next = 0, next_r = 0;
  82. while (p_amount) {
  83. p_amount--;
  84. int64_t pos = p_offset >> MIX_FRAC_BITS;
  85. if (is_stereo && !is_ima_adpcm && !is_qoa) {
  86. pos <<= 1;
  87. }
  88. if (is_ima_adpcm) {
  89. int64_t sample_pos = pos + p_ima_adpcm[0].window_ofs;
  90. while (sample_pos > p_ima_adpcm[0].last_nibble) {
  91. static const int16_t _ima_adpcm_step_table[89] = {
  92. 7, 8, 9, 10, 11, 12, 13, 14, 16, 17,
  93. 19, 21, 23, 25, 28, 31, 34, 37, 41, 45,
  94. 50, 55, 60, 66, 73, 80, 88, 97, 107, 118,
  95. 130, 143, 157, 173, 190, 209, 230, 253, 279, 307,
  96. 337, 371, 408, 449, 494, 544, 598, 658, 724, 796,
  97. 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066,
  98. 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358,
  99. 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899,
  100. 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767
  101. };
  102. static const int8_t _ima_adpcm_index_table[16] = {
  103. -1, -1, -1, -1, 2, 4, 6, 8,
  104. -1, -1, -1, -1, 2, 4, 6, 8
  105. };
  106. for (int i = 0; i < (is_stereo ? 2 : 1); i++) {
  107. int16_t nibble, diff, step;
  108. p_ima_adpcm[i].last_nibble++;
  109. uint8_t nbb = p_src[(p_ima_adpcm[i].last_nibble >> 1) * (is_stereo ? 2 : 1) + i];
  110. nibble = (p_ima_adpcm[i].last_nibble & 1) ? (nbb >> 4) : (nbb & 0xF);
  111. step = _ima_adpcm_step_table[p_ima_adpcm[i].step_index];
  112. p_ima_adpcm[i].step_index += _ima_adpcm_index_table[nibble];
  113. if (p_ima_adpcm[i].step_index < 0) {
  114. p_ima_adpcm[i].step_index = 0;
  115. }
  116. if (p_ima_adpcm[i].step_index > 88) {
  117. p_ima_adpcm[i].step_index = 88;
  118. }
  119. diff = step >> 3;
  120. if (nibble & 1) {
  121. diff += step >> 2;
  122. }
  123. if (nibble & 2) {
  124. diff += step >> 1;
  125. }
  126. if (nibble & 4) {
  127. diff += step;
  128. }
  129. if (nibble & 8) {
  130. diff = -diff;
  131. }
  132. p_ima_adpcm[i].predictor += diff;
  133. if (p_ima_adpcm[i].predictor < -0x8000) {
  134. p_ima_adpcm[i].predictor = -0x8000;
  135. } else if (p_ima_adpcm[i].predictor > 0x7FFF) {
  136. p_ima_adpcm[i].predictor = 0x7FFF;
  137. }
  138. /* store loop if there */
  139. if (p_ima_adpcm[i].last_nibble == p_ima_adpcm[i].loop_pos) {
  140. p_ima_adpcm[i].loop_step_index = p_ima_adpcm[i].step_index;
  141. p_ima_adpcm[i].loop_predictor = p_ima_adpcm[i].predictor;
  142. }
  143. //printf("%i - %i - pred %i\n",int(p_ima_adpcm[i].last_nibble),int(nibble),int(p_ima_adpcm[i].predictor));
  144. }
  145. }
  146. final = p_ima_adpcm[0].predictor;
  147. if (is_stereo) {
  148. final_r = p_ima_adpcm[1].predictor;
  149. }
  150. } else {
  151. if (is_qoa) {
  152. if (pos != p_qoa->cache_pos) { // Prevents triple decoding on lower mix rates.
  153. for (int i = 0; i < 2; i++) {
  154. // Sign operations prevent triple decoding on backward loops, maxing prevents pop.
  155. uint32_t interp_pos = MIN(pos + (i * sign) + (sign < 0), p_qoa->desc.samples - 1);
  156. uint32_t new_data_ofs = 8 + interp_pos / QOA_FRAME_LEN * p_qoa->frame_len;
  157. if (p_qoa->data_ofs != new_data_ofs) {
  158. p_qoa->data_ofs = new_data_ofs;
  159. const uint8_t *ofs_src = (uint8_t *)p_src + p_qoa->data_ofs;
  160. qoa_decode_frame(ofs_src, p_qoa->frame_len, &p_qoa->desc, p_qoa->dec.ptr(), &p_qoa->dec_len);
  161. }
  162. uint32_t dec_idx = (interp_pos % QOA_FRAME_LEN) * p_qoa->desc.channels;
  163. if ((sign > 0 && i == 0) || (sign < 0 && i == 1)) {
  164. final = p_qoa->dec[dec_idx];
  165. p_qoa->cache[0] = final;
  166. if (is_stereo) {
  167. final_r = p_qoa->dec[dec_idx + 1];
  168. p_qoa->cache_r[0] = final_r;
  169. }
  170. } else {
  171. next = p_qoa->dec[dec_idx];
  172. p_qoa->cache[1] = next;
  173. if (is_stereo) {
  174. next_r = p_qoa->dec[dec_idx + 1];
  175. p_qoa->cache_r[1] = next_r;
  176. }
  177. }
  178. }
  179. p_qoa->cache_pos = pos;
  180. } else {
  181. final = p_qoa->cache[0];
  182. if (is_stereo) {
  183. final_r = p_qoa->cache_r[0];
  184. }
  185. next = p_qoa->cache[1];
  186. if (is_stereo) {
  187. next_r = p_qoa->cache_r[1];
  188. }
  189. }
  190. } else {
  191. final = p_src[pos];
  192. if (is_stereo) {
  193. final_r = p_src[pos + 1];
  194. }
  195. if constexpr (sizeof(Depth) == 1) { /* conditions will not exist anymore when compiled! */
  196. final <<= 8;
  197. if (is_stereo) {
  198. final_r <<= 8;
  199. }
  200. }
  201. if (is_stereo) {
  202. next = p_src[pos + 2];
  203. next_r = p_src[pos + 3];
  204. } else {
  205. next = p_src[pos + 1];
  206. }
  207. if constexpr (sizeof(Depth) == 1) {
  208. next <<= 8;
  209. if (is_stereo) {
  210. next_r <<= 8;
  211. }
  212. }
  213. }
  214. int32_t frac = int64_t(p_offset & MIX_FRAC_MASK);
  215. final = final + ((next - final) * frac >> MIX_FRAC_BITS);
  216. if (is_stereo) {
  217. final_r = final_r + ((next_r - final_r) * frac >> MIX_FRAC_BITS);
  218. }
  219. }
  220. if (!is_stereo) {
  221. final_r = final; //copy to right channel if stereo
  222. }
  223. p_dst->left = final / 32767.0;
  224. p_dst->right = final_r / 32767.0;
  225. p_dst++;
  226. p_offset += p_increment;
  227. }
  228. }
  229. int AudioStreamPlaybackWAV::mix(AudioFrame *p_buffer, float p_rate_scale, int p_frames) {
  230. if (base->data.is_empty() || !active) {
  231. for (int i = 0; i < p_frames; i++) {
  232. p_buffer[i] = AudioFrame(0, 0);
  233. }
  234. return 0;
  235. }
  236. int len = base->data_bytes;
  237. switch (base->format) {
  238. case AudioStreamWAV::FORMAT_8_BITS:
  239. len /= 1;
  240. break;
  241. case AudioStreamWAV::FORMAT_16_BITS:
  242. len /= 2;
  243. break;
  244. case AudioStreamWAV::FORMAT_IMA_ADPCM:
  245. len *= 2;
  246. break;
  247. case AudioStreamWAV::FORMAT_QOA:
  248. len = qoa.desc.samples * qoa.desc.channels;
  249. break;
  250. }
  251. if (base->stereo) {
  252. len /= 2;
  253. }
  254. /* some 64-bit fixed point precaches */
  255. int64_t loop_begin_fp = ((int64_t)base->loop_begin << MIX_FRAC_BITS);
  256. int64_t loop_end_fp = ((int64_t)base->loop_end << MIX_FRAC_BITS);
  257. int64_t length_fp = ((int64_t)len << MIX_FRAC_BITS);
  258. int64_t begin_limit = (base->loop_mode != AudioStreamWAV::LOOP_DISABLED) ? loop_begin_fp : 0;
  259. int64_t end_limit = (base->loop_mode != AudioStreamWAV::LOOP_DISABLED) ? loop_end_fp : length_fp - MIX_FRAC_LEN;
  260. bool is_stereo = base->stereo;
  261. int32_t todo = p_frames;
  262. if (base->loop_mode == AudioStreamWAV::LOOP_BACKWARD) {
  263. sign = -1;
  264. }
  265. float base_rate = AudioServer::get_singleton()->get_mix_rate();
  266. float srate = base->mix_rate;
  267. srate *= p_rate_scale;
  268. float playback_speed_scale = AudioServer::get_singleton()->get_playback_speed_scale();
  269. float fincrement = (srate * playback_speed_scale) / base_rate;
  270. int32_t increment = int32_t(MAX(fincrement * MIX_FRAC_LEN, 1));
  271. increment *= sign;
  272. //looping
  273. AudioStreamWAV::LoopMode loop_format = base->loop_mode;
  274. AudioStreamWAV::Format format = base->format;
  275. /* audio data */
  276. const uint8_t *data = base->data.ptr() + AudioStreamWAV::DATA_PAD;
  277. AudioFrame *dst_buff = p_buffer;
  278. if (format == AudioStreamWAV::FORMAT_IMA_ADPCM) {
  279. if (loop_format != AudioStreamWAV::LOOP_DISABLED) {
  280. ima_adpcm[0].loop_pos = loop_begin_fp >> MIX_FRAC_BITS;
  281. ima_adpcm[1].loop_pos = loop_begin_fp >> MIX_FRAC_BITS;
  282. loop_format = AudioStreamWAV::LOOP_FORWARD;
  283. }
  284. }
  285. while (todo > 0) {
  286. int64_t limit = 0;
  287. int32_t target = 0, aux = 0;
  288. /** LOOP CHECKING **/
  289. if (increment < 0) {
  290. /* going backwards */
  291. if (loop_format != AudioStreamWAV::LOOP_DISABLED && offset < loop_begin_fp) {
  292. /* loopstart reached */
  293. if (loop_format == AudioStreamWAV::LOOP_PINGPONG) {
  294. /* bounce ping pong */
  295. offset = loop_begin_fp + (loop_begin_fp - offset);
  296. increment = -increment;
  297. sign *= -1;
  298. } else {
  299. /* go to loop-end */
  300. offset = loop_end_fp - (loop_begin_fp - offset);
  301. }
  302. } else {
  303. /* check for sample not reaching beginning */
  304. if (offset < 0) {
  305. active = false;
  306. break;
  307. }
  308. }
  309. } else {
  310. /* going forward */
  311. if (loop_format != AudioStreamWAV::LOOP_DISABLED && offset >= loop_end_fp) {
  312. /* loopend reached */
  313. if (loop_format == AudioStreamWAV::LOOP_PINGPONG) {
  314. /* bounce ping pong */
  315. offset = loop_end_fp - (offset - loop_end_fp);
  316. increment = -increment;
  317. sign *= -1;
  318. } else {
  319. /* go to loop-begin */
  320. if (format == AudioStreamWAV::FORMAT_IMA_ADPCM) {
  321. for (int i = 0; i < 2; i++) {
  322. ima_adpcm[i].step_index = ima_adpcm[i].loop_step_index;
  323. ima_adpcm[i].predictor = ima_adpcm[i].loop_predictor;
  324. ima_adpcm[i].last_nibble = loop_begin_fp >> MIX_FRAC_BITS;
  325. }
  326. offset = loop_begin_fp;
  327. } else {
  328. offset = loop_begin_fp + (offset - loop_end_fp);
  329. }
  330. }
  331. } else {
  332. /* no loop, check for end of sample */
  333. if (offset >= length_fp) {
  334. active = false;
  335. break;
  336. }
  337. }
  338. }
  339. /** MIXCOUNT COMPUTING **/
  340. /* next possible limit (looppoints or sample begin/end */
  341. limit = (increment < 0) ? begin_limit : end_limit;
  342. /* compute what is shorter, the todo or the limit? */
  343. aux = (limit - offset) / increment + 1;
  344. target = (aux < todo) ? aux : todo; /* mix target is the shorter buffer */
  345. /* check just in case */
  346. if (target <= 0) {
  347. active = false;
  348. break;
  349. }
  350. todo -= target;
  351. switch (base->format) {
  352. case AudioStreamWAV::FORMAT_8_BITS: {
  353. if (is_stereo) {
  354. do_resample<int8_t, true, false, false>((int8_t *)data, dst_buff, offset, increment, target, ima_adpcm, &qoa);
  355. } else {
  356. do_resample<int8_t, false, false, false>((int8_t *)data, dst_buff, offset, increment, target, ima_adpcm, &qoa);
  357. }
  358. } break;
  359. case AudioStreamWAV::FORMAT_16_BITS: {
  360. if (is_stereo) {
  361. do_resample<int16_t, true, false, false>((int16_t *)data, dst_buff, offset, increment, target, ima_adpcm, &qoa);
  362. } else {
  363. do_resample<int16_t, false, false, false>((int16_t *)data, dst_buff, offset, increment, target, ima_adpcm, &qoa);
  364. }
  365. } break;
  366. case AudioStreamWAV::FORMAT_IMA_ADPCM: {
  367. if (is_stereo) {
  368. do_resample<int8_t, true, true, false>((int8_t *)data, dst_buff, offset, increment, target, ima_adpcm, &qoa);
  369. } else {
  370. do_resample<int8_t, false, true, false>((int8_t *)data, dst_buff, offset, increment, target, ima_adpcm, &qoa);
  371. }
  372. } break;
  373. case AudioStreamWAV::FORMAT_QOA: {
  374. if (is_stereo) {
  375. do_resample<uint8_t, true, false, true>((uint8_t *)data, dst_buff, offset, increment, target, ima_adpcm, &qoa);
  376. } else {
  377. do_resample<uint8_t, false, false, true>((uint8_t *)data, dst_buff, offset, increment, target, ima_adpcm, &qoa);
  378. }
  379. } break;
  380. }
  381. dst_buff += target;
  382. }
  383. if (todo) {
  384. int mixed_frames = p_frames - todo;
  385. //bit was missing from mix
  386. int todo_ofs = p_frames - todo;
  387. for (int i = todo_ofs; i < p_frames; i++) {
  388. p_buffer[i] = AudioFrame(0, 0);
  389. }
  390. return mixed_frames;
  391. }
  392. return p_frames;
  393. }
  394. void AudioStreamPlaybackWAV::tag_used_streams() {
  395. base->tag_used(get_playback_position());
  396. }
  397. void AudioStreamPlaybackWAV::set_is_sample(bool p_is_sample) {
  398. _is_sample = p_is_sample;
  399. }
  400. bool AudioStreamPlaybackWAV::get_is_sample() const {
  401. return _is_sample;
  402. }
  403. Ref<AudioSamplePlayback> AudioStreamPlaybackWAV::get_sample_playback() const {
  404. return sample_playback;
  405. }
  406. void AudioStreamPlaybackWAV::set_sample_playback(const Ref<AudioSamplePlayback> &p_playback) {
  407. sample_playback = p_playback;
  408. if (sample_playback.is_valid()) {
  409. sample_playback->stream_playback = Ref<AudioStreamPlayback>(this);
  410. }
  411. }
  412. AudioStreamPlaybackWAV::AudioStreamPlaybackWAV() {}
  413. AudioStreamPlaybackWAV::~AudioStreamPlaybackWAV() {}
  414. /////////////////////
  415. void AudioStreamWAV::set_format(Format p_format) {
  416. format = p_format;
  417. }
  418. AudioStreamWAV::Format AudioStreamWAV::get_format() const {
  419. return format;
  420. }
  421. void AudioStreamWAV::set_loop_mode(LoopMode p_loop_mode) {
  422. loop_mode = p_loop_mode;
  423. }
  424. AudioStreamWAV::LoopMode AudioStreamWAV::get_loop_mode() const {
  425. return loop_mode;
  426. }
  427. void AudioStreamWAV::set_loop_begin(int p_frame) {
  428. loop_begin = p_frame;
  429. }
  430. int AudioStreamWAV::get_loop_begin() const {
  431. return loop_begin;
  432. }
  433. void AudioStreamWAV::set_loop_end(int p_frame) {
  434. loop_end = p_frame;
  435. }
  436. int AudioStreamWAV::get_loop_end() const {
  437. return loop_end;
  438. }
  439. void AudioStreamWAV::set_mix_rate(int p_hz) {
  440. ERR_FAIL_COND(p_hz == 0);
  441. mix_rate = p_hz;
  442. }
  443. int AudioStreamWAV::get_mix_rate() const {
  444. return mix_rate;
  445. }
  446. void AudioStreamWAV::set_stereo(bool p_enable) {
  447. stereo = p_enable;
  448. }
  449. bool AudioStreamWAV::is_stereo() const {
  450. return stereo;
  451. }
  452. double AudioStreamWAV::get_length() const {
  453. int len = data_bytes;
  454. switch (format) {
  455. case AudioStreamWAV::FORMAT_8_BITS:
  456. len /= 1;
  457. break;
  458. case AudioStreamWAV::FORMAT_16_BITS:
  459. len /= 2;
  460. break;
  461. case AudioStreamWAV::FORMAT_IMA_ADPCM:
  462. len *= 2;
  463. break;
  464. case AudioStreamWAV::FORMAT_QOA:
  465. qoa_desc desc = {};
  466. qoa_decode_header(data.ptr() + DATA_PAD, data_bytes, &desc);
  467. len = desc.samples * desc.channels;
  468. break;
  469. }
  470. if (stereo) {
  471. len /= 2;
  472. }
  473. return double(len) / mix_rate;
  474. }
  475. bool AudioStreamWAV::is_monophonic() const {
  476. return false;
  477. }
  478. void AudioStreamWAV::set_data(const Vector<uint8_t> &p_data) {
  479. AudioServer::get_singleton()->lock();
  480. int src_data_len = p_data.size();
  481. data.clear();
  482. int alloc_len = src_data_len + DATA_PAD * 2;
  483. data.resize(alloc_len);
  484. memset(data.ptr(), 0, alloc_len);
  485. memcpy(data.ptr() + DATA_PAD, p_data.ptr(), src_data_len);
  486. data_bytes = src_data_len;
  487. AudioServer::get_singleton()->unlock();
  488. }
  489. Vector<uint8_t> AudioStreamWAV::get_data() const {
  490. Vector<uint8_t> pv;
  491. if (data_bytes) {
  492. pv.resize(data_bytes);
  493. memcpy(pv.ptrw(), data.ptr() + DATA_PAD, data_bytes);
  494. }
  495. return pv;
  496. }
  497. Error AudioStreamWAV::save_to_wav(const String &p_path) {
  498. if (format == AudioStreamWAV::FORMAT_IMA_ADPCM || format == AudioStreamWAV::FORMAT_QOA) {
  499. WARN_PRINT("Saving IMA_ADPCM and QOA samples is not supported yet");
  500. return ERR_UNAVAILABLE;
  501. }
  502. int sub_chunk_2_size = data_bytes; //Subchunk2Size = Size of data in bytes
  503. // Format code
  504. // 1:PCM format (for 8 or 16 bit)
  505. // 3:IEEE float format
  506. int format_code = (format == FORMAT_IMA_ADPCM) ? 3 : 1;
  507. int n_channels = stereo ? 2 : 1;
  508. long sample_rate = mix_rate;
  509. int byte_pr_sample = 0;
  510. switch (format) {
  511. case AudioStreamWAV::FORMAT_8_BITS:
  512. byte_pr_sample = 1;
  513. break;
  514. case AudioStreamWAV::FORMAT_16_BITS:
  515. case AudioStreamWAV::FORMAT_QOA:
  516. byte_pr_sample = 2;
  517. break;
  518. case AudioStreamWAV::FORMAT_IMA_ADPCM:
  519. byte_pr_sample = 4;
  520. break;
  521. }
  522. String file_path = p_path;
  523. if (file_path.substr(file_path.length() - 4, 4).to_lower() != ".wav") {
  524. file_path += ".wav";
  525. }
  526. Ref<FileAccess> file = FileAccess::open(file_path, FileAccess::WRITE); //Overrides existing file if present
  527. ERR_FAIL_COND_V(file.is_null(), ERR_FILE_CANT_WRITE);
  528. // Create WAV Header
  529. file->store_string("RIFF"); //ChunkID
  530. file->store_32(sub_chunk_2_size + 36); //ChunkSize = 36 + SubChunk2Size (size of entire file minus the 8 bits for this and previous header)
  531. file->store_string("WAVE"); //Format
  532. file->store_string("fmt "); //Subchunk1ID
  533. file->store_32(16); //Subchunk1Size = 16
  534. file->store_16(format_code); //AudioFormat
  535. file->store_16(n_channels); //Number of Channels
  536. file->store_32(sample_rate); //SampleRate
  537. file->store_32(sample_rate * n_channels * byte_pr_sample); //ByteRate
  538. file->store_16(n_channels * byte_pr_sample); //BlockAlign = NumChannels * BytePrSample
  539. file->store_16(byte_pr_sample * 8); //BitsPerSample
  540. file->store_string("data"); //Subchunk2ID
  541. file->store_32(sub_chunk_2_size); //Subchunk2Size
  542. // Add data
  543. Vector<uint8_t> stream_data = get_data();
  544. const uint8_t *read_data = stream_data.ptr();
  545. switch (format) {
  546. case AudioStreamWAV::FORMAT_8_BITS:
  547. for (unsigned int i = 0; i < data_bytes; i++) {
  548. uint8_t data_point = (read_data[i] + 128);
  549. file->store_8(data_point);
  550. }
  551. break;
  552. case AudioStreamWAV::FORMAT_16_BITS:
  553. case AudioStreamWAV::FORMAT_QOA:
  554. for (unsigned int i = 0; i < data_bytes / 2; i++) {
  555. uint16_t data_point = decode_uint16(&read_data[i * 2]);
  556. file->store_16(data_point);
  557. }
  558. break;
  559. case AudioStreamWAV::FORMAT_IMA_ADPCM:
  560. //Unimplemented
  561. break;
  562. }
  563. return OK;
  564. }
  565. Ref<AudioStreamPlayback> AudioStreamWAV::instantiate_playback() {
  566. Ref<AudioStreamPlaybackWAV> sample;
  567. sample.instantiate();
  568. sample->base = Ref<AudioStreamWAV>(this);
  569. if (format == AudioStreamWAV::FORMAT_QOA) {
  570. uint32_t ffp = qoa_decode_header(data.ptr() + DATA_PAD, data_bytes, &sample->qoa.desc);
  571. ERR_FAIL_COND_V(ffp != 8, Ref<AudioStreamPlaybackWAV>());
  572. sample->qoa.frame_len = qoa_max_frame_size(&sample->qoa.desc);
  573. int samples_len = (sample->qoa.desc.samples > QOA_FRAME_LEN ? QOA_FRAME_LEN : sample->qoa.desc.samples);
  574. int dec_len = sample->qoa.desc.channels * samples_len;
  575. sample->qoa.dec.resize(dec_len);
  576. }
  577. return sample;
  578. }
  579. String AudioStreamWAV::get_stream_name() const {
  580. return "";
  581. }
  582. Ref<AudioSample> AudioStreamWAV::generate_sample() const {
  583. Ref<AudioSample> sample;
  584. sample.instantiate();
  585. sample->stream = this;
  586. switch (loop_mode) {
  587. case AudioStreamWAV::LoopMode::LOOP_DISABLED: {
  588. sample->loop_mode = AudioSample::LoopMode::LOOP_DISABLED;
  589. } break;
  590. case AudioStreamWAV::LoopMode::LOOP_FORWARD: {
  591. sample->loop_mode = AudioSample::LoopMode::LOOP_FORWARD;
  592. } break;
  593. case AudioStreamWAV::LoopMode::LOOP_PINGPONG: {
  594. sample->loop_mode = AudioSample::LoopMode::LOOP_PINGPONG;
  595. } break;
  596. case AudioStreamWAV::LoopMode::LOOP_BACKWARD: {
  597. sample->loop_mode = AudioSample::LoopMode::LOOP_BACKWARD;
  598. } break;
  599. }
  600. sample->loop_begin = loop_begin;
  601. sample->loop_end = loop_end;
  602. sample->sample_rate = mix_rate;
  603. return sample;
  604. }
  605. Ref<AudioStreamWAV> AudioStreamWAV::load_from_buffer(const Vector<uint8_t> &p_stream_data, const Dictionary &p_options) {
  606. // /* STEP 1, READ WAVE FILE */
  607. Ref<FileAccessMemory> file;
  608. file.instantiate();
  609. Error err = file->open_custom(p_stream_data.ptr(), p_stream_data.size());
  610. ERR_FAIL_COND_V_MSG(err != OK, Ref<AudioStreamWAV>(), "Cannot create memfile for WAV file buffer.");
  611. /* CHECK RIFF */
  612. char riff[5];
  613. riff[4] = 0;
  614. file->get_buffer((uint8_t *)&riff, 4); //RIFF
  615. if (riff[0] != 'R' || riff[1] != 'I' || riff[2] != 'F' || riff[3] != 'F') {
  616. ERR_FAIL_V_MSG(Ref<AudioStreamWAV>(), vformat("Not a WAV file. File should start with 'RIFF', but found '%s', in file of size %d bytes", riff, file->get_length()));
  617. }
  618. /* GET FILESIZE */
  619. // The file size in header is 8 bytes less than the actual size.
  620. // See https://docs.fileformat.com/audio/wav/
  621. const int FILE_SIZE_HEADER_OFFSET = 8;
  622. uint32_t file_size_header = file->get_32() + FILE_SIZE_HEADER_OFFSET;
  623. uint64_t file_size = file->get_length();
  624. if (file_size != file_size_header) {
  625. WARN_PRINT(vformat("File size %d is %s than the expected size %d.", file_size, file_size > file_size_header ? "larger" : "smaller", file_size_header));
  626. }
  627. /* CHECK WAVE */
  628. char wave[5];
  629. wave[4] = 0;
  630. file->get_buffer((uint8_t *)&wave, 4); //WAVE
  631. if (wave[0] != 'W' || wave[1] != 'A' || wave[2] != 'V' || wave[3] != 'E') {
  632. ERR_FAIL_V_MSG(Ref<AudioStreamWAV>(), vformat("Not a WAV file. Header should contain 'WAVE', but found '%s', in file of size %d bytes", wave, file->get_length()));
  633. }
  634. // Let users override potential loop points from the WAV.
  635. // We parse the WAV loop points only with "Detect From WAV" (0).
  636. int import_loop_mode = p_options["edit/loop_mode"];
  637. int format_bits = 0;
  638. int format_channels = 0;
  639. AudioStreamWAV::LoopMode loop_mode = AudioStreamWAV::LOOP_DISABLED;
  640. uint16_t compression_code = 1;
  641. bool format_found = false;
  642. bool data_found = false;
  643. int format_freq = 0;
  644. int loop_begin = 0;
  645. int loop_end = 0;
  646. int frames = 0;
  647. Vector<float> data;
  648. while (!file->eof_reached()) {
  649. /* chunk */
  650. char chunk_id[4];
  651. file->get_buffer((uint8_t *)&chunk_id, 4); //RIFF
  652. /* chunk size */
  653. uint32_t chunksize = file->get_32();
  654. uint32_t file_pos = file->get_position(); //save file pos, so we can skip to next chunk safely
  655. if (file->eof_reached()) {
  656. //ERR_PRINT("EOF REACH");
  657. break;
  658. }
  659. if (chunk_id[0] == 'f' && chunk_id[1] == 'm' && chunk_id[2] == 't' && chunk_id[3] == ' ' && !format_found) {
  660. /* IS FORMAT CHUNK */
  661. //Issue: #7755 : Not a bug - usage of other formats (format codes) are unsupported in current importer version.
  662. //Consider revision for engine version 3.0
  663. compression_code = file->get_16();
  664. if (compression_code != 1 && compression_code != 3) {
  665. ERR_FAIL_V_MSG(Ref<AudioStreamWAV>(), "Format not supported for WAVE file (not PCM). Save WAVE files as uncompressed PCM or IEEE float instead.");
  666. }
  667. format_channels = file->get_16();
  668. if (format_channels != 1 && format_channels != 2) {
  669. ERR_FAIL_V_MSG(Ref<AudioStreamWAV>(), "Format not supported for WAVE file (not stereo or mono).");
  670. }
  671. format_freq = file->get_32(); //sampling rate
  672. file->get_32(); // average bits/second (unused)
  673. file->get_16(); // block align (unused)
  674. format_bits = file->get_16(); // bits per sample
  675. if (format_bits % 8 || format_bits == 0) {
  676. ERR_FAIL_V_MSG(Ref<AudioStreamWAV>(), "Invalid amount of bits in the sample (should be one of 8, 16, 24 or 32).");
  677. }
  678. if (compression_code == 3 && format_bits % 32) {
  679. ERR_FAIL_V_MSG(Ref<AudioStreamWAV>(), "Invalid amount of bits in the IEEE float sample (should be 32 or 64).");
  680. }
  681. /* Don't need anything else, continue */
  682. format_found = true;
  683. }
  684. if (chunk_id[0] == 'd' && chunk_id[1] == 'a' && chunk_id[2] == 't' && chunk_id[3] == 'a' && !data_found) {
  685. /* IS DATA CHUNK */
  686. data_found = true;
  687. if (!format_found) {
  688. ERR_PRINT("'data' chunk before 'format' chunk found.");
  689. break;
  690. }
  691. uint64_t remaining_bytes = file_size - file_pos;
  692. frames = chunksize;
  693. if (remaining_bytes < chunksize) {
  694. WARN_PRINT("Data chunk size is smaller than expected. Proceeding with actual data size.");
  695. frames = remaining_bytes;
  696. }
  697. ERR_FAIL_COND_V(format_channels == 0, Ref<AudioStreamWAV>());
  698. frames /= format_channels;
  699. frames /= (format_bits >> 3);
  700. /*print_line("chunksize: "+itos(chunksize));
  701. print_line("channels: "+itos(format_channels));
  702. print_line("bits: "+itos(format_bits));
  703. */
  704. data.resize(frames * format_channels);
  705. if (compression_code == 1) {
  706. if (format_bits == 8) {
  707. for (int i = 0; i < frames * format_channels; i++) {
  708. // 8 bit samples are UNSIGNED
  709. data.write[i] = int8_t(file->get_8() - 128) / 128.f;
  710. }
  711. } else if (format_bits == 16) {
  712. for (int i = 0; i < frames * format_channels; i++) {
  713. //16 bit SIGNED
  714. data.write[i] = int16_t(file->get_16()) / 32768.f;
  715. }
  716. } else {
  717. for (int i = 0; i < frames * format_channels; i++) {
  718. //16+ bits samples are SIGNED
  719. // if sample is > 16 bits, just read extra bytes
  720. uint32_t s = 0;
  721. for (int b = 0; b < (format_bits >> 3); b++) {
  722. s |= ((uint32_t)file->get_8()) << (b * 8);
  723. }
  724. s <<= (32 - format_bits);
  725. data.write[i] = (int32_t(s) >> 16) / 32768.f;
  726. }
  727. }
  728. } else if (compression_code == 3) {
  729. if (format_bits == 32) {
  730. for (int i = 0; i < frames * format_channels; i++) {
  731. //32 bit IEEE Float
  732. data.write[i] = file->get_float();
  733. }
  734. } else if (format_bits == 64) {
  735. for (int i = 0; i < frames * format_channels; i++) {
  736. //64 bit IEEE Float
  737. data.write[i] = file->get_double();
  738. }
  739. }
  740. }
  741. // This is commented out due to some weird edge case seemingly in FileAccessMemory, doesn't seem to have any side effects though.
  742. // if (file->eof_reached()) {
  743. // ERR_FAIL_V_MSG(Ref<AudioStreamWAV>(), "Premature end of file.");
  744. // }
  745. }
  746. if (import_loop_mode == 0 && chunk_id[0] == 's' && chunk_id[1] == 'm' && chunk_id[2] == 'p' && chunk_id[3] == 'l') {
  747. // Loop point info!
  748. /**
  749. * Consider exploring next document:
  750. * http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/Docs/RIFFNEW.pdf
  751. * Especially on page:
  752. * 16 - 17
  753. * Timestamp:
  754. * 22:38 06.07.2017 GMT
  755. **/
  756. for (int i = 0; i < 10; i++) {
  757. file->get_32(); // i wish to know why should i do this... no doc!
  758. }
  759. // only read 0x00 (loop forward), 0x01 (loop ping-pong) and 0x02 (loop backward)
  760. // Skip anything else because it's not supported, reserved for future uses or sampler specific
  761. // from https://sites.google.com/site/musicgapi/technical-documents/wav-file-format#smpl (loop type values table)
  762. int loop_type = file->get_32();
  763. if (loop_type == 0x00 || loop_type == 0x01 || loop_type == 0x02) {
  764. if (loop_type == 0x00) {
  765. loop_mode = AudioStreamWAV::LOOP_FORWARD;
  766. } else if (loop_type == 0x01) {
  767. loop_mode = AudioStreamWAV::LOOP_PINGPONG;
  768. } else if (loop_type == 0x02) {
  769. loop_mode = AudioStreamWAV::LOOP_BACKWARD;
  770. }
  771. loop_begin = file->get_32();
  772. loop_end = file->get_32();
  773. }
  774. }
  775. // Move to the start of the next chunk. Note that RIFF requires a padding byte for odd
  776. // chunk sizes.
  777. file->seek(file_pos + chunksize + (chunksize & 1));
  778. }
  779. // STEP 2, APPLY CONVERSIONS
  780. bool is16 = format_bits != 8;
  781. int rate = format_freq;
  782. /*
  783. print_line("Input Sample: ");
  784. print_line("\tframes: " + itos(frames));
  785. print_line("\tformat_channels: " + itos(format_channels));
  786. print_line("\t16bits: " + itos(is16));
  787. print_line("\trate: " + itos(rate));
  788. print_line("\tloop: " + itos(loop));
  789. print_line("\tloop begin: " + itos(loop_begin));
  790. print_line("\tloop end: " + itos(loop_end));
  791. */
  792. //apply frequency limit
  793. bool limit_rate = p_options["force/max_rate"];
  794. int limit_rate_hz = p_options["force/max_rate_hz"];
  795. if (limit_rate && rate > limit_rate_hz && rate > 0 && frames > 0) {
  796. // resample!
  797. int new_data_frames = (int)(frames * (float)limit_rate_hz / (float)rate);
  798. Vector<float> new_data;
  799. new_data.resize(new_data_frames * format_channels);
  800. for (int c = 0; c < format_channels; c++) {
  801. float frac = 0.0;
  802. int ipos = 0;
  803. for (int i = 0; i < new_data_frames; i++) {
  804. // Cubic interpolation should be enough.
  805. float y0 = data[MAX(0, ipos - 1) * format_channels + c];
  806. float y1 = data[ipos * format_channels + c];
  807. float y2 = data[MIN(frames - 1, ipos + 1) * format_channels + c];
  808. float y3 = data[MIN(frames - 1, ipos + 2) * format_channels + c];
  809. new_data.write[i * format_channels + c] = Math::cubic_interpolate(y1, y2, y0, y3, frac);
  810. // update position and always keep fractional part within ]0...1]
  811. // in order to avoid 32bit floating point precision errors
  812. frac += (float)rate / (float)limit_rate_hz;
  813. int tpos = (int)Math::floor(frac);
  814. ipos += tpos;
  815. frac -= tpos;
  816. }
  817. }
  818. if (loop_mode) {
  819. loop_begin = (int)(loop_begin * (float)new_data_frames / (float)frames);
  820. loop_end = (int)(loop_end * (float)new_data_frames / (float)frames);
  821. }
  822. data = new_data;
  823. rate = limit_rate_hz;
  824. frames = new_data_frames;
  825. }
  826. bool normalize = p_options["edit/normalize"];
  827. if (normalize) {
  828. float max = 0.0;
  829. for (int i = 0; i < data.size(); i++) {
  830. float amp = Math::abs(data[i]);
  831. if (amp > max) {
  832. max = amp;
  833. }
  834. }
  835. if (max > 0) {
  836. float mult = 1.0 / max;
  837. for (int i = 0; i < data.size(); i++) {
  838. data.write[i] *= mult;
  839. }
  840. }
  841. }
  842. bool trim = p_options["edit/trim"];
  843. if (trim && (loop_mode == AudioStreamWAV::LOOP_DISABLED) && format_channels > 0) {
  844. int first = 0;
  845. int last = (frames / format_channels) - 1;
  846. bool found = false;
  847. float limit = Math::db_to_linear(TRIM_DB_LIMIT);
  848. for (int i = 0; i < data.size() / format_channels; i++) {
  849. float amp_channel_sum = 0.0;
  850. for (int j = 0; j < format_channels; j++) {
  851. amp_channel_sum += Math::abs(data[(i * format_channels) + j]);
  852. }
  853. float amp = Math::abs(amp_channel_sum / (float)format_channels);
  854. if (!found && amp > limit) {
  855. first = i;
  856. found = true;
  857. }
  858. if (found && amp > limit) {
  859. last = i;
  860. }
  861. }
  862. if (first < last) {
  863. Vector<float> new_data;
  864. new_data.resize((last - first) * format_channels);
  865. for (int i = first; i < last; i++) {
  866. float fade_out_mult = 1.0;
  867. if (last - i < TRIM_FADE_OUT_FRAMES) {
  868. fade_out_mult = ((float)(last - i - 1) / (float)TRIM_FADE_OUT_FRAMES);
  869. }
  870. for (int j = 0; j < format_channels; j++) {
  871. new_data.write[((i - first) * format_channels) + j] = data[(i * format_channels) + j] * fade_out_mult;
  872. }
  873. }
  874. data = new_data;
  875. frames = data.size() / format_channels;
  876. }
  877. }
  878. if (import_loop_mode >= 2) {
  879. loop_mode = (AudioStreamWAV::LoopMode)(import_loop_mode - 1);
  880. loop_begin = p_options["edit/loop_begin"];
  881. loop_end = p_options["edit/loop_end"];
  882. // Wrap around to max frames, so `-1` can be used to select the end, etc.
  883. if (loop_begin < 0) {
  884. loop_begin = CLAMP(loop_begin + frames, 0, frames - 1);
  885. }
  886. if (loop_end < 0) {
  887. loop_end = CLAMP(loop_end + frames, 0, frames - 1);
  888. }
  889. }
  890. int compression = p_options["compress/mode"];
  891. bool force_mono = p_options["force/mono"];
  892. if (force_mono && format_channels == 2) {
  893. Vector<float> new_data;
  894. new_data.resize(data.size() / 2);
  895. for (int i = 0; i < frames; i++) {
  896. new_data.write[i] = (data[i * 2 + 0] + data[i * 2 + 1]) / 2.0;
  897. }
  898. data = new_data;
  899. format_channels = 1;
  900. }
  901. bool force_8_bit = p_options["force/8_bit"];
  902. if (force_8_bit) {
  903. is16 = false;
  904. }
  905. Vector<uint8_t> dst_data;
  906. AudioStreamWAV::Format dst_format;
  907. if (compression == 1) {
  908. dst_format = AudioStreamWAV::FORMAT_IMA_ADPCM;
  909. if (format_channels == 1) {
  910. _compress_ima_adpcm(data, dst_data);
  911. } else {
  912. //byte interleave
  913. Vector<float> left;
  914. Vector<float> right;
  915. int tframes = data.size() / 2;
  916. left.resize(tframes);
  917. right.resize(tframes);
  918. for (int i = 0; i < tframes; i++) {
  919. left.write[i] = data[i * 2 + 0];
  920. right.write[i] = data[i * 2 + 1];
  921. }
  922. Vector<uint8_t> bleft;
  923. Vector<uint8_t> bright;
  924. _compress_ima_adpcm(left, bleft);
  925. _compress_ima_adpcm(right, bright);
  926. int dl = bleft.size();
  927. dst_data.resize(dl * 2);
  928. uint8_t *w = dst_data.ptrw();
  929. const uint8_t *rl = bleft.ptr();
  930. const uint8_t *rr = bright.ptr();
  931. for (int i = 0; i < dl; i++) {
  932. w[i * 2 + 0] = rl[i];
  933. w[i * 2 + 1] = rr[i];
  934. }
  935. }
  936. } else if (compression == 2) {
  937. dst_format = AudioStreamWAV::FORMAT_QOA;
  938. qoa_desc desc = {};
  939. desc.samplerate = rate;
  940. desc.samples = frames;
  941. desc.channels = format_channels;
  942. _compress_qoa(data, dst_data, &desc);
  943. } else {
  944. dst_format = is16 ? AudioStreamWAV::FORMAT_16_BITS : AudioStreamWAV::FORMAT_8_BITS;
  945. dst_data.resize(data.size() * (is16 ? 2 : 1));
  946. {
  947. uint8_t *w = dst_data.ptrw();
  948. int ds = data.size();
  949. for (int i = 0; i < ds; i++) {
  950. if (is16) {
  951. int16_t v = CLAMP(data[i] * 32768, -32768, 32767);
  952. encode_uint16(v, &w[i * 2]);
  953. } else {
  954. int8_t v = CLAMP(data[i] * 128, -128, 127);
  955. w[i] = v;
  956. }
  957. }
  958. }
  959. }
  960. Ref<AudioStreamWAV> sample;
  961. sample.instantiate();
  962. sample->set_data(dst_data);
  963. sample->set_format(dst_format);
  964. sample->set_mix_rate(rate);
  965. sample->set_loop_mode(loop_mode);
  966. sample->set_loop_begin(loop_begin);
  967. sample->set_loop_end(loop_end);
  968. sample->set_stereo(format_channels == 2);
  969. return sample;
  970. }
  971. Ref<AudioStreamWAV> AudioStreamWAV::load_from_file(const String &p_path, const Dictionary &p_options) {
  972. const Vector<uint8_t> stream_data = FileAccess::get_file_as_bytes(p_path);
  973. ERR_FAIL_COND_V_MSG(stream_data.is_empty(), Ref<AudioStreamWAV>(), vformat("Cannot open file '%s'.", p_path));
  974. return load_from_buffer(stream_data, p_options);
  975. }
  976. void AudioStreamWAV::_bind_methods() {
  977. ClassDB::bind_static_method("AudioStreamWAV", D_METHOD("load_from_buffer", "stream_data", "options"), &AudioStreamWAV::load_from_buffer, DEFVAL(Dictionary()));
  978. ClassDB::bind_static_method("AudioStreamWAV", D_METHOD("load_from_file", "path", "options"), &AudioStreamWAV::load_from_file, DEFVAL(Dictionary()));
  979. ClassDB::bind_method(D_METHOD("set_data", "data"), &AudioStreamWAV::set_data);
  980. ClassDB::bind_method(D_METHOD("get_data"), &AudioStreamWAV::get_data);
  981. ClassDB::bind_method(D_METHOD("set_format", "format"), &AudioStreamWAV::set_format);
  982. ClassDB::bind_method(D_METHOD("get_format"), &AudioStreamWAV::get_format);
  983. ClassDB::bind_method(D_METHOD("set_loop_mode", "loop_mode"), &AudioStreamWAV::set_loop_mode);
  984. ClassDB::bind_method(D_METHOD("get_loop_mode"), &AudioStreamWAV::get_loop_mode);
  985. ClassDB::bind_method(D_METHOD("set_loop_begin", "loop_begin"), &AudioStreamWAV::set_loop_begin);
  986. ClassDB::bind_method(D_METHOD("get_loop_begin"), &AudioStreamWAV::get_loop_begin);
  987. ClassDB::bind_method(D_METHOD("set_loop_end", "loop_end"), &AudioStreamWAV::set_loop_end);
  988. ClassDB::bind_method(D_METHOD("get_loop_end"), &AudioStreamWAV::get_loop_end);
  989. ClassDB::bind_method(D_METHOD("set_mix_rate", "mix_rate"), &AudioStreamWAV::set_mix_rate);
  990. ClassDB::bind_method(D_METHOD("get_mix_rate"), &AudioStreamWAV::get_mix_rate);
  991. ClassDB::bind_method(D_METHOD("set_stereo", "stereo"), &AudioStreamWAV::set_stereo);
  992. ClassDB::bind_method(D_METHOD("is_stereo"), &AudioStreamWAV::is_stereo);
  993. ClassDB::bind_method(D_METHOD("save_to_wav", "path"), &AudioStreamWAV::save_to_wav);
  994. ADD_PROPERTY(PropertyInfo(Variant::PACKED_BYTE_ARRAY, "data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "set_data", "get_data");
  995. ADD_PROPERTY(PropertyInfo(Variant::INT, "format", PROPERTY_HINT_ENUM, "8-Bit,16-Bit,IMA ADPCM,Quite OK Audio"), "set_format", "get_format");
  996. ADD_PROPERTY(PropertyInfo(Variant::INT, "loop_mode", PROPERTY_HINT_ENUM, "Disabled,Forward,Ping-Pong,Backward"), "set_loop_mode", "get_loop_mode");
  997. ADD_PROPERTY(PropertyInfo(Variant::INT, "loop_begin"), "set_loop_begin", "get_loop_begin");
  998. ADD_PROPERTY(PropertyInfo(Variant::INT, "loop_end"), "set_loop_end", "get_loop_end");
  999. ADD_PROPERTY(PropertyInfo(Variant::INT, "mix_rate"), "set_mix_rate", "get_mix_rate");
  1000. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "stereo"), "set_stereo", "is_stereo");
  1001. BIND_ENUM_CONSTANT(FORMAT_8_BITS);
  1002. BIND_ENUM_CONSTANT(FORMAT_16_BITS);
  1003. BIND_ENUM_CONSTANT(FORMAT_IMA_ADPCM);
  1004. BIND_ENUM_CONSTANT(FORMAT_QOA);
  1005. BIND_ENUM_CONSTANT(LOOP_DISABLED);
  1006. BIND_ENUM_CONSTANT(LOOP_FORWARD);
  1007. BIND_ENUM_CONSTANT(LOOP_PINGPONG);
  1008. BIND_ENUM_CONSTANT(LOOP_BACKWARD);
  1009. }
  1010. AudioStreamWAV::AudioStreamWAV() {}
  1011. AudioStreamWAV::~AudioStreamWAV() {}