oggplay.c 15 KB

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