audio_stream_opus.cpp 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. /*************************************************************************/
  2. /* audio_stream_opus.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2019 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_opus.h"
  31. /**
  32. @author George Marques <[email protected]>
  33. */
  34. const float AudioStreamPlaybackOpus::osrate = 48000.0f;
  35. int AudioStreamPlaybackOpus::_op_read_func(void *_stream, unsigned char *_ptr, int _nbytes) {
  36. FileAccess *fa = (FileAccess *)_stream;
  37. if (fa->eof_reached())
  38. return 0;
  39. uint8_t *dst = (uint8_t *)_ptr;
  40. int read = fa->get_buffer(dst, _nbytes);
  41. return read;
  42. }
  43. int AudioStreamPlaybackOpus::_op_seek_func(void *_stream, opus_int64 _offset, int _whence) {
  44. #ifdef SEEK_SET
  45. FileAccess *fa = (FileAccess *)_stream;
  46. switch (_whence) {
  47. case SEEK_SET: {
  48. fa->seek(_offset);
  49. } break;
  50. case SEEK_CUR: {
  51. fa->seek(fa->get_position() + _offset);
  52. } break;
  53. case SEEK_END: {
  54. fa->seek_end(_offset);
  55. } break;
  56. default: {
  57. ERR_PRINT("Opus seek function failure: Unexpected value in _whence\n");
  58. }
  59. }
  60. int ret = fa->eof_reached() ? -1 : 0;
  61. return ret;
  62. #else
  63. return -1; // no seeking
  64. #endif
  65. }
  66. int AudioStreamPlaybackOpus::_op_close_func(void *_stream) {
  67. if (!_stream)
  68. return 0;
  69. FileAccess *fa = (FileAccess *)_stream;
  70. if (fa->is_open())
  71. fa->close();
  72. return 0;
  73. }
  74. opus_int64 AudioStreamPlaybackOpus::_op_tell_func(void *_stream) {
  75. FileAccess *_fa = (FileAccess *)_stream;
  76. return (opus_int64)_fa->get_position();
  77. }
  78. void AudioStreamPlaybackOpus::_clear_stream() {
  79. if (!stream_loaded)
  80. return;
  81. op_free(opus_file);
  82. _close_file();
  83. stream_loaded = false;
  84. stream_channels = 1;
  85. playing = false;
  86. }
  87. void AudioStreamPlaybackOpus::_close_file() {
  88. if (f) {
  89. memdelete(f);
  90. f = NULL;
  91. }
  92. }
  93. Error AudioStreamPlaybackOpus::_load_stream() {
  94. ERR_FAIL_COND_V(!stream_valid, ERR_UNCONFIGURED);
  95. _clear_stream();
  96. if (file == "")
  97. return ERR_INVALID_DATA;
  98. Error err;
  99. f = FileAccess::open(file, FileAccess::READ, &err);
  100. ERR_FAIL_COND_V_MSG(err, err, "Cannot open file '" + file + "'.");
  101. int _err = 0;
  102. opus_file = op_open_callbacks(f, &_op_callbacks, NULL, 0, &_err);
  103. switch (_err) {
  104. case OP_EREAD: { // - Can't read the file.
  105. memdelete(f);
  106. f = NULL;
  107. ERR_FAIL_V(ERR_FILE_CANT_READ);
  108. } break;
  109. case OP_EVERSION: // - Unrecognized version number.
  110. case OP_ENOTFORMAT: // - Stream is not Opus data.
  111. case OP_EIMPL: { // - Stream used non-implemented feature.
  112. memdelete(f);
  113. f = NULL;
  114. ERR_FAIL_V(ERR_FILE_UNRECOGNIZED);
  115. } break;
  116. case OP_EBADLINK: // - Failed to find old data after seeking.
  117. case OP_EBADTIMESTAMP: // - Timestamp failed the validity checks.
  118. case OP_EBADHEADER: { // - Invalid or missing Opus bitstream header.
  119. memdelete(f);
  120. f = NULL;
  121. ERR_FAIL_V(ERR_FILE_CORRUPT);
  122. } break;
  123. case OP_EFAULT: { // - Internal logic fault; indicates a bug or heap/stack corruption.
  124. memdelete(f);
  125. f = NULL;
  126. ERR_FAIL_V(ERR_BUG);
  127. } break;
  128. }
  129. repeats = 0;
  130. stream_loaded = true;
  131. return OK;
  132. }
  133. AudioStreamPlaybackOpus::AudioStreamPlaybackOpus() {
  134. loops = false;
  135. playing = false;
  136. f = NULL;
  137. stream_loaded = false;
  138. stream_valid = false;
  139. repeats = 0;
  140. paused = true;
  141. stream_channels = 0;
  142. current_section = 0;
  143. length = 0;
  144. loop_restart_time = 0;
  145. pre_skip = 0;
  146. _op_callbacks.read = _op_read_func;
  147. _op_callbacks.seek = _op_seek_func;
  148. _op_callbacks.tell = _op_tell_func;
  149. _op_callbacks.close = _op_close_func;
  150. }
  151. Error AudioStreamPlaybackOpus::set_file(const String &p_file) {
  152. file = p_file;
  153. stream_valid = false;
  154. Error err;
  155. f = FileAccess::open(file, FileAccess::READ, &err);
  156. ERR_FAIL_COND_V_MSG(err, err, "Cannot open file '" + file + "'.");
  157. int _err;
  158. opus_file = op_open_callbacks(f, &_op_callbacks, NULL, 0, &_err);
  159. switch (_err) {
  160. case OP_EREAD: { // - Can't read the file.
  161. memdelete(f);
  162. f = NULL;
  163. ERR_FAIL_V(ERR_FILE_CANT_READ);
  164. } break;
  165. case OP_EVERSION: // - Unrecognized version number.
  166. case OP_ENOTFORMAT: // - Stream is not Opus data.
  167. case OP_EIMPL: { // - Stream used non-implemented feature.
  168. memdelete(f);
  169. f = NULL;
  170. ERR_FAIL_V(ERR_FILE_UNRECOGNIZED);
  171. } break;
  172. case OP_EBADLINK: // - Failed to find old data after seeking.
  173. case OP_EBADTIMESTAMP: // - Timestamp failed the validity checks.
  174. case OP_EBADHEADER: { // - Invalid or missing Opus bitstream header.
  175. memdelete(f);
  176. f = NULL;
  177. ERR_FAIL_V(ERR_FILE_CORRUPT);
  178. } break;
  179. case OP_EFAULT: { // - Internal logic fault; indicates a bug or heap/stack corruption.
  180. memdelete(f);
  181. f = NULL;
  182. ERR_FAIL_V(ERR_BUG);
  183. } break;
  184. }
  185. const OpusHead *oinfo = op_head(opus_file, -1);
  186. stream_channels = oinfo->channel_count;
  187. pre_skip = oinfo->pre_skip;
  188. frames_mixed = pre_skip;
  189. ogg_int64_t len = op_pcm_total(opus_file, -1);
  190. if (len < 0) {
  191. length = 0;
  192. } else {
  193. length = (len / osrate);
  194. }
  195. op_free(opus_file);
  196. memdelete(f);
  197. f = NULL;
  198. stream_valid = true;
  199. return OK;
  200. }
  201. void AudioStreamPlaybackOpus::play(float p_from) {
  202. if (playing)
  203. stop();
  204. if (_load_stream() != OK)
  205. return;
  206. frames_mixed = pre_skip;
  207. playing = true;
  208. if (p_from > 0) {
  209. seek(p_from);
  210. }
  211. }
  212. void AudioStreamPlaybackOpus::stop() {
  213. _clear_stream();
  214. playing = false;
  215. }
  216. void AudioStreamPlaybackOpus::seek(float p_time) {
  217. if (!playing) return;
  218. ogg_int64_t pcm_offset = (ogg_int64_t)(p_time * osrate);
  219. bool ok = op_pcm_seek(opus_file, pcm_offset) == 0;
  220. if (!ok) {
  221. ERR_PRINT("Seek time over stream size.");
  222. return;
  223. }
  224. frames_mixed = osrate * p_time;
  225. }
  226. int AudioStreamPlaybackOpus::mix(int16_t *p_buffer, int p_frames) {
  227. if (!playing)
  228. return 0;
  229. int total = p_frames;
  230. while (true) {
  231. int todo = p_frames;
  232. if (todo < MIN_MIX) {
  233. break;
  234. }
  235. int ret = op_read(opus_file, (opus_int16 *)p_buffer, todo * stream_channels, &current_section);
  236. if (ret < 0) {
  237. playing = false;
  238. ERR_BREAK_MSG(ret < 0, "Error reading Opus file: " + file + ".");
  239. } else if (ret == 0) { // end of song, reload?
  240. op_free(opus_file);
  241. _close_file();
  242. f = FileAccess::open(file, FileAccess::READ);
  243. int errv = 0;
  244. opus_file = op_open_callbacks(f, &_op_callbacks, NULL, 0, &errv);
  245. if (errv != 0) {
  246. playing = false;
  247. break; // :(
  248. }
  249. if (!has_loop()) {
  250. playing = false;
  251. repeats = 1;
  252. break;
  253. }
  254. if (loop_restart_time) {
  255. bool ok = op_pcm_seek(opus_file, (loop_restart_time * osrate) + pre_skip) == 0;
  256. if (!ok) {
  257. playing = false;
  258. ERR_PRINT("Loop restart time rejected");
  259. }
  260. frames_mixed = (loop_restart_time * osrate) + pre_skip;
  261. } else {
  262. frames_mixed = pre_skip;
  263. }
  264. repeats++;
  265. continue;
  266. }
  267. stream_channels = op_head(opus_file, current_section)->channel_count;
  268. frames_mixed += ret;
  269. p_buffer += ret * stream_channels;
  270. p_frames -= ret;
  271. }
  272. return total - p_frames;
  273. }
  274. float AudioStreamPlaybackOpus::get_length() const {
  275. if (!stream_loaded) {
  276. if (const_cast<AudioStreamPlaybackOpus *>(this)->_load_stream() != OK)
  277. return 0;
  278. }
  279. return length;
  280. }
  281. float AudioStreamPlaybackOpus::get_playback_position() const {
  282. int32_t frames = int32_t(frames_mixed);
  283. if (frames < 0)
  284. frames = 0;
  285. return double(frames) / osrate;
  286. }
  287. int AudioStreamPlaybackOpus::get_minimum_buffer_size() const {
  288. return MIN_MIX;
  289. }
  290. AudioStreamPlaybackOpus::~AudioStreamPlaybackOpus() {
  291. _clear_stream();
  292. }
  293. RES ResourceFormatLoaderAudioStreamOpus::load(const String &p_path, const String &p_original_path, Error *r_error) {
  294. if (r_error)
  295. *r_error = OK;
  296. AudioStreamOpus *opus_stream = memnew(AudioStreamOpus);
  297. opus_stream->set_file(p_path);
  298. return Ref<AudioStreamOpus>(opus_stream);
  299. }
  300. void ResourceFormatLoaderAudioStreamOpus::get_recognized_extensions(List<String> *p_extensions) const {
  301. p_extensions->push_back("opus");
  302. }
  303. String ResourceFormatLoaderAudioStreamOpus::get_resource_type(const String &p_path) const {
  304. if (p_path.get_extension().to_lower() == "opus")
  305. return "AudioStreamOpus";
  306. return "";
  307. }
  308. bool ResourceFormatLoaderAudioStreamOpus::handles_type(const String &p_type) const {
  309. return (p_type == "AudioStream" || p_type == "AudioStreamOpus");
  310. }