opus.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. /*
  2. * Squeezelite - lightweight headless squeezebox emulator
  3. *
  4. * (c) Adrian Smith 2012-2015, triode1@btinternet.com
  5. * Ralph Irving 2015-2017, ralph_irving@hotmail.com
  6. * Philippe 2018-2019, philippe_44@outlook.com
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation, either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. *
  21. */
  22. #include "squeezelite.h"
  23. /*
  24. * with some low-end CPU, the decode call takes a fair bit of time and if the outputbuf is locked during that
  25. * period, the output_thread (or equivalent) will be locked although there is plenty of samples available.
  26. * Normally, with PRIO_INHERIT, that thread should increase decoder priority and get the lock quickly but it
  27. * seems that when the streambuf has plenty of data, the decode thread grabs the CPU to much, even it the output
  28. * thread has a higher priority. Using an interim buffer where opus decoder writes the output is not great from
  29. * an efficiency (one extra memory copy) point of view, but it allows the lock to not be kept for too long
  30. */
  31. #if BYTES_PER_FRAME == 4
  32. #define ALIGN(n) (n)
  33. #else
  34. #define ALIGN(n) (n << 16)
  35. #endif
  36. #include <ogg/ogg.h>
  37. #include <opus.h>
  38. // opus maximum output frames is 120ms @ 48kHz
  39. #define MAX_OPUS_FRAMES 5760
  40. struct opus {
  41. enum { OGG_ID_HEADER, OGG_COMMENT_HEADER } status;
  42. ogg_stream_state state;
  43. ogg_packet packet;
  44. ogg_sync_state sync;
  45. ogg_page page;
  46. OpusDecoder* decoder;
  47. int rate, gain, pre_skip;
  48. size_t overframes;
  49. u8_t *overbuf;
  50. int channels;
  51. };
  52. #if !LINKALL
  53. static struct {
  54. void *handle;
  55. int (*ogg_stream_init)(ogg_stream_state* os, int serialno);
  56. int (*ogg_stream_clear)(ogg_stream_state* os);
  57. int (*ogg_stream_reset)(ogg_stream_state* os);
  58. int (*ogg_stream_eos)(ogg_stream_state* os);
  59. int (*ogg_stream_reset_serialno)(ogg_stream_state* os, int serialno);
  60. int (*ogg_sync_clear)(ogg_sync_state* oy);
  61. void (*ogg_packet_clear)(ogg_packet* op);
  62. char* (*ogg_sync_buffer)(ogg_sync_state* oy, long size);
  63. int (*ogg_sync_wrote)(ogg_sync_state* oy, long bytes);
  64. long (*ogg_sync_pageseek)(ogg_sync_state* oy, ogg_page* og);
  65. int (*ogg_sync_pageout)(ogg_sync_state* oy, ogg_page* og);
  66. int (*ogg_stream_pagein)(ogg_stream_state* os, ogg_page* og);
  67. int (*ogg_stream_packetout)(ogg_stream_state* os, ogg_packet* op);
  68. int (*ogg_page_packets)(const ogg_page* og);
  69. } go;
  70. static struct {
  71. void* handle;
  72. OpusDecoder* (*opus_decoder_create)(opus_int32 Fs, int channels, int* error);
  73. int (*opus_decode)(OpusDecoder* st, const unsigned char* data, opus_int32 len, opus_int16* pcm, int frame_size, int decode_fec);
  74. void (*opus_decoder_destroy)(OpusDecoder* st);
  75. } gu;
  76. #endif
  77. static struct opus *u;
  78. extern log_level loglevel;
  79. extern struct buffer *streambuf;
  80. extern struct buffer *outputbuf;
  81. extern struct streamstate stream;
  82. extern struct outputstate output;
  83. extern struct decodestate decode;
  84. extern struct processstate process;
  85. #define LOCK_S mutex_lock(streambuf->mutex)
  86. #define UNLOCK_S mutex_unlock(streambuf->mutex)
  87. #define LOCK_O mutex_lock(outputbuf->mutex)
  88. #define UNLOCK_O mutex_unlock(outputbuf->mutex)
  89. #if PROCESS
  90. #define LOCK_O_direct if (decode.direct) mutex_lock(outputbuf->mutex)
  91. #define UNLOCK_O_direct if (decode.direct) mutex_unlock(outputbuf->mutex)
  92. #define IF_DIRECT(x) if (decode.direct) { x }
  93. #define IF_PROCESS(x) if (!decode.direct) { x }
  94. #else
  95. #define LOCK_O_direct mutex_lock(outputbuf->mutex)
  96. #define UNLOCK_O_direct mutex_unlock(outputbuf->mutex)
  97. #define IF_DIRECT(x) { x }
  98. #define IF_PROCESS(x)
  99. #endif
  100. #if LINKALL
  101. #define OG(h, fn, ...) (ogg_ ## fn)(__VA_ARGS__)
  102. #define OP(h, fn, ...) (opus_ ## fn)(__VA_ARGS__)
  103. #else
  104. #define OG(h, fn, ...) (h)->ogg_ ## fn(__VA_ARGS__)
  105. #define OP(h, fn, ...) (h)->opus_ ## fn(__VA_ARGS__)
  106. #endif
  107. static unsigned parse_uint16(const unsigned char* _data) {
  108. return _data[0] | _data[1] << 8;
  109. }
  110. static int parse_int16(const unsigned char* _data) {
  111. return ((_data[0] | _data[1] << 8) ^ 0x8000) - 0x8000;
  112. }
  113. static opus_uint32 parse_uint32(const unsigned char* _data) {
  114. return _data[0] | (opus_uint32)_data[1] << 8 |
  115. (opus_uint32)_data[2] << 16 | (opus_uint32)_data[3] << 24;
  116. }
  117. static int get_audio_packet(void) {
  118. int status, packet = -1;
  119. LOCK_S;
  120. size_t bytes = min(_buf_used(streambuf), _buf_cont_read(streambuf));
  121. while (!(status = OG(&go, stream_packetout, &u->state, &u->packet)) && bytes) {
  122. // if sync_pageout (or sync_pageseek) is not called here, sync buffers build up
  123. while (!(status = OG(&go, sync_pageout, &u->sync, &u->page)) && bytes) {
  124. size_t consumed = min(bytes, 4096);
  125. char* buffer = OG(&go, sync_buffer, &u->sync, consumed);
  126. memcpy(buffer, streambuf->readp, consumed);
  127. OG(&go, sync_wrote, &u->sync, consumed);
  128. _buf_inc_readp(streambuf, consumed);
  129. bytes -= consumed;
  130. }
  131. // if we have a new page, put it in and reset serialno at BoS
  132. if (status) {
  133. OG(&go, stream_pagein, &u->state, &u->page);
  134. if (OG(&go, page_bos, &u->page)) OG(&go, stream_reset_serialno, &u->state, OG(&go, page_serialno, &u->page));
  135. }
  136. }
  137. /* discard header packets. With no packet, we return a negative value
  138. * when there is really nothing more to proceed */
  139. if (status > 0 && memcmp(u->packet.packet, "OpusHead", 8) && memcmp(u->packet.packet, "OpusTags", 8)) packet = status;
  140. else if (stream.state > DISCONNECT || _buf_used(streambuf)) packet = 0;
  141. UNLOCK_S;
  142. return packet;
  143. }
  144. static int read_opus_header(void) {
  145. int done = 0;
  146. bool fetch = true;
  147. LOCK_S;
  148. size_t bytes = min(_buf_used(streambuf), _buf_cont_read(streambuf));
  149. while (bytes && !done) {
  150. int status;
  151. // get aligned to a page and ready to bring it in
  152. do {
  153. size_t consumed = min(bytes, 4096);
  154. char* buffer = OG(&go, sync_buffer, &u->sync, consumed);
  155. memcpy(buffer, streambuf->readp, consumed);
  156. OG(&go, sync_wrote, &u->sync, consumed);
  157. _buf_inc_readp(streambuf, consumed);
  158. bytes -= consumed;
  159. status = fetch ? OG(&go, sync_pageout, &u->sync, &u->page) :
  160. OG(&go, sync_pageseek, &u->sync, &u->page);
  161. } while (bytes && status <= 0);
  162. // nothing has been found and we have no more bytes, come back later
  163. if (status <= 0) break;
  164. // always set stream serialno if we have a new one (no multiplexed streams)
  165. if (OG(&go, page_bos, &u->page)) OG(&go, stream_reset_serialno, &u->state, OG(&go, page_serialno, &u->page));
  166. // bring new page in if we want it (otherwise we're just skipping)
  167. if (fetch) OG(&go, stream_pagein, &u->state, &u->page);
  168. // no need for a switch...case
  169. if (u->status == OGG_ID_HEADER) {
  170. // we need the id packet, get more pages if we don't
  171. if (OG(&go, stream_packetout, &u->state, &u->packet) <= 0) continue;
  172. // make sure this is a valid packet
  173. if (u->packet.bytes < 19 || memcmp(u->packet.packet, "OpusHead", 8)) {
  174. LOG_ERROR("wrong header packet (size:%u)", u->packet.bytes);
  175. done = -100;
  176. } else {
  177. u->status = OGG_COMMENT_HEADER;
  178. u->channels = u->packet.packet[9];
  179. u->pre_skip = parse_uint16(u->packet.packet + 10);
  180. u->rate = parse_uint32(u->packet.packet + 12);
  181. u->gain = parse_int16(u->packet.packet + 16);
  182. u->decoder = OP(&gu, decoder_create, 48000, u->channels, &status);
  183. fetch = false;
  184. if (!u->decoder || status != OPUS_OK) {
  185. LOG_ERROR("can't create decoder %d (channels:%u)", status, u->channels);
  186. }
  187. else {
  188. LOG_INFO("codec up and running");
  189. }
  190. }
  191. } else if (u->status == OGG_COMMENT_HEADER) {
  192. // don't consume VorbisComment which could be a huge packet, just skip it
  193. if (!OG(&go, page_packets, &u->page)) continue;
  194. LOG_INFO("comment skipped successfully");
  195. done = 1;
  196. }
  197. }
  198. UNLOCK_S;
  199. return done;
  200. }
  201. static decode_state opus_decompress(void) {
  202. frames_t frames;
  203. u8_t *write_buf;
  204. if (decode.new_stream) {
  205. int status = read_opus_header();
  206. if (status == 0) {
  207. return DECODE_RUNNING;
  208. } else if (status < 0) {
  209. LOG_WARN("can't create codec");
  210. return DECODE_ERROR;
  211. }
  212. LOCK_O;
  213. output.next_sample_rate = decode_newstream(48000, output.supported_rates);
  214. IF_DSD( output.next_fmt = PCM; )
  215. output.track_start = outputbuf->writep;
  216. if (output.fade_mode) _checkfade(true);
  217. decode.new_stream = false;
  218. UNLOCK_O;
  219. if (u->channels > 2) {
  220. LOG_WARN("too many channels: %d", u->channels);
  221. return DECODE_ERROR;
  222. }
  223. LOG_INFO("setting track_start");
  224. }
  225. LOCK_O_direct;
  226. IF_DIRECT(
  227. frames = min(_buf_space(outputbuf), _buf_cont_write(outputbuf)) / BYTES_PER_FRAME;
  228. write_buf = outputbuf->writep;
  229. );
  230. IF_PROCESS(
  231. frames = process.max_in_frames;
  232. write_buf = process.inbuf;
  233. );
  234. int packet, n = 0;
  235. // get some packets and decode them, or use the leftover from previous pass
  236. if (u->overframes) {
  237. /* use potential leftover from previous encoding. We know that it will fit this time
  238. * as min_space is >=MAX_OPUS_FRAMES and we start from the beginning of the buffer */
  239. memcpy(write_buf, u->overbuf, u->overframes * BYTES_PER_FRAME);
  240. n = u->overframes;
  241. u->overframes = 0;
  242. } else if ((packet = get_audio_packet()) > 0) {
  243. if (frames < MAX_OPUS_FRAMES) {
  244. // don't have enough contiguous space, use the overflow buffer
  245. n = OP(&gu, decode, u->decoder, u->packet.packet, u->packet.bytes, (opus_int16*) u->overbuf, MAX_OPUS_FRAMES, 0);
  246. if (n > 0) {
  247. u->overframes = n - min(n, frames);
  248. n = min(n, frames);
  249. memcpy(write_buf, u->overbuf, n * BYTES_PER_FRAME);
  250. memmove(u->overbuf, u->overbuf + n, u->overframes);
  251. }
  252. } else {
  253. /* we just do one packet at a time, although we could loop on packets but that means locking the
  254. * outputbuf and streambuf for maybe a long time while we process it all, so don't do that */
  255. n = OP(&gu, decode, u->decoder, u->packet.packet, u->packet.bytes, (opus_int16*) write_buf, frames, 0);
  256. }
  257. } else if (!packet) {
  258. UNLOCK_O_direct;
  259. return DECODE_RUNNING;
  260. }
  261. if (n > 0) {
  262. frames_t count;
  263. s16_t *iptr;
  264. ISAMPLE_T *optr;
  265. frames = n;
  266. count = frames * u->channels;
  267. // work backward to unpack samples (if needed)
  268. iptr = (s16_t *) write_buf + count;
  269. IF_DIRECT(
  270. optr = (ISAMPLE_T *) outputbuf->writep + frames * 2;
  271. )
  272. IF_PROCESS(
  273. optr = (ISAMPLE_T *) write_buf + frames * 2;
  274. )
  275. if (u->channels == 2) {
  276. #if BYTES_PER_FRAME == 8
  277. while (count--) {
  278. *--optr = ALIGN(*--iptr);
  279. }
  280. #endif
  281. } else if (u->channels == 1) {
  282. while (count--) {
  283. *--optr = ALIGN(*--iptr);
  284. *--optr = ALIGN(*iptr);
  285. }
  286. }
  287. IF_DIRECT(
  288. _buf_inc_writep(outputbuf, frames * BYTES_PER_FRAME);
  289. );
  290. IF_PROCESS(
  291. process.in_frames = frames;
  292. );
  293. LOG_SDEBUG("wrote %u frames", frames);
  294. } else if (n == 0) {
  295. if (packet < 0) {
  296. LOG_INFO("end of decode");
  297. UNLOCK_O_direct;
  298. return DECODE_COMPLETE;
  299. } else {
  300. LOG_INFO("no frame decoded");
  301. }
  302. } else {
  303. LOG_INFO("decode error: %d", n);
  304. UNLOCK_O_direct;
  305. return DECODE_COMPLETE;
  306. }
  307. UNLOCK_O_direct;
  308. return DECODE_RUNNING;
  309. }
  310. static void opus_open(u8_t size, u8_t rate, u8_t chan, u8_t endianness) {
  311. if (u->decoder) OP(&gu, decoder_destroy, u->decoder);
  312. u->decoder = NULL;
  313. if (!u->overbuf) u->overbuf = malloc(MAX_OPUS_FRAMES * BYTES_PER_FRAME);
  314. u->status = OGG_ID_HEADER;
  315. u->overframes = 0;
  316. OG(&go, stream_clear, &u->state);
  317. OG(&go, sync_clear, &u->sync);
  318. OG(&go, stream_init, &u->state, -1);
  319. }
  320. static void opus_close(void) {
  321. if (u->decoder) OP(&gu, decoder_destroy, u->decoder);
  322. u->decoder = NULL;
  323. free(u->overbuf);
  324. u->overbuf = NULL;
  325. OG(&go, stream_clear, &u->state);
  326. OG(&go, sync_clear, &u->sync);
  327. }
  328. static bool load_opus(void) {
  329. #if !LINKALL
  330. char *err;
  331. void *u.handle = dlopen(LIBOPUS, RTLD_NOW);
  332. if (!u_handle) {
  333. LOG_INFO("opus dlerror: %s", dlerror());
  334. return false;
  335. }
  336. void *g_handle = dlopen(LIBOGG, RTLD_NOW);
  337. if (!g_handle) {
  338. dlclose(u_handle);
  339. LOG_INFO("ogg dlerror: %s", dlerror());
  340. return false;
  341. }
  342. g_handle->ogg_stream_clear = dlsym(g_handle->handle, "ogg_stream_clear");
  343. g_handle->ogg_stream_reset = dlsym(g_handle->handle, "ogg_stream_reset");
  344. g_handle->ogg_stream_eos = dlsym(g_handle->handle, "ogg_stream_eos");
  345. g_handle->ogg_stream_reset_serialno = dlsym(g_handle->handle, "ogg_stream_reset_serialno");
  346. g_handle->ogg_sync_clear = dlsym(g_handle->handle, "ogg_sync_clear");
  347. g_handle->ogg_packet_clear = dlsym(g_handle->handle, "ogg_packet_clear");
  348. g_handle->ogg_sync_buffer = dlsym(g_handle->handle, "ogg_sync_buffer");
  349. g_handle->ogg_sync_wrote = dlsym(g_handle->handle, "ogg_sync_wrote");
  350. g_handle->ogg_sync_pageseek = dlsym(g_handle->handle, "ogg_sync_pageseek");
  351. g_handle->ogg_sync_pageout = dlsym(g_handle->handle, "ogg_sync_pageout");
  352. g_handle->ogg_stream_pagein = dlsym(g_handle->handle, "ogg_stream_pagein");
  353. g_handle->ogg_stream_packetout = dlsym(g_handle->handle, "ogg_stream_packetout");
  354. g_handle->ogg_page_packets = dlsym(g_handle->handle, "ogg_page_packets");
  355. u_handle->opus_decoder_create = dlsym(u_handle->handle, "opus_decoder_create");
  356. u_handle->opus_decoder_destroy = dlsym(u_handle->handle, "opus_decoder_destroy");
  357. u_handle->opus_decode = dlsym(u_handle->handle, "opus_decode");
  358. if ((err = dlerror()) != NULL) {
  359. LOG_INFO("dlerror: %s", err);
  360. return false;
  361. }
  362. LOG_INFO("loaded "LIBOPUS);
  363. #endif
  364. return true;
  365. }
  366. struct codec *register_opus(void) {
  367. static struct codec ret = {
  368. 'u', // id
  369. "ops", // types
  370. 8*1024, // min read
  371. MAX_OPUS_FRAMES*BYTES_PER_FRAME*2, // min space
  372. opus_open, // open
  373. opus_close, // close
  374. opus_decompress, // decode
  375. };
  376. if ((u = calloc(1, sizeof(struct opus))) == NULL) {
  377. return NULL;
  378. }
  379. if (!load_opus()) {
  380. return NULL;
  381. }
  382. LOG_INFO("using opus to decode ops");
  383. return &ret;
  384. }