oggplay.c 15 KB

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