oggplay.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. /* -*- mode: c; tab-width: 4; c-basic-offset: 4; c-file-style: "linux" -*- */
  2. //
  3. // Copyright (c) 2009-2011, Wei Mingzhi <whistler_wmz@users.sf.net>.
  4. // Copyright (c) 2011-2017, SDLPAL development team.
  5. // All rights reserved.
  6. //
  7. // This file is part of SDLPAL.
  8. //
  9. // SDLPAL is free software: you can redistribute it and/or modify
  10. // it under the terms of the GNU General Public License as published by
  11. // the Free Software Foundation, either version 3 of the License, or
  12. // (at your option) any later version.
  13. //
  14. // This program is distributed in the hope that it will be useful,
  15. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. // GNU General Public License for more details.
  18. //
  19. // You should have received a copy of the GNU General Public License
  20. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  21. //
  22. // oggplay.h: Player of OGG files.
  23. // @Author: Lou Yihua <louyihua@21cn.com>, 2015-07-28.
  24. //
  25. #include "util.h"
  26. #include "global.h"
  27. #include "palcfg.h"
  28. #include "players.h"
  29. #include "audio.h"
  30. #include <math.h>
  31. #if PAL_HAS_OGG
  32. #include <vorbis/vorbisfile.h>
  33. #include "resampler.h"
  34. #define FLAG_OY 0x01
  35. #define FLAG_VI 0x02
  36. #define FLAG_VC 0x04
  37. #define FLAG_OS 0x08
  38. #define FLAG_VD 0x10
  39. #define FLAG_VB 0x20
  40. #define STAGE_PAGEOUT 1
  41. #define STAGE_PACKETOUT 2
  42. #define STAGE_PCMOUT 3
  43. #define STAGE_REWIND 4
  44. #define OGG_BUFFER_LENGTH 4096
  45. typedef struct tagOGGPLAYER
  46. {
  47. AUDIOPLAYER_COMMONS;
  48. ogg_sync_state oy; /* sync and verify incoming physical bitstream */
  49. ogg_stream_state os; /* take physical pages, weld into a logical stream of packets */
  50. ogg_page og; /* one Ogg bitstream page. Vorbis packets are inside */
  51. vorbis_info vi; /* struct that stores all the static vorbis bitstream settings */
  52. vorbis_comment vc; /* struct that stores all the bitstream user comments */
  53. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  54. vorbis_block vb; /* local working space for packet->PCM decode */
  55. FILE *fp;
  56. void *resampler[2];
  57. INT iFlags;
  58. INT iMusic;
  59. INT iStage;
  60. INT nChannels;
  61. BOOL fLoop;
  62. BOOL fReady;
  63. BOOL fUseResampler;
  64. } OGGPLAYER, *LPOGGPLAYER;
  65. PAL_FORCE_INLINE ogg_int16_t OGG_GetSample(float pcm)
  66. {
  67. int val = (int)(floor(pcm * 32767.f + .5f));
  68. /* might as well guard against clipping */
  69. if (val > 32767) {
  70. val = 32767;
  71. }
  72. else if (val < -32768) {
  73. val = -32768;
  74. }
  75. return (ogg_int16_t)val;
  76. }
  77. PAL_FORCE_INLINE void OGG_FillResample(LPOGGPLAYER player, ogg_int16_t* stream)
  78. {
  79. if (gConfig.iAudioChannels == 2) {
  80. stream[0] = resampler_get_and_remove_sample(player->resampler[0]);
  81. stream[1] = (player->vi.channels > 1) ? resampler_get_and_remove_sample(player->resampler[1]) : stream[0];
  82. }
  83. else {
  84. if (player->vi.channels > 1) {
  85. *stream = (short)((int)(resampler_get_and_remove_sample(player->resampler[0]) + resampler_get_and_remove_sample(player->resampler[1])) >> 1);
  86. }
  87. else {
  88. *stream = resampler_get_and_remove_sample(player->resampler[0]);
  89. }
  90. }
  91. }
  92. static void OGG_Cleanup(LPOGGPLAYER player)
  93. {
  94. int i;
  95. for (i = 0; i < gConfig.iAudioChannels; i++) resampler_clear(player->resampler[0]);
  96. /* Do various cleanups */
  97. if (player->iFlags & FLAG_VB) vorbis_block_clear(&player->vb);
  98. if (player->iFlags & FLAG_VD) vorbis_dsp_clear(&player->vd);
  99. if (player->iFlags & FLAG_OS) ogg_stream_clear(&player->os);
  100. if (player->iFlags & FLAG_VC) vorbis_comment_clear(&player->vc);
  101. if (player->iFlags & FLAG_VI) vorbis_info_clear(&player->vi); /* must be called last */
  102. if (player->iFlags & FLAG_OY) ogg_sync_clear(&player->oy);
  103. player->iFlags = player->iStage = 0;
  104. player->fReady = FALSE;
  105. }
  106. static BOOL OGG_Rewind(LPOGGPLAYER player)
  107. {
  108. ogg_packet op; /* one raw packet of data for decode */
  109. char *buffer;
  110. int i, bytes;
  111. OGG_Cleanup(player);
  112. fseek(player->fp, 0, SEEK_SET);
  113. ogg_sync_init(&player->oy); player->iFlags = FLAG_OY;
  114. /* grab some data at the head of the stream. We want the first page
  115. (which is guaranteed to be small and only contain the Vorbis
  116. stream initial header) We need the first page to get the stream
  117. serialno. */
  118. /* submit a 4k block to libvorbis' Ogg layer */
  119. buffer = ogg_sync_buffer(&player->oy, OGG_BUFFER_LENGTH);
  120. bytes = fread(buffer, 1, OGG_BUFFER_LENGTH, player->fp);
  121. ogg_sync_wrote(&player->oy, bytes);
  122. /* Get the first page. */
  123. if (ogg_sync_pageout(&player->oy, &player->og) != 1) {
  124. /* have we simply run out of data? If so, we're done. */
  125. /* error case. Must not be Vorbis data */
  126. OGG_Cleanup(player);
  127. return (player->fReady = FALSE);
  128. }
  129. /* Get the serial number and set up the rest of decode. */
  130. /* serialno first; use it to set up a logical stream */
  131. ogg_stream_init(&player->os, ogg_page_serialno(&player->og));
  132. player->iFlags |= FLAG_OS;
  133. /* extract the initial header from the first page and verify that the
  134. Ogg bitstream is in fact Vorbis data */
  135. /* I handle the initial header first instead of just having the code
  136. read all three Vorbis headers at once because reading the initial
  137. header is an easy way to identify a Vorbis bitstream and it's
  138. useful to see that functionality seperated out. */
  139. vorbis_info_init(&player->vi); player->iFlags |= FLAG_VI;
  140. vorbis_comment_init(&player->vc); player->iFlags |= FLAG_VC;
  141. if (ogg_stream_pagein(&player->os, &player->og)<0) {
  142. /* error; stream version mismatch perhaps */
  143. OGG_Cleanup(player);
  144. return (player->fReady = FALSE);
  145. }
  146. if (ogg_stream_packetout(&player->os, &op) != 1) {
  147. /* no page? must not be vorbis */
  148. OGG_Cleanup(player);
  149. return (player->fReady = FALSE);
  150. }
  151. if (vorbis_synthesis_headerin(&player->vi, &player->vc, &op)<0) {
  152. /* error case; not a vorbis header */
  153. OGG_Cleanup(player);
  154. return (player->fReady = FALSE);
  155. }
  156. /* At this point, we're sure we're Vorbis. We've set up the logical
  157. (Ogg) bitstream decoder. Get the comment and codebook headers and
  158. set up the Vorbis decoder */
  159. /* The next two packets in order are the comment and codebook headers.
  160. They're likely large and may span multiple pages. Thus we read
  161. and submit data until we get our two packets, watching that no
  162. pages are missing. If a page is missing, error out; losing a
  163. header page is the only place where missing data is fatal. */
  164. i = 0;
  165. while (i < 2) {
  166. while (i < 2) {
  167. int result = ogg_sync_pageout(&player->oy, &player->og);
  168. if (result == 0)break; /* Need more data */
  169. /* Don't complain about missing or corrupt data yet. We'll
  170. catch it at the packet output phase */
  171. if (result == 1) {
  172. ogg_stream_pagein(&player->os, &player->og); /* we can ignore any errors here
  173. as they'll also become apparent
  174. at packetout */
  175. while (i < 2) {
  176. result = ogg_stream_packetout(&player->os, &op);
  177. if (result == 0)break;
  178. if (result < 0) {
  179. /* Uh oh; data at some point was corrupted or missing!
  180. We can't tolerate that in a header. Die. */
  181. OGG_Cleanup(player);
  182. return (player->fReady = FALSE);
  183. }
  184. result = vorbis_synthesis_headerin(&player->vi, &player->vc, &op);
  185. if (result < 0) {
  186. OGG_Cleanup(player);
  187. return (player->fReady = FALSE);
  188. }
  189. i++;
  190. }
  191. }
  192. }
  193. /* no harm in not checking before adding more */
  194. buffer = ogg_sync_buffer(&player->oy, OGG_BUFFER_LENGTH);
  195. bytes = fread(buffer, 1, OGG_BUFFER_LENGTH, player->fp);
  196. if (bytes == 0 && i < 2) {
  197. OGG_Cleanup(player);
  198. return (player->fReady = FALSE);
  199. }
  200. ogg_sync_wrote(&player->oy, bytes);
  201. }
  202. if (vorbis_synthesis_init(&player->vd, &player->vi) == 0) { /* central decode state */
  203. vorbis_block_init(&player->vd, &player->vb); /* local state for most of the decode
  204. so multiple block decodes can
  205. proceed in parallel. We could init
  206. multiple vorbis_block structures
  207. for vd here */
  208. player->iStage = STAGE_PAGEOUT;
  209. player->iFlags |= FLAG_VD | FLAG_VB;
  210. player->fUseResampler = (player->vi.rate != gConfig.iSampleRate);
  211. if (player->fUseResampler) {
  212. double factor = (double)player->vi.rate / (double)gConfig.iSampleRate;
  213. for (i = 0; i < min(player->vi.channels, 2); i++)
  214. {
  215. resampler_set_quality(player->resampler[i], AUDIO_IsIntegerConversion(player->vi.rate) ? RESAMPLER_QUALITY_MIN : gConfig.iResampleQuality);
  216. resampler_set_rate(player->resampler[i], factor);
  217. resampler_clear(player->resampler[i]);
  218. }
  219. }
  220. return (player->fReady = TRUE);
  221. }
  222. else {
  223. OGG_Cleanup(player);
  224. return (player->fReady = FALSE);
  225. }
  226. }
  227. static VOID
  228. OGG_FillBuffer(
  229. VOID *object,
  230. LPBYTE stream,
  231. INT len
  232. )
  233. {
  234. LPOGGPLAYER player = (LPOGGPLAYER)object;
  235. if (player->fReady) {
  236. ogg_packet op; /* one raw packet of data for decode */
  237. int total_bytes = 0, stage = player->iStage;
  238. while (total_bytes < len) {
  239. float **pcm;
  240. int samples, result;
  241. switch (stage)
  242. {
  243. case STAGE_PAGEOUT: /* PAGEOUT stage */
  244. result = ogg_sync_pageout(&player->oy, &player->og);
  245. if (result > 0) {
  246. /* can safely ignore errors at this point */
  247. ogg_stream_pagein(&player->os, &player->og);
  248. stage = STAGE_PACKETOUT;
  249. }
  250. else {
  251. if (result == 0) { /* need more data */
  252. char *buffer = ogg_sync_buffer(&player->oy, OGG_BUFFER_LENGTH);
  253. int bytes = fread(buffer, 1, OGG_BUFFER_LENGTH, player->fp);
  254. ogg_sync_wrote(&player->oy, bytes);
  255. stage = (bytes > 0) ? STAGE_PAGEOUT : STAGE_REWIND;
  256. }
  257. break;
  258. }
  259. case STAGE_PACKETOUT:
  260. result = ogg_stream_packetout(&player->os, &op);
  261. if (result > 0) {
  262. /* we have a packet. Decode it */
  263. if (vorbis_synthesis(&player->vb, &op) == 0) { /* test for success! */
  264. vorbis_synthesis_blockin(&player->vd, &player->vb);
  265. }
  266. stage = STAGE_PCMOUT;
  267. }
  268. else {
  269. if (result == 0) { /* need more data */
  270. if (ogg_page_eos(&player->og)) {
  271. if (player->fLoop) {
  272. stage = STAGE_REWIND;
  273. }
  274. else {
  275. OGG_Cleanup(player);
  276. UTIL_CloseFile(player->fp);
  277. player->fp = NULL;
  278. return;
  279. }
  280. }
  281. else {
  282. stage = STAGE_PAGEOUT;
  283. }
  284. }
  285. break;
  286. }
  287. case STAGE_PCMOUT:
  288. if ((samples = vorbis_synthesis_pcmout(&player->vd, &pcm)) > 0) {
  289. int bout;
  290. if (player->fUseResampler) { /* Resampler is available and should be used */
  291. bout = 0;
  292. while (total_bytes < len && samples > 0) { /* Fill as many samples into resampler as possible */
  293. int i, j, to_write = resampler_get_free_count(player->resampler[0]);
  294. if (to_write > 0) {
  295. if (to_write >= samples) to_write = samples;
  296. for (i = 0; i < min(player->vi.channels, 2); i++) {
  297. float *mono = pcm[i] + bout;
  298. for (j = 0; j < to_write; j++) {
  299. resampler_write_sample(player->resampler[i], OGG_GetSample(mono[j]));
  300. }
  301. }
  302. }
  303. /* Fetch resampled samples if available */
  304. j = resampler_get_sample_count(player->resampler[0]);
  305. while (total_bytes < len && resampler_get_sample_count(player->resampler[0]) > 0) {
  306. OGG_FillResample(player, (ogg_int16_t *)(stream + total_bytes));
  307. total_bytes += gConfig.iAudioChannels * sizeof(ogg_int16_t);
  308. }
  309. samples -= to_write; bout += to_write;
  310. }
  311. }
  312. else {
  313. int i;
  314. ogg_int16_t *ptr = (ogg_int16_t *)(stream + total_bytes);
  315. bout = (len - total_bytes) / gConfig.iAudioChannels / sizeof(ogg_int16_t);
  316. if (bout > samples) bout = samples;
  317. for (i = 0; i < bout; i++) {
  318. if (gConfig.iAudioChannels == 2) {
  319. ptr[0] = OGG_GetSample(pcm[0][i]);
  320. ptr[1] = (player->vi.channels > 1) ? OGG_GetSample(pcm[1][i]) : ptr[0];
  321. }
  322. else {
  323. if (player->vi.channels > 1) {
  324. ptr[0] = (short)((int)(OGG_GetSample(pcm[0][i]) + OGG_GetSample(pcm[1][i])) >> 1);
  325. }
  326. else {
  327. ptr[0] = OGG_GetSample(pcm[0][i]);
  328. }
  329. }
  330. ptr += gConfig.iAudioChannels;
  331. }
  332. total_bytes += bout * gConfig.iAudioChannels * sizeof(ogg_int16_t);
  333. }
  334. /* tell libvorbis how many samples we actually consumed */
  335. vorbis_synthesis_read(&player->vd, bout);
  336. }
  337. else {
  338. stage = STAGE_PACKETOUT;
  339. }
  340. break;
  341. case STAGE_REWIND:
  342. if (player->vi.rate != gConfig.iSampleRate) { /* If there are samples in the resampler, fetch them first */
  343. while (total_bytes < len && resampler_get_sample_count(player->resampler[0]) > 0) {
  344. OGG_FillResample(player, (ogg_int16_t *)(stream + total_bytes));
  345. total_bytes += gConfig.iAudioChannels * sizeof(ogg_int16_t);
  346. }
  347. /* Break out if there are still samples in the resampler */
  348. if (resampler_get_sample_count(player->resampler[0]) > 0) break;
  349. }
  350. OGG_Rewind(player);
  351. stage = player->iStage;
  352. break;
  353. default:
  354. return;
  355. }
  356. }
  357. player->iStage = stage;
  358. }
  359. }
  360. static BOOL
  361. OGG_Play(
  362. VOID *object,
  363. INT iNum,
  364. BOOL fLoop,
  365. FLOAT flFadeTime
  366. )
  367. {
  368. LPOGGPLAYER player = (LPOGGPLAYER)object;
  369. //
  370. // Check for NULL pointer.
  371. //
  372. if (player == NULL)
  373. {
  374. return FALSE;
  375. }
  376. player->fLoop = fLoop;
  377. if (iNum == player->iMusic)
  378. {
  379. return TRUE;
  380. }
  381. player->fReady = FALSE;
  382. OGG_Cleanup(player);
  383. if (player->fp)
  384. {
  385. UTIL_CloseFile(player->fp);
  386. player->fp = NULL;
  387. }
  388. if (iNum == -1)
  389. {
  390. return TRUE;
  391. }
  392. player->iMusic = iNum;
  393. player->fp = UTIL_OpenFile(PAL_va(0, "ogg/%.2d.ogg", iNum));
  394. if (player->fp == NULL)
  395. {
  396. return FALSE;
  397. }
  398. if (!OGG_Rewind(player))
  399. {
  400. UTIL_CloseFile(player->fp);
  401. player->fp = NULL;
  402. return FALSE;
  403. }
  404. return TRUE;
  405. }
  406. static VOID
  407. OGG_Shutdown(
  408. VOID *object
  409. )
  410. {
  411. if (object)
  412. {
  413. LPOGGPLAYER player = (LPOGGPLAYER)object;
  414. OGG_Cleanup(player);
  415. resampler_delete(player->resampler[0]);
  416. resampler_delete(player->resampler[1]);
  417. UTIL_CloseFile(player->fp);
  418. free(player);
  419. }
  420. }
  421. LPAUDIOPLAYER
  422. OGG_Init(
  423. VOID
  424. )
  425. {
  426. LPOGGPLAYER player;
  427. if ((player = (LPOGGPLAYER)malloc(sizeof(OGGPLAYER))) != NULL)
  428. {
  429. memset(player, 0, sizeof(OGGPLAYER));
  430. player->FillBuffer = OGG_FillBuffer;
  431. player->Play = OGG_Play;
  432. player->Shutdown = OGG_Shutdown;
  433. player->fp = NULL;
  434. player->iMusic = -1;
  435. player->iFlags = 0;
  436. player->iStage = 0;
  437. player->fLoop = FALSE;
  438. player->fReady = FALSE;
  439. player->fUseResampler = FALSE;
  440. player->resampler[0] = resampler_create();
  441. if (player->resampler[0])
  442. {
  443. player->resampler[1] = resampler_create();
  444. if (player->resampler[1] == NULL)
  445. {
  446. resampler_delete(player->resampler[0]);
  447. player->resampler[0] = NULL;
  448. }
  449. }
  450. }
  451. return (LPAUDIOPLAYER)player;
  452. }
  453. #else
  454. LPAUDIOPLAYER
  455. OGG_Init(
  456. VOID
  457. )
  458. {
  459. return NULL;
  460. }
  461. #endif