audio_stream_ogg_vorbis.cpp 17 KB

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