audio_stream_ogg_vorbis.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
  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 "thirdparty/libogg/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 prefered 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_FAIL_COND_V_MSG((err = vorbis_synthesis(&block, packet)), 0, "Error during vorbis synthesis " + itos(err));
  136. ERR_FAIL_COND_V_MSG((err = vorbis_synthesis_blockin(&dsp_state, &block)), 0, "Error during vorbis block processing " + itos(err));
  137. have_packets_left = !packet->e_o_s;
  138. }
  139. float **pcm; // Accessed with pcm[channel_idx][sample_idx].
  140. int frames = vorbis_synthesis_pcmout(&dsp_state, &pcm);
  141. if (frames > p_frames) {
  142. frames = p_frames;
  143. have_samples_left = true;
  144. } else {
  145. have_samples_left = false;
  146. }
  147. if (info.channels > 1) {
  148. for (int frame = 0; frame < frames; frame++) {
  149. p_buffer[frame].l = pcm[0][frame];
  150. p_buffer[frame].r = pcm[1][frame];
  151. }
  152. } else {
  153. for (int frame = 0; frame < frames; frame++) {
  154. p_buffer[frame].l = pcm[0][frame];
  155. p_buffer[frame].r = pcm[0][frame];
  156. }
  157. }
  158. vorbis_synthesis_read(&dsp_state, frames);
  159. return frames;
  160. }
  161. float AudioStreamPlaybackOggVorbis::get_stream_sampling_rate() {
  162. return vorbis_data->get_sampling_rate();
  163. }
  164. bool AudioStreamPlaybackOggVorbis::_alloc_vorbis() {
  165. vorbis_info_init(&info);
  166. info_is_allocated = true;
  167. vorbis_comment_init(&comment);
  168. comment_is_allocated = true;
  169. ERR_FAIL_COND_V(vorbis_data.is_null(), false);
  170. vorbis_data_playback = vorbis_data->instantiate_playback();
  171. ogg_packet *packet;
  172. int err;
  173. for (int i = 0; i < 3; i++) {
  174. if (!vorbis_data_playback->next_ogg_packet(&packet)) {
  175. WARN_PRINT("Not enough packets to parse header");
  176. return false;
  177. }
  178. err = vorbis_synthesis_headerin(&info, &comment, packet);
  179. ERR_FAIL_COND_V_MSG(err != 0, false, "Error parsing header");
  180. }
  181. err = vorbis_synthesis_init(&dsp_state, &info);
  182. ERR_FAIL_COND_V_MSG(err != 0, false, "Error initializing dsp state");
  183. dsp_state_is_allocated = true;
  184. err = vorbis_block_init(&dsp_state, &block);
  185. ERR_FAIL_COND_V_MSG(err != 0, false, "Error initializing block");
  186. block_is_allocated = true;
  187. ready = true;
  188. return true;
  189. }
  190. void AudioStreamPlaybackOggVorbis::start(float p_from_pos) {
  191. ERR_FAIL_COND(!ready);
  192. loop_fade_remaining = FADE_SIZE;
  193. active = true;
  194. seek(p_from_pos);
  195. loops = 0;
  196. begin_resample();
  197. }
  198. void AudioStreamPlaybackOggVorbis::stop() {
  199. active = false;
  200. }
  201. bool AudioStreamPlaybackOggVorbis::is_playing() const {
  202. return active;
  203. }
  204. int AudioStreamPlaybackOggVorbis::get_loop_count() const {
  205. return loops;
  206. }
  207. float AudioStreamPlaybackOggVorbis::get_playback_position() const {
  208. return float(frames_mixed) / vorbis_data->get_sampling_rate();
  209. }
  210. void AudioStreamPlaybackOggVorbis::tag_used_streams() {
  211. vorbis_stream->tag_used(get_playback_position());
  212. }
  213. void AudioStreamPlaybackOggVorbis::seek(float p_time) {
  214. ERR_FAIL_COND(!ready);
  215. ERR_FAIL_COND(vorbis_stream.is_null());
  216. if (!active) {
  217. return;
  218. }
  219. vorbis_synthesis_restart(&dsp_state);
  220. if (p_time >= vorbis_stream->get_length()) {
  221. p_time = 0;
  222. }
  223. frames_mixed = uint32_t(vorbis_data->get_sampling_rate() * p_time);
  224. const int64_t desired_sample = p_time * get_stream_sampling_rate();
  225. if (!vorbis_data_playback->seek_page(desired_sample)) {
  226. WARN_PRINT("seek failed");
  227. return;
  228. }
  229. ogg_packet *packet;
  230. if (!vorbis_data_playback->next_ogg_packet(&packet)) {
  231. WARN_PRINT_ONCE("seeking beyond limits");
  232. return;
  233. }
  234. // The granule position of the page we're seeking through.
  235. int64_t granule_pos = 0;
  236. int headers_remaining = 0;
  237. int samples_in_page = 0;
  238. int err;
  239. while (true) {
  240. if (vorbis_synthesis_idheader(packet)) {
  241. headers_remaining = 3;
  242. }
  243. if (!headers_remaining) {
  244. ERR_FAIL_COND_MSG((err = vorbis_synthesis(&block, packet)), "Error during vorbis synthesis " + itos(err));
  245. ERR_FAIL_COND_MSG((err = vorbis_synthesis_blockin(&dsp_state, &block)), "Error during vorbis block processing " + itos(err));
  246. int samples_out = vorbis_synthesis_pcmout(&dsp_state, nullptr);
  247. ERR_FAIL_COND_MSG((err = vorbis_synthesis_read(&dsp_state, samples_out)), "Error during vorbis read updating " + itos(err));
  248. samples_in_page += samples_out;
  249. } else {
  250. headers_remaining--;
  251. }
  252. if (packet->granulepos != -1 && headers_remaining == 0) {
  253. // This indicates the end of the page.
  254. granule_pos = packet->granulepos;
  255. break;
  256. }
  257. if (packet->e_o_s) {
  258. break;
  259. }
  260. if (!vorbis_data_playback->next_ogg_packet(&packet)) {
  261. // We should get an e_o_s flag before this happens.
  262. WARN_PRINT("Vorbis file ended without warning.");
  263. break;
  264. }
  265. }
  266. int64_t samples_to_burn = samples_in_page - (granule_pos - desired_sample);
  267. if (samples_to_burn > samples_in_page) {
  268. WARN_PRINT("Burning more samples than we have in this page. Check seek algorithm.");
  269. } else if (samples_to_burn < 0) {
  270. WARN_PRINT("Burning negative samples doesn't make sense. Check seek algorithm.");
  271. }
  272. // Seek again, this time we'll burn a specific number of samples instead of all of them.
  273. if (!vorbis_data_playback->seek_page(desired_sample)) {
  274. WARN_PRINT("seek failed");
  275. return;
  276. }
  277. if (!vorbis_data_playback->next_ogg_packet(&packet)) {
  278. WARN_PRINT_ONCE("seeking beyond limits");
  279. return;
  280. }
  281. vorbis_synthesis_restart(&dsp_state);
  282. while (true) {
  283. if (vorbis_synthesis_idheader(packet)) {
  284. headers_remaining = 3;
  285. }
  286. if (!headers_remaining) {
  287. ERR_FAIL_COND_MSG((err = vorbis_synthesis(&block, packet)), "Error during vorbis synthesis " + itos(err));
  288. ERR_FAIL_COND_MSG((err = vorbis_synthesis_blockin(&dsp_state, &block)), "Error during vorbis block processing " + itos(err));
  289. int samples_out = vorbis_synthesis_pcmout(&dsp_state, nullptr);
  290. int read_samples = samples_to_burn > samples_out ? samples_out : samples_to_burn;
  291. ERR_FAIL_COND_MSG((err = vorbis_synthesis_read(&dsp_state, samples_out)), "Error during vorbis read updating " + itos(err));
  292. samples_to_burn -= read_samples;
  293. if (samples_to_burn <= 0) {
  294. break;
  295. }
  296. } else {
  297. headers_remaining--;
  298. }
  299. if (packet->granulepos != -1 && headers_remaining == 0) {
  300. // This indicates the end of the page.
  301. break;
  302. }
  303. if (packet->e_o_s) {
  304. break;
  305. }
  306. if (!vorbis_data_playback->next_ogg_packet(&packet)) {
  307. // We should get an e_o_s flag before this happens.
  308. WARN_PRINT("Vorbis file ended without warning.");
  309. break;
  310. }
  311. }
  312. }
  313. AudioStreamPlaybackOggVorbis::~AudioStreamPlaybackOggVorbis() {
  314. if (block_is_allocated) {
  315. vorbis_block_clear(&block);
  316. }
  317. if (dsp_state_is_allocated) {
  318. vorbis_dsp_clear(&dsp_state);
  319. }
  320. if (comment_is_allocated) {
  321. vorbis_comment_clear(&comment);
  322. }
  323. if (info_is_allocated) {
  324. vorbis_info_clear(&info);
  325. }
  326. }
  327. Ref<AudioStreamPlayback> AudioStreamOggVorbis::instantiate_playback() {
  328. Ref<AudioStreamPlaybackOggVorbis> ovs;
  329. ERR_FAIL_COND_V(packet_sequence.is_null(), nullptr);
  330. ovs.instantiate();
  331. ovs->vorbis_stream = Ref<AudioStreamOggVorbis>(this);
  332. ovs->vorbis_data = packet_sequence;
  333. ovs->frames_mixed = 0;
  334. ovs->active = false;
  335. ovs->loops = 0;
  336. if (ovs->_alloc_vorbis()) {
  337. return ovs;
  338. }
  339. // Failed to allocate data structures.
  340. return nullptr;
  341. }
  342. String AudioStreamOggVorbis::get_stream_name() const {
  343. return ""; //return stream_name;
  344. }
  345. void AudioStreamOggVorbis::maybe_update_info() {
  346. ERR_FAIL_COND(packet_sequence.is_null());
  347. vorbis_info info;
  348. vorbis_comment comment;
  349. int err;
  350. vorbis_info_init(&info);
  351. vorbis_comment_init(&comment);
  352. Ref<OggPacketSequencePlayback> packet_sequence_playback = packet_sequence->instantiate_playback();
  353. for (int i = 0; i < 3; i++) {
  354. ogg_packet *packet;
  355. if (!packet_sequence_playback->next_ogg_packet(&packet)) {
  356. WARN_PRINT("Failed to get header packet");
  357. break;
  358. }
  359. if (i == 0) {
  360. packet->b_o_s = 1;
  361. }
  362. if (i == 0) {
  363. ERR_FAIL_COND(!vorbis_synthesis_idheader(packet));
  364. }
  365. err = vorbis_synthesis_headerin(&info, &comment, packet);
  366. ERR_FAIL_COND_MSG(err != 0, "Error parsing header packet " + itos(i) + ": " + itos(err));
  367. }
  368. packet_sequence->set_sampling_rate(info.rate);
  369. vorbis_comment_clear(&comment);
  370. vorbis_info_clear(&info);
  371. }
  372. void AudioStreamOggVorbis::set_packet_sequence(Ref<OggPacketSequence> p_packet_sequence) {
  373. packet_sequence = p_packet_sequence;
  374. if (packet_sequence.is_valid()) {
  375. maybe_update_info();
  376. }
  377. }
  378. Ref<OggPacketSequence> AudioStreamOggVorbis::get_packet_sequence() const {
  379. return packet_sequence;
  380. }
  381. void AudioStreamOggVorbis::set_loop(bool p_enable) {
  382. loop = p_enable;
  383. }
  384. bool AudioStreamOggVorbis::has_loop() const {
  385. return loop;
  386. }
  387. void AudioStreamOggVorbis::set_loop_offset(float p_seconds) {
  388. loop_offset = p_seconds;
  389. }
  390. float AudioStreamOggVorbis::get_loop_offset() const {
  391. return loop_offset;
  392. }
  393. float AudioStreamOggVorbis::get_length() const {
  394. ERR_FAIL_COND_V(packet_sequence.is_null(), 0);
  395. return packet_sequence->get_length();
  396. }
  397. void AudioStreamOggVorbis::set_bpm(double p_bpm) {
  398. ERR_FAIL_COND(p_bpm < 0);
  399. bpm = p_bpm;
  400. emit_changed();
  401. }
  402. double AudioStreamOggVorbis::get_bpm() const {
  403. return bpm;
  404. }
  405. void AudioStreamOggVorbis::set_beat_count(int p_beat_count) {
  406. ERR_FAIL_COND(p_beat_count < 0);
  407. beat_count = p_beat_count;
  408. emit_changed();
  409. }
  410. int AudioStreamOggVorbis::get_beat_count() const {
  411. return beat_count;
  412. }
  413. void AudioStreamOggVorbis::set_bar_beats(int p_bar_beats) {
  414. ERR_FAIL_COND(p_bar_beats < 2);
  415. bar_beats = p_bar_beats;
  416. emit_changed();
  417. }
  418. int AudioStreamOggVorbis::get_bar_beats() const {
  419. return bar_beats;
  420. }
  421. bool AudioStreamOggVorbis::is_monophonic() const {
  422. return false;
  423. }
  424. void AudioStreamOggVorbis::_bind_methods() {
  425. ClassDB::bind_method(D_METHOD("set_packet_sequence", "packet_sequence"), &AudioStreamOggVorbis::set_packet_sequence);
  426. ClassDB::bind_method(D_METHOD("get_packet_sequence"), &AudioStreamOggVorbis::get_packet_sequence);
  427. ClassDB::bind_method(D_METHOD("set_loop", "enable"), &AudioStreamOggVorbis::set_loop);
  428. ClassDB::bind_method(D_METHOD("has_loop"), &AudioStreamOggVorbis::has_loop);
  429. ClassDB::bind_method(D_METHOD("set_loop_offset", "seconds"), &AudioStreamOggVorbis::set_loop_offset);
  430. ClassDB::bind_method(D_METHOD("get_loop_offset"), &AudioStreamOggVorbis::get_loop_offset);
  431. ClassDB::bind_method(D_METHOD("set_bpm", "bpm"), &AudioStreamOggVorbis::set_bpm);
  432. ClassDB::bind_method(D_METHOD("get_bpm"), &AudioStreamOggVorbis::get_bpm);
  433. ClassDB::bind_method(D_METHOD("set_beat_count", "count"), &AudioStreamOggVorbis::set_beat_count);
  434. ClassDB::bind_method(D_METHOD("get_beat_count"), &AudioStreamOggVorbis::get_beat_count);
  435. ClassDB::bind_method(D_METHOD("set_bar_beats", "count"), &AudioStreamOggVorbis::set_bar_beats);
  436. ClassDB::bind_method(D_METHOD("get_bar_beats"), &AudioStreamOggVorbis::get_bar_beats);
  437. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "packet_sequence", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "set_packet_sequence", "get_packet_sequence");
  438. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "bpm", PROPERTY_HINT_RANGE, "0,400,0.01,or_greater"), "set_bpm", "get_bpm");
  439. ADD_PROPERTY(PropertyInfo(Variant::INT, "beat_count", PROPERTY_HINT_RANGE, "0,512,1,or_greater"), "set_beat_count", "get_beat_count");
  440. ADD_PROPERTY(PropertyInfo(Variant::INT, "bar_beats", PROPERTY_HINT_RANGE, "2,32,1,or_greater"), "set_bar_beats", "get_bar_beats");
  441. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "loop"), "set_loop", "has_loop");
  442. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "loop_offset"), "set_loop_offset", "get_loop_offset");
  443. }
  444. AudioStreamOggVorbis::AudioStreamOggVorbis() {}
  445. AudioStreamOggVorbis::~AudioStreamOggVorbis() {}