audio_stream_ogg_vorbis.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. /**************************************************************************/
  2. /* audio_stream_ogg_vorbis.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_ogg_vorbis.h"
  31. #include "core/io/file_access.h"
  32. #include "core/variant/typed_array.h"
  33. #include <ogg/ogg.h>
  34. int AudioStreamPlaybackOggVorbis::_mix_internal(AudioFrame *p_buffer, int p_frames) {
  35. ERR_FAIL_COND_V(!ready, 0);
  36. if (!active) {
  37. return 0;
  38. }
  39. int todo = p_frames;
  40. int beat_length_frames = -1;
  41. bool beat_loop = vorbis_stream->has_loop();
  42. if (beat_loop && vorbis_stream->get_bpm() > 0 && vorbis_stream->get_beat_count() > 0) {
  43. beat_length_frames = vorbis_stream->get_beat_count() * vorbis_data->get_sampling_rate() * 60 / vorbis_stream->get_bpm();
  44. }
  45. while (todo > 0 && active) {
  46. AudioFrame *buffer = p_buffer;
  47. buffer += p_frames - todo;
  48. int to_mix = todo;
  49. if (beat_length_frames >= 0 && (beat_length_frames - (int)frames_mixed) < to_mix) {
  50. to_mix = MAX(0, beat_length_frames - (int)frames_mixed);
  51. }
  52. int mixed = _mix_frames_vorbis(buffer, to_mix);
  53. ERR_FAIL_COND_V(mixed < 0, 0);
  54. todo -= mixed;
  55. frames_mixed += mixed;
  56. if (loop_fade_remaining < FADE_SIZE) {
  57. int to_fade = loop_fade_remaining + MIN(FADE_SIZE - loop_fade_remaining, mixed);
  58. for (int i = loop_fade_remaining; i < to_fade; i++) {
  59. buffer[i - loop_fade_remaining] += loop_fade[i] * (float(FADE_SIZE - i) / float(FADE_SIZE));
  60. }
  61. loop_fade_remaining = to_fade;
  62. }
  63. if (beat_length_frames >= 0) {
  64. /**
  65. * Length determined by beat length
  66. * This code is commented out because, in practice, it is preferred that the fade
  67. * is done by the transitioner and this stream just goes on until it ends while fading out.
  68. *
  69. * End fade implementation is left here for reference in case at some point this feature
  70. * is desired.
  71. if (!beat_loop && (int)frames_mixed > beat_length_frames - FADE_SIZE) {
  72. print_line("beat length fade/after mix?");
  73. //No loop, just fade and finish
  74. for (int i = 0; i < mixed; i++) {
  75. int idx = frames_mixed + i - mixed;
  76. buffer[i] *= 1.0 - float(MAX(0, (idx - (beat_length_frames - FADE_SIZE)))) / float(FADE_SIZE);
  77. }
  78. if ((int)frames_mixed == beat_length_frames) {
  79. for (int i = p_frames - todo; i < p_frames; i++) {
  80. p_buffer[i] = AudioFrame(0, 0);
  81. }
  82. active = false;
  83. break;
  84. }
  85. } else
  86. **/
  87. if (beat_loop && beat_length_frames <= (int)frames_mixed) {
  88. // End of file when doing beat-based looping. <= used instead of == because importer editing
  89. if (!have_packets_left && !have_samples_left) {
  90. //Nothing remaining, so do nothing.
  91. loop_fade_remaining = FADE_SIZE;
  92. } else {
  93. // Add some loop fade;
  94. int faded_mix = _mix_frames_vorbis(loop_fade, FADE_SIZE);
  95. for (int i = faded_mix; i < FADE_SIZE; i++) {
  96. // In case lesss was mixed, pad with zeros
  97. loop_fade[i] = AudioFrame(0, 0);
  98. }
  99. loop_fade_remaining = 0;
  100. }
  101. seek(vorbis_stream->loop_offset);
  102. loops++;
  103. // We still have buffer to fill, start from this element in the next iteration.
  104. continue;
  105. }
  106. }
  107. if (!have_packets_left && !have_samples_left) {
  108. // Actual end of file!
  109. bool is_not_empty = mixed > 0 || vorbis_stream->get_length() > 0;
  110. if (vorbis_stream->loop && is_not_empty) {
  111. //loop
  112. seek(vorbis_stream->loop_offset);
  113. loops++;
  114. // We still have buffer to fill, start from this element in the next iteration.
  115. } else {
  116. for (int i = p_frames - todo; i < p_frames; i++) {
  117. p_buffer[i] = AudioFrame(0, 0);
  118. }
  119. active = false;
  120. }
  121. }
  122. }
  123. return p_frames - todo;
  124. }
  125. int AudioStreamPlaybackOggVorbis::_mix_frames_vorbis(AudioFrame *p_buffer, int p_frames) {
  126. ERR_FAIL_COND_V(!ready, 0);
  127. if (!have_samples_left) {
  128. ogg_packet *packet = nullptr;
  129. int err;
  130. if (!vorbis_data_playback->next_ogg_packet(&packet)) {
  131. have_packets_left = false;
  132. WARN_PRINT("ran out of packets in stream");
  133. return -1;
  134. }
  135. err = vorbis_synthesis(&block, packet);
  136. ERR_FAIL_COND_V_MSG(err != 0, 0, "Error during vorbis synthesis " + itos(err));
  137. err = vorbis_synthesis_blockin(&dsp_state, &block);
  138. ERR_FAIL_COND_V_MSG(err != 0, 0, "Error during vorbis block processing " + itos(err));
  139. have_packets_left = !packet->e_o_s;
  140. }
  141. float **pcm; // Accessed with pcm[channel_idx][sample_idx].
  142. int frames = vorbis_synthesis_pcmout(&dsp_state, &pcm);
  143. if (frames > p_frames) {
  144. frames = p_frames;
  145. have_samples_left = true;
  146. } else {
  147. have_samples_left = false;
  148. }
  149. if (info.channels > 1) {
  150. for (int frame = 0; frame < frames; frame++) {
  151. p_buffer[frame].l = pcm[0][frame];
  152. p_buffer[frame].r = pcm[1][frame];
  153. }
  154. } else {
  155. for (int frame = 0; frame < frames; frame++) {
  156. p_buffer[frame].l = pcm[0][frame];
  157. p_buffer[frame].r = pcm[0][frame];
  158. }
  159. }
  160. vorbis_synthesis_read(&dsp_state, frames);
  161. return frames;
  162. }
  163. float AudioStreamPlaybackOggVorbis::get_stream_sampling_rate() {
  164. return vorbis_data->get_sampling_rate();
  165. }
  166. bool AudioStreamPlaybackOggVorbis::_alloc_vorbis() {
  167. vorbis_info_init(&info);
  168. info_is_allocated = true;
  169. vorbis_comment_init(&comment);
  170. comment_is_allocated = true;
  171. ERR_FAIL_COND_V(vorbis_data.is_null(), false);
  172. vorbis_data_playback = vorbis_data->instantiate_playback();
  173. ogg_packet *packet;
  174. int err;
  175. for (int i = 0; i < 3; i++) {
  176. if (!vorbis_data_playback->next_ogg_packet(&packet)) {
  177. WARN_PRINT("Not enough packets to parse header");
  178. return false;
  179. }
  180. err = vorbis_synthesis_headerin(&info, &comment, packet);
  181. ERR_FAIL_COND_V_MSG(err != 0, false, "Error parsing header");
  182. }
  183. err = vorbis_synthesis_init(&dsp_state, &info);
  184. ERR_FAIL_COND_V_MSG(err != 0, false, "Error initializing dsp state");
  185. dsp_state_is_allocated = true;
  186. err = vorbis_block_init(&dsp_state, &block);
  187. ERR_FAIL_COND_V_MSG(err != 0, false, "Error initializing block");
  188. block_is_allocated = true;
  189. ready = true;
  190. return true;
  191. }
  192. void AudioStreamPlaybackOggVorbis::start(double p_from_pos) {
  193. ERR_FAIL_COND(!ready);
  194. loop_fade_remaining = FADE_SIZE;
  195. active = true;
  196. seek(p_from_pos);
  197. loops = 0;
  198. begin_resample();
  199. }
  200. void AudioStreamPlaybackOggVorbis::stop() {
  201. active = false;
  202. }
  203. bool AudioStreamPlaybackOggVorbis::is_playing() const {
  204. return active;
  205. }
  206. int AudioStreamPlaybackOggVorbis::get_loop_count() const {
  207. return loops;
  208. }
  209. double AudioStreamPlaybackOggVorbis::get_playback_position() const {
  210. return double(frames_mixed) / (double)vorbis_data->get_sampling_rate();
  211. }
  212. void AudioStreamPlaybackOggVorbis::tag_used_streams() {
  213. vorbis_stream->tag_used(get_playback_position());
  214. }
  215. void AudioStreamPlaybackOggVorbis::seek(double p_time) {
  216. ERR_FAIL_COND(!ready);
  217. ERR_FAIL_COND(vorbis_stream.is_null());
  218. if (!active) {
  219. return;
  220. }
  221. vorbis_synthesis_restart(&dsp_state);
  222. if (p_time >= vorbis_stream->get_length()) {
  223. p_time = 0;
  224. }
  225. frames_mixed = uint32_t(vorbis_data->get_sampling_rate() * p_time);
  226. const int64_t desired_sample = p_time * get_stream_sampling_rate();
  227. if (!vorbis_data_playback->seek_page(desired_sample)) {
  228. WARN_PRINT("seek failed");
  229. return;
  230. }
  231. ogg_packet *packet;
  232. if (!vorbis_data_playback->next_ogg_packet(&packet)) {
  233. WARN_PRINT_ONCE("seeking beyond limits");
  234. return;
  235. }
  236. // The granule position of the page we're seeking through.
  237. int64_t granule_pos = 0;
  238. int headers_remaining = 0;
  239. int samples_in_page = 0;
  240. int err;
  241. while (true) {
  242. if (vorbis_synthesis_idheader(packet)) {
  243. headers_remaining = 3;
  244. }
  245. if (!headers_remaining) {
  246. err = vorbis_synthesis(&block, packet);
  247. ERR_FAIL_COND_MSG(err != 0, "Error during vorbis synthesis " + itos(err));
  248. err = vorbis_synthesis_blockin(&dsp_state, &block);
  249. ERR_FAIL_COND_MSG(err != 0, "Error during vorbis block processing " + itos(err));
  250. int samples_out = vorbis_synthesis_pcmout(&dsp_state, nullptr);
  251. err = vorbis_synthesis_read(&dsp_state, samples_out);
  252. ERR_FAIL_COND_MSG(err != 0, "Error during vorbis read updating " + itos(err));
  253. samples_in_page += samples_out;
  254. } else {
  255. headers_remaining--;
  256. }
  257. if (packet->granulepos != -1 && headers_remaining == 0) {
  258. // This indicates the end of the page.
  259. granule_pos = packet->granulepos;
  260. break;
  261. }
  262. if (packet->e_o_s) {
  263. break;
  264. }
  265. if (!vorbis_data_playback->next_ogg_packet(&packet)) {
  266. // We should get an e_o_s flag before this happens.
  267. WARN_PRINT("Vorbis file ended without warning.");
  268. break;
  269. }
  270. }
  271. int64_t samples_to_burn = samples_in_page - (granule_pos - desired_sample);
  272. if (samples_to_burn > samples_in_page) {
  273. WARN_PRINT("Burning more samples than we have in this page. Check seek algorithm.");
  274. } else if (samples_to_burn < 0) {
  275. WARN_PRINT("Burning negative samples doesn't make sense. Check seek algorithm.");
  276. }
  277. // Seek again, this time we'll burn a specific number of samples instead of all of them.
  278. if (!vorbis_data_playback->seek_page(desired_sample)) {
  279. WARN_PRINT("seek failed");
  280. return;
  281. }
  282. if (!vorbis_data_playback->next_ogg_packet(&packet)) {
  283. WARN_PRINT_ONCE("seeking beyond limits");
  284. return;
  285. }
  286. vorbis_synthesis_restart(&dsp_state);
  287. while (true) {
  288. if (vorbis_synthesis_idheader(packet)) {
  289. headers_remaining = 3;
  290. }
  291. if (!headers_remaining) {
  292. err = vorbis_synthesis(&block, packet);
  293. ERR_FAIL_COND_MSG(err != 0, "Error during vorbis synthesis " + itos(err));
  294. err = vorbis_synthesis_blockin(&dsp_state, &block);
  295. ERR_FAIL_COND_MSG(err != 0, "Error during vorbis block processing " + itos(err));
  296. int samples_out = vorbis_synthesis_pcmout(&dsp_state, nullptr);
  297. int read_samples = samples_to_burn > samples_out ? samples_out : samples_to_burn;
  298. err = vorbis_synthesis_read(&dsp_state, samples_out);
  299. ERR_FAIL_COND_MSG(err != 0, "Error during vorbis read updating " + itos(err));
  300. samples_to_burn -= read_samples;
  301. if (samples_to_burn <= 0) {
  302. break;
  303. }
  304. } else {
  305. headers_remaining--;
  306. }
  307. if (packet->granulepos != -1 && headers_remaining == 0) {
  308. // This indicates the end of the page.
  309. break;
  310. }
  311. if (packet->e_o_s) {
  312. break;
  313. }
  314. if (!vorbis_data_playback->next_ogg_packet(&packet)) {
  315. // We should get an e_o_s flag before this happens.
  316. WARN_PRINT("Vorbis file ended without warning.");
  317. break;
  318. }
  319. }
  320. }
  321. AudioStreamPlaybackOggVorbis::~AudioStreamPlaybackOggVorbis() {
  322. if (block_is_allocated) {
  323. vorbis_block_clear(&block);
  324. }
  325. if (dsp_state_is_allocated) {
  326. vorbis_dsp_clear(&dsp_state);
  327. }
  328. if (comment_is_allocated) {
  329. vorbis_comment_clear(&comment);
  330. }
  331. if (info_is_allocated) {
  332. vorbis_info_clear(&info);
  333. }
  334. }
  335. Ref<AudioStreamPlayback> AudioStreamOggVorbis::instantiate_playback() {
  336. Ref<AudioStreamPlaybackOggVorbis> ovs;
  337. ERR_FAIL_COND_V(packet_sequence.is_null(), nullptr);
  338. ovs.instantiate();
  339. ovs->vorbis_stream = Ref<AudioStreamOggVorbis>(this);
  340. ovs->vorbis_data = packet_sequence;
  341. ovs->frames_mixed = 0;
  342. ovs->active = false;
  343. ovs->loops = 0;
  344. if (ovs->_alloc_vorbis()) {
  345. return ovs;
  346. }
  347. // Failed to allocate data structures.
  348. return nullptr;
  349. }
  350. String AudioStreamOggVorbis::get_stream_name() const {
  351. return ""; //return stream_name;
  352. }
  353. void AudioStreamOggVorbis::maybe_update_info() {
  354. ERR_FAIL_COND(packet_sequence.is_null());
  355. vorbis_info info;
  356. vorbis_comment comment;
  357. int err;
  358. vorbis_info_init(&info);
  359. vorbis_comment_init(&comment);
  360. Ref<OggPacketSequencePlayback> packet_sequence_playback = packet_sequence->instantiate_playback();
  361. for (int i = 0; i < 3; i++) {
  362. ogg_packet *packet;
  363. if (!packet_sequence_playback->next_ogg_packet(&packet)) {
  364. WARN_PRINT("Failed to get header packet");
  365. break;
  366. }
  367. if (i == 0) {
  368. packet->b_o_s = 1;
  369. ERR_FAIL_COND(!vorbis_synthesis_idheader(packet));
  370. }
  371. err = vorbis_synthesis_headerin(&info, &comment, packet);
  372. ERR_FAIL_COND_MSG(err != 0, "Error parsing header packet " + itos(i) + ": " + itos(err));
  373. }
  374. packet_sequence->set_sampling_rate(info.rate);
  375. vorbis_comment_clear(&comment);
  376. vorbis_info_clear(&info);
  377. }
  378. void AudioStreamOggVorbis::set_packet_sequence(Ref<OggPacketSequence> p_packet_sequence) {
  379. packet_sequence = p_packet_sequence;
  380. if (packet_sequence.is_valid()) {
  381. maybe_update_info();
  382. }
  383. }
  384. Ref<OggPacketSequence> AudioStreamOggVorbis::get_packet_sequence() const {
  385. return packet_sequence;
  386. }
  387. void AudioStreamOggVorbis::set_loop(bool p_enable) {
  388. loop = p_enable;
  389. }
  390. bool AudioStreamOggVorbis::has_loop() const {
  391. return loop;
  392. }
  393. void AudioStreamOggVorbis::set_loop_offset(double p_seconds) {
  394. loop_offset = p_seconds;
  395. }
  396. double AudioStreamOggVorbis::get_loop_offset() const {
  397. return loop_offset;
  398. }
  399. double AudioStreamOggVorbis::get_length() const {
  400. ERR_FAIL_COND_V(packet_sequence.is_null(), 0);
  401. return packet_sequence->get_length();
  402. }
  403. void AudioStreamOggVorbis::set_bpm(double p_bpm) {
  404. ERR_FAIL_COND(p_bpm < 0);
  405. bpm = p_bpm;
  406. emit_changed();
  407. }
  408. double AudioStreamOggVorbis::get_bpm() const {
  409. return bpm;
  410. }
  411. void AudioStreamOggVorbis::set_beat_count(int p_beat_count) {
  412. ERR_FAIL_COND(p_beat_count < 0);
  413. beat_count = p_beat_count;
  414. emit_changed();
  415. }
  416. int AudioStreamOggVorbis::get_beat_count() const {
  417. return beat_count;
  418. }
  419. void AudioStreamOggVorbis::set_bar_beats(int p_bar_beats) {
  420. ERR_FAIL_COND(p_bar_beats < 2);
  421. bar_beats = p_bar_beats;
  422. emit_changed();
  423. }
  424. int AudioStreamOggVorbis::get_bar_beats() const {
  425. return bar_beats;
  426. }
  427. bool AudioStreamOggVorbis::is_monophonic() const {
  428. return false;
  429. }
  430. void AudioStreamOggVorbis::_bind_methods() {
  431. ClassDB::bind_method(D_METHOD("set_packet_sequence", "packet_sequence"), &AudioStreamOggVorbis::set_packet_sequence);
  432. ClassDB::bind_method(D_METHOD("get_packet_sequence"), &AudioStreamOggVorbis::get_packet_sequence);
  433. ClassDB::bind_method(D_METHOD("set_loop", "enable"), &AudioStreamOggVorbis::set_loop);
  434. ClassDB::bind_method(D_METHOD("has_loop"), &AudioStreamOggVorbis::has_loop);
  435. ClassDB::bind_method(D_METHOD("set_loop_offset", "seconds"), &AudioStreamOggVorbis::set_loop_offset);
  436. ClassDB::bind_method(D_METHOD("get_loop_offset"), &AudioStreamOggVorbis::get_loop_offset);
  437. ClassDB::bind_method(D_METHOD("set_bpm", "bpm"), &AudioStreamOggVorbis::set_bpm);
  438. ClassDB::bind_method(D_METHOD("get_bpm"), &AudioStreamOggVorbis::get_bpm);
  439. ClassDB::bind_method(D_METHOD("set_beat_count", "count"), &AudioStreamOggVorbis::set_beat_count);
  440. ClassDB::bind_method(D_METHOD("get_beat_count"), &AudioStreamOggVorbis::get_beat_count);
  441. ClassDB::bind_method(D_METHOD("set_bar_beats", "count"), &AudioStreamOggVorbis::set_bar_beats);
  442. ClassDB::bind_method(D_METHOD("get_bar_beats"), &AudioStreamOggVorbis::get_bar_beats);
  443. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "packet_sequence", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "set_packet_sequence", "get_packet_sequence");
  444. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "bpm", PROPERTY_HINT_RANGE, "0,400,0.01,or_greater"), "set_bpm", "get_bpm");
  445. ADD_PROPERTY(PropertyInfo(Variant::INT, "beat_count", PROPERTY_HINT_RANGE, "0,512,1,or_greater"), "set_beat_count", "get_beat_count");
  446. ADD_PROPERTY(PropertyInfo(Variant::INT, "bar_beats", PROPERTY_HINT_RANGE, "2,32,1,or_greater"), "set_bar_beats", "get_bar_beats");
  447. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "loop"), "set_loop", "has_loop");
  448. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "loop_offset"), "set_loop_offset", "get_loop_offset");
  449. }
  450. AudioStreamOggVorbis::AudioStreamOggVorbis() {}
  451. AudioStreamOggVorbis::~AudioStreamOggVorbis() {}