audio_stream_ogg_vorbis.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  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 <ogg/ogg.h>
  32. int AudioStreamPlaybackOggVorbis::_mix_internal(AudioFrame *p_buffer, int p_frames) {
  33. ERR_FAIL_COND_V(!ready, 0);
  34. if (!active) {
  35. return 0;
  36. }
  37. int todo = p_frames;
  38. int beat_length_frames = -1;
  39. bool use_loop = looping_override ? looping : vorbis_stream->loop;
  40. if (use_loop && vorbis_stream->get_bpm() > 0 && vorbis_stream->get_beat_count() > 0) {
  41. beat_length_frames = vorbis_stream->get_beat_count() * vorbis_data->get_sampling_rate() * 60 / vorbis_stream->get_bpm();
  42. }
  43. while (todo > 0 && active) {
  44. AudioFrame *buffer = p_buffer;
  45. buffer += p_frames - todo;
  46. int to_mix = todo;
  47. if (beat_length_frames >= 0 && (beat_length_frames - (int)frames_mixed) < to_mix) {
  48. to_mix = MAX(0, beat_length_frames - (int)frames_mixed);
  49. }
  50. int mixed = _mix_frames_vorbis(buffer, to_mix);
  51. ERR_FAIL_COND_V(mixed < 0, 0);
  52. todo -= mixed;
  53. frames_mixed += mixed;
  54. if (loop_fade_remaining < FADE_SIZE) {
  55. int to_fade = loop_fade_remaining + MIN(FADE_SIZE - loop_fade_remaining, mixed);
  56. for (int i = loop_fade_remaining; i < to_fade; i++) {
  57. buffer[i - loop_fade_remaining] += loop_fade[i] * (float(FADE_SIZE - i) / float(FADE_SIZE));
  58. }
  59. loop_fade_remaining = to_fade;
  60. }
  61. if (beat_length_frames >= 0) {
  62. /**
  63. * Length determined by beat length
  64. * This code is commented out because, in practice, it is preferred that the fade
  65. * is done by the transitioner and this stream just goes on until it ends while fading out.
  66. *
  67. * End fade implementation is left here for reference in case at some point this feature
  68. * is desired.
  69. if (!beat_loop && (int)frames_mixed > beat_length_frames - FADE_SIZE) {
  70. print_line("beat length fade/after mix?");
  71. //No loop, just fade and finish
  72. for (int i = 0; i < mixed; i++) {
  73. int idx = frames_mixed + i - mixed;
  74. buffer[i] *= 1.0 - float(MAX(0, (idx - (beat_length_frames - FADE_SIZE)))) / float(FADE_SIZE);
  75. }
  76. if ((int)frames_mixed == beat_length_frames) {
  77. for (int i = p_frames - todo; i < p_frames; i++) {
  78. p_buffer[i] = AudioFrame(0, 0);
  79. }
  80. active = false;
  81. break;
  82. }
  83. } else
  84. **/
  85. if (use_loop && beat_length_frames <= (int)frames_mixed) {
  86. // End of file when doing beat-based looping. <= used instead of == because importer editing
  87. if (!have_packets_left && !have_samples_left) {
  88. //Nothing remaining, so do nothing.
  89. loop_fade_remaining = FADE_SIZE;
  90. } else {
  91. // Add some loop fade;
  92. int faded_mix = _mix_frames_vorbis(loop_fade, FADE_SIZE);
  93. for (int i = faded_mix; i < FADE_SIZE; i++) {
  94. // In case lesss was mixed, pad with zeros
  95. loop_fade[i] = AudioFrame(0, 0);
  96. }
  97. loop_fade_remaining = 0;
  98. }
  99. seek(vorbis_stream->loop_offset);
  100. loops++;
  101. // We still have buffer to fill, start from this element in the next iteration.
  102. continue;
  103. }
  104. }
  105. if (!have_packets_left && !have_samples_left) {
  106. // Actual end of file!
  107. bool is_not_empty = mixed > 0 || vorbis_stream->get_length() > 0;
  108. if (use_loop && is_not_empty) {
  109. //loop
  110. seek(vorbis_stream->loop_offset);
  111. loops++;
  112. // We still have buffer to fill, start from this element in the next iteration.
  113. } else {
  114. for (int i = p_frames - todo; i < p_frames; i++) {
  115. p_buffer[i] = AudioFrame(0, 0);
  116. }
  117. active = false;
  118. }
  119. }
  120. }
  121. return p_frames - todo;
  122. }
  123. int AudioStreamPlaybackOggVorbis::_mix_frames_vorbis(AudioFrame *p_buffer, int p_frames) {
  124. ERR_FAIL_COND_V(!ready, p_frames);
  125. if (!have_samples_left) {
  126. ogg_packet *packet = nullptr;
  127. int err;
  128. if (!vorbis_data_playback->next_ogg_packet(&packet)) {
  129. have_packets_left = false;
  130. WARN_PRINT("ran out of packets in stream");
  131. return -1;
  132. }
  133. err = vorbis_synthesis(&block, packet);
  134. ERR_FAIL_COND_V_MSG(err != 0, p_frames, "Error during vorbis synthesis " + itos(err));
  135. err = vorbis_synthesis_blockin(&dsp_state, &block);
  136. ERR_FAIL_COND_V_MSG(err != 0, p_frames, "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].left = pcm[0][frame];
  150. p_buffer[frame].right = pcm[1][frame];
  151. }
  152. } else {
  153. for (int frame = 0; frame < frames; frame++) {
  154. p_buffer[frame].left = pcm[0][frame];
  155. p_buffer[frame].right = 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(double 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. double AudioStreamPlaybackOggVorbis::get_playback_position() const {
  208. return double(frames_mixed) / (double)vorbis_data->get_sampling_rate();
  209. }
  210. void AudioStreamPlaybackOggVorbis::tag_used_streams() {
  211. vorbis_stream->tag_used(get_playback_position());
  212. }
  213. void AudioStreamPlaybackOggVorbis::set_parameter(const StringName &p_name, const Variant &p_value) {
  214. if (p_name == SNAME("looping")) {
  215. if (p_value == Variant()) {
  216. looping_override = false;
  217. looping = false;
  218. } else {
  219. looping_override = true;
  220. looping = p_value;
  221. }
  222. }
  223. }
  224. Variant AudioStreamPlaybackOggVorbis::get_parameter(const StringName &p_name) const {
  225. if (looping_override && p_name == SNAME("looping")) {
  226. return looping;
  227. }
  228. return Variant();
  229. }
  230. void AudioStreamPlaybackOggVorbis::seek(double p_time) {
  231. ERR_FAIL_COND(!ready);
  232. ERR_FAIL_COND(vorbis_stream.is_null());
  233. if (!active) {
  234. return;
  235. }
  236. if (p_time >= vorbis_stream->get_length()) {
  237. p_time = 0;
  238. }
  239. frames_mixed = uint32_t(vorbis_data->get_sampling_rate() * p_time);
  240. const int64_t desired_sample = p_time * get_stream_sampling_rate();
  241. if (!vorbis_data_playback->seek_page(desired_sample)) {
  242. WARN_PRINT("seek failed");
  243. return;
  244. }
  245. // We want to start decoding before the page that we expect the sample to be in (the sample may
  246. // be part of a partial packet across page boundaries). Otherwise, the decoder may not have
  247. // synchronized before reaching the sample.
  248. int64_t start_page_number = vorbis_data_playback->get_page_number() - 1;
  249. if (start_page_number < 0) {
  250. start_page_number = 0;
  251. }
  252. while (true) {
  253. ogg_packet *packet;
  254. int err;
  255. // We start at an unknown granule position.
  256. int64_t granule_pos = -1;
  257. // Decode data until we get to the desired sample or notice that we have read past it.
  258. vorbis_data_playback->set_page_number(start_page_number);
  259. vorbis_synthesis_restart(&dsp_state);
  260. while (true) {
  261. if (!vorbis_data_playback->next_ogg_packet(&packet)) {
  262. WARN_PRINT_ONCE("Seeking beyond limits");
  263. return;
  264. }
  265. err = vorbis_synthesis(&block, packet);
  266. if (err != OV_ENOTAUDIO) {
  267. ERR_FAIL_COND_MSG(err != 0, "Error during vorbis synthesis " + itos(err) + ".");
  268. err = vorbis_synthesis_blockin(&dsp_state, &block);
  269. ERR_FAIL_COND_MSG(err != 0, "Error during vorbis block processing " + itos(err) + ".");
  270. int samples_out = vorbis_synthesis_pcmout(&dsp_state, nullptr);
  271. if (granule_pos < 0) {
  272. // We don't know where we are yet, so just keep on decoding.
  273. err = vorbis_synthesis_read(&dsp_state, samples_out);
  274. ERR_FAIL_COND_MSG(err != 0, "Error during vorbis read updating " + itos(err) + ".");
  275. } else if (granule_pos + samples_out >= desired_sample) {
  276. // Our sample is in this block. Skip the beginning of the block up to the sample, then
  277. // return.
  278. int skip_samples = (int)(desired_sample - granule_pos);
  279. err = vorbis_synthesis_read(&dsp_state, skip_samples);
  280. ERR_FAIL_COND_MSG(err != 0, "Error during vorbis read updating " + itos(err) + ".");
  281. have_samples_left = skip_samples < samples_out;
  282. have_packets_left = !packet->e_o_s;
  283. return;
  284. } else {
  285. // Our sample is not in this block. Skip it.
  286. err = vorbis_synthesis_read(&dsp_state, samples_out);
  287. ERR_FAIL_COND_MSG(err != 0, "Error during vorbis read updating " + itos(err) + ".");
  288. granule_pos += samples_out;
  289. }
  290. }
  291. if (packet->granulepos != -1) {
  292. // We found an update to our granule position.
  293. granule_pos = packet->granulepos;
  294. if (granule_pos > desired_sample) {
  295. // We've read past our sample. We need to start on an earlier page.
  296. if (start_page_number == 0) {
  297. // We didn't find the sample even reading from the beginning.
  298. have_samples_left = false;
  299. have_packets_left = !packet->e_o_s;
  300. return;
  301. }
  302. start_page_number--;
  303. break;
  304. }
  305. }
  306. if (packet->e_o_s) {
  307. // We've reached the end of the stream and didn't find our sample.
  308. have_samples_left = false;
  309. have_packets_left = false;
  310. return;
  311. }
  312. }
  313. }
  314. }
  315. void AudioStreamPlaybackOggVorbis::set_is_sample(bool p_is_sample) {
  316. _is_sample = p_is_sample;
  317. }
  318. bool AudioStreamPlaybackOggVorbis::get_is_sample() const {
  319. return _is_sample;
  320. }
  321. Ref<AudioSamplePlayback> AudioStreamPlaybackOggVorbis::get_sample_playback() const {
  322. return sample_playback;
  323. }
  324. void AudioStreamPlaybackOggVorbis::set_sample_playback(const Ref<AudioSamplePlayback> &p_playback) {
  325. sample_playback = p_playback;
  326. if (sample_playback.is_valid()) {
  327. sample_playback->stream_playback = Ref<AudioStreamPlayback>(this);
  328. }
  329. }
  330. AudioStreamPlaybackOggVorbis::~AudioStreamPlaybackOggVorbis() {
  331. if (block_is_allocated) {
  332. vorbis_block_clear(&block);
  333. }
  334. if (dsp_state_is_allocated) {
  335. vorbis_dsp_clear(&dsp_state);
  336. }
  337. if (comment_is_allocated) {
  338. vorbis_comment_clear(&comment);
  339. }
  340. if (info_is_allocated) {
  341. vorbis_info_clear(&info);
  342. }
  343. }
  344. Ref<AudioStreamPlayback> AudioStreamOggVorbis::instantiate_playback() {
  345. Ref<AudioStreamPlaybackOggVorbis> ovs;
  346. ERR_FAIL_COND_V(packet_sequence.is_null(), nullptr);
  347. ovs.instantiate();
  348. ovs->vorbis_stream = Ref<AudioStreamOggVorbis>(this);
  349. ovs->vorbis_data = packet_sequence;
  350. ovs->frames_mixed = 0;
  351. ovs->active = false;
  352. ovs->loops = 0;
  353. if (ovs->_alloc_vorbis()) {
  354. return ovs;
  355. }
  356. // Failed to allocate data structures.
  357. return nullptr;
  358. }
  359. String AudioStreamOggVorbis::get_stream_name() const {
  360. return ""; //return stream_name;
  361. }
  362. void AudioStreamOggVorbis::maybe_update_info() {
  363. ERR_FAIL_COND(packet_sequence.is_null());
  364. vorbis_info info;
  365. vorbis_comment comment;
  366. int err;
  367. vorbis_info_init(&info);
  368. vorbis_comment_init(&comment);
  369. Ref<OggPacketSequencePlayback> packet_sequence_playback = packet_sequence->instantiate_playback();
  370. for (int i = 0; i < 3; i++) {
  371. ogg_packet *packet;
  372. if (!packet_sequence_playback->next_ogg_packet(&packet)) {
  373. WARN_PRINT("Failed to get header packet");
  374. break;
  375. }
  376. if (i == 0) {
  377. packet->b_o_s = 1;
  378. ERR_FAIL_COND(!vorbis_synthesis_idheader(packet));
  379. }
  380. err = vorbis_synthesis_headerin(&info, &comment, packet);
  381. ERR_FAIL_COND_MSG(err != 0, "Error parsing header packet " + itos(i) + ": " + itos(err));
  382. }
  383. packet_sequence->set_sampling_rate(info.rate);
  384. vorbis_comment_clear(&comment);
  385. vorbis_info_clear(&info);
  386. }
  387. void AudioStreamOggVorbis::set_packet_sequence(Ref<OggPacketSequence> p_packet_sequence) {
  388. packet_sequence = p_packet_sequence;
  389. if (packet_sequence.is_valid()) {
  390. maybe_update_info();
  391. }
  392. }
  393. Ref<OggPacketSequence> AudioStreamOggVorbis::get_packet_sequence() const {
  394. return packet_sequence;
  395. }
  396. void AudioStreamOggVorbis::set_loop(bool p_enable) {
  397. loop = p_enable;
  398. }
  399. bool AudioStreamOggVorbis::has_loop() const {
  400. return loop;
  401. }
  402. void AudioStreamOggVorbis::set_loop_offset(double p_seconds) {
  403. loop_offset = p_seconds;
  404. }
  405. double AudioStreamOggVorbis::get_loop_offset() const {
  406. return loop_offset;
  407. }
  408. double AudioStreamOggVorbis::get_length() const {
  409. ERR_FAIL_COND_V(packet_sequence.is_null(), 0);
  410. return packet_sequence->get_length();
  411. }
  412. void AudioStreamOggVorbis::set_bpm(double p_bpm) {
  413. ERR_FAIL_COND(p_bpm < 0);
  414. bpm = p_bpm;
  415. emit_changed();
  416. }
  417. double AudioStreamOggVorbis::get_bpm() const {
  418. return bpm;
  419. }
  420. void AudioStreamOggVorbis::set_beat_count(int p_beat_count) {
  421. ERR_FAIL_COND(p_beat_count < 0);
  422. beat_count = p_beat_count;
  423. emit_changed();
  424. }
  425. int AudioStreamOggVorbis::get_beat_count() const {
  426. return beat_count;
  427. }
  428. void AudioStreamOggVorbis::set_bar_beats(int p_bar_beats) {
  429. ERR_FAIL_COND(p_bar_beats < 2);
  430. bar_beats = p_bar_beats;
  431. emit_changed();
  432. }
  433. int AudioStreamOggVorbis::get_bar_beats() const {
  434. return bar_beats;
  435. }
  436. bool AudioStreamOggVorbis::is_monophonic() const {
  437. return false;
  438. }
  439. void AudioStreamOggVorbis::get_parameter_list(List<Parameter> *r_parameters) {
  440. r_parameters->push_back(Parameter(PropertyInfo(Variant::BOOL, "looping", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_CHECKABLE), Variant()));
  441. }
  442. Ref<AudioSample> AudioStreamOggVorbis::generate_sample() const {
  443. Ref<AudioSample> sample;
  444. sample.instantiate();
  445. sample->stream = this;
  446. sample->loop_mode = loop
  447. ? AudioSample::LoopMode::LOOP_FORWARD
  448. : AudioSample::LoopMode::LOOP_DISABLED;
  449. sample->loop_begin = loop_offset;
  450. sample->loop_end = 0;
  451. return sample;
  452. }
  453. Ref<AudioStreamOggVorbis> AudioStreamOggVorbis::load_from_buffer(const Vector<uint8_t> &p_stream_data) {
  454. Ref<AudioStreamOggVorbis> ogg_vorbis_stream;
  455. ogg_vorbis_stream.instantiate();
  456. Ref<OggPacketSequence> ogg_packet_sequence;
  457. ogg_packet_sequence.instantiate();
  458. ogg_stream_state stream_state;
  459. ogg_sync_state sync_state;
  460. ogg_page page;
  461. ogg_packet packet;
  462. bool initialized_stream = false;
  463. ogg_sync_init(&sync_state);
  464. const long OGG_SYNC_BUFFER_SIZE = 8192;
  465. int err;
  466. size_t cursor = 0;
  467. size_t packet_count = 0;
  468. bool done = false;
  469. while (!done) {
  470. err = ogg_sync_check(&sync_state);
  471. ERR_FAIL_COND_V_MSG(err != 0, Ref<AudioStreamOggVorbis>(), "Ogg sync error " + itos(err));
  472. while (ogg_sync_pageout(&sync_state, &page) != 1) {
  473. if (cursor >= size_t(p_stream_data.size())) {
  474. done = true;
  475. break;
  476. }
  477. err = ogg_sync_check(&sync_state);
  478. ERR_FAIL_COND_V_MSG(err != 0, Ref<AudioStreamOggVorbis>(), "Ogg sync error " + itos(err));
  479. char *sync_buf = ogg_sync_buffer(&sync_state, OGG_SYNC_BUFFER_SIZE);
  480. err = ogg_sync_check(&sync_state);
  481. ERR_FAIL_COND_V_MSG(err != 0, Ref<AudioStreamOggVorbis>(), "Ogg sync error " + itos(err));
  482. size_t copy_size = p_stream_data.size() - cursor;
  483. if (copy_size > OGG_SYNC_BUFFER_SIZE) {
  484. copy_size = OGG_SYNC_BUFFER_SIZE;
  485. }
  486. memcpy(sync_buf, &p_stream_data[cursor], copy_size);
  487. ogg_sync_wrote(&sync_state, copy_size);
  488. cursor += copy_size;
  489. err = ogg_sync_check(&sync_state);
  490. ERR_FAIL_COND_V_MSG(err != 0, Ref<AudioStreamOggVorbis>(), "Ogg sync error " + itos(err));
  491. }
  492. if (done) {
  493. break;
  494. }
  495. err = ogg_sync_check(&sync_state);
  496. ERR_FAIL_COND_V_MSG(err != 0, Ref<AudioStreamOggVorbis>(), "Ogg sync error " + itos(err));
  497. // Have a page now.
  498. if (!initialized_stream) {
  499. if (ogg_stream_init(&stream_state, ogg_page_serialno(&page))) {
  500. ERR_FAIL_V_MSG(Ref<AudioStreamOggVorbis>(), "Failed allocating memory for Ogg Vorbis stream.");
  501. }
  502. initialized_stream = true;
  503. }
  504. ogg_stream_pagein(&stream_state, &page);
  505. err = ogg_stream_check(&stream_state);
  506. ERR_FAIL_COND_V_MSG(err != 0, Ref<AudioStreamOggVorbis>(), "Ogg stream error " + itos(err));
  507. int desync_iters = 0;
  508. RBMap<uint64_t, Vector<Vector<uint8_t>>> sorted_packets;
  509. int64_t granule_pos = 0;
  510. while (true) {
  511. err = ogg_stream_packetout(&stream_state, &packet);
  512. if (err == -1) {
  513. // According to the docs this is usually recoverable, but don't sit here spinning forever.
  514. desync_iters++;
  515. WARN_PRINT_ONCE("Desync during ogg import.");
  516. ERR_FAIL_COND_V_MSG(desync_iters > 100, Ref<AudioStreamOggVorbis>(), "Packet sync issue during Ogg import");
  517. continue;
  518. } else if (err == 0) {
  519. // Not enough data to fully reconstruct a packet. Go on to the next page.
  520. break;
  521. }
  522. if (packet_count == 0 && vorbis_synthesis_idheader(&packet) == 0) {
  523. print_verbose("Found a non-vorbis-header packet in a header position");
  524. // Clearly this logical stream is not a vorbis stream, so destroy it and try again with the next page.
  525. if (initialized_stream) {
  526. ogg_stream_clear(&stream_state);
  527. initialized_stream = false;
  528. }
  529. break;
  530. }
  531. if (packet.granulepos > granule_pos) {
  532. granule_pos = packet.granulepos;
  533. }
  534. if (packet.bytes > 0) {
  535. PackedByteArray data;
  536. data.resize(packet.bytes);
  537. memcpy(data.ptrw(), packet.packet, packet.bytes);
  538. sorted_packets[granule_pos].push_back(data);
  539. packet_count++;
  540. }
  541. }
  542. Vector<Vector<uint8_t>> packet_data;
  543. for (const KeyValue<uint64_t, Vector<Vector<uint8_t>>> &pair : sorted_packets) {
  544. for (const Vector<uint8_t> &packets : pair.value) {
  545. packet_data.push_back(packets);
  546. }
  547. }
  548. if (initialized_stream && packet_data.size() > 0) {
  549. ogg_packet_sequence->push_page(ogg_page_granulepos(&page), packet_data);
  550. }
  551. }
  552. if (initialized_stream) {
  553. ogg_stream_clear(&stream_state);
  554. }
  555. ogg_sync_clear(&sync_state);
  556. if (ogg_packet_sequence->get_packet_granule_positions().is_empty()) {
  557. ERR_FAIL_V_MSG(Ref<AudioStreamOggVorbis>(), "Ogg Vorbis decoding failed. Check that your data is a valid Ogg Vorbis audio stream.");
  558. }
  559. ogg_vorbis_stream->set_packet_sequence(ogg_packet_sequence);
  560. return ogg_vorbis_stream;
  561. }
  562. Ref<AudioStreamOggVorbis> AudioStreamOggVorbis::load_from_file(const String &p_path) {
  563. const Vector<uint8_t> stream_data = FileAccess::get_file_as_bytes(p_path);
  564. ERR_FAIL_COND_V_MSG(stream_data.is_empty(), Ref<AudioStreamOggVorbis>(), vformat("Cannot open file '%s'.", p_path));
  565. return load_from_buffer(stream_data);
  566. }
  567. void AudioStreamOggVorbis::_bind_methods() {
  568. ClassDB::bind_static_method("AudioStreamOggVorbis", D_METHOD("load_from_buffer", "stream_data"), &AudioStreamOggVorbis::load_from_buffer);
  569. ClassDB::bind_static_method("AudioStreamOggVorbis", D_METHOD("load_from_file", "path"), &AudioStreamOggVorbis::load_from_file);
  570. ClassDB::bind_method(D_METHOD("set_packet_sequence", "packet_sequence"), &AudioStreamOggVorbis::set_packet_sequence);
  571. ClassDB::bind_method(D_METHOD("get_packet_sequence"), &AudioStreamOggVorbis::get_packet_sequence);
  572. ClassDB::bind_method(D_METHOD("set_loop", "enable"), &AudioStreamOggVorbis::set_loop);
  573. ClassDB::bind_method(D_METHOD("has_loop"), &AudioStreamOggVorbis::has_loop);
  574. ClassDB::bind_method(D_METHOD("set_loop_offset", "seconds"), &AudioStreamOggVorbis::set_loop_offset);
  575. ClassDB::bind_method(D_METHOD("get_loop_offset"), &AudioStreamOggVorbis::get_loop_offset);
  576. ClassDB::bind_method(D_METHOD("set_bpm", "bpm"), &AudioStreamOggVorbis::set_bpm);
  577. ClassDB::bind_method(D_METHOD("get_bpm"), &AudioStreamOggVorbis::get_bpm);
  578. ClassDB::bind_method(D_METHOD("set_beat_count", "count"), &AudioStreamOggVorbis::set_beat_count);
  579. ClassDB::bind_method(D_METHOD("get_beat_count"), &AudioStreamOggVorbis::get_beat_count);
  580. ClassDB::bind_method(D_METHOD("set_bar_beats", "count"), &AudioStreamOggVorbis::set_bar_beats);
  581. ClassDB::bind_method(D_METHOD("get_bar_beats"), &AudioStreamOggVorbis::get_bar_beats);
  582. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "packet_sequence", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "set_packet_sequence", "get_packet_sequence");
  583. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "bpm", PROPERTY_HINT_RANGE, "0,400,0.01,or_greater"), "set_bpm", "get_bpm");
  584. ADD_PROPERTY(PropertyInfo(Variant::INT, "beat_count", PROPERTY_HINT_RANGE, "0,512,1,or_greater"), "set_beat_count", "get_beat_count");
  585. ADD_PROPERTY(PropertyInfo(Variant::INT, "bar_beats", PROPERTY_HINT_RANGE, "2,32,1,or_greater"), "set_bar_beats", "get_bar_beats");
  586. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "loop"), "set_loop", "has_loop");
  587. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "loop_offset"), "set_loop_offset", "get_loop_offset");
  588. }
  589. AudioStreamOggVorbis::AudioStreamOggVorbis() {}
  590. AudioStreamOggVorbis::~AudioStreamOggVorbis() {}