oggplay.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  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, int volume)
  60. {
  61. int val = floor(pcm * 32767.f + .5f) * volume / SDL_MIX_MAXVOLUME;
  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. #ifdef __SYMBIAN32__
  229. int volume = g_iVolume / 2;
  230. #else
  231. int volume = SDL_MIX_MAXVOLUME / 2;
  232. #endif
  233. if (player->fReady) {
  234. ogg_packet op; /* one raw packet of data for decode */
  235. int total_bytes = 0, stage = player->iStage;
  236. while (total_bytes < len) {
  237. float **pcm;
  238. int samples, result;
  239. switch (stage)
  240. {
  241. case STAGE_PAGEOUT: /* PAGEOUT stage */
  242. result = ogg_sync_pageout(&player->oy, &player->og);
  243. if (result > 0) {
  244. /* can safely ignore errors at this point */
  245. ogg_stream_pagein(&player->os, &player->og);
  246. stage = STAGE_PACKETOUT;
  247. }
  248. else {
  249. if (result == 0) { /* need more data */
  250. char *buffer = ogg_sync_buffer(&player->oy, OGG_BUFFER_LENGTH);
  251. int bytes = fread(buffer, 1, OGG_BUFFER_LENGTH, player->fp);
  252. ogg_sync_wrote(&player->oy, bytes);
  253. stage = (bytes > 0) ? STAGE_PAGEOUT : STAGE_REWIND;
  254. }
  255. break;
  256. }
  257. case STAGE_PACKETOUT:
  258. result = ogg_stream_packetout(&player->os, &op);
  259. if (result > 0) {
  260. /* we have a packet. Decode it */
  261. if (vorbis_synthesis(&player->vb, &op) == 0) { /* test for success! */
  262. vorbis_synthesis_blockin(&player->vd, &player->vb);
  263. }
  264. stage = STAGE_PCMOUT;
  265. }
  266. else {
  267. if (result == 0) { /* need more data */
  268. if (ogg_page_eos(&player->og)) {
  269. if (player->fLoop) {
  270. stage = STAGE_REWIND;
  271. }
  272. else {
  273. OGG_Cleanup(player);
  274. UTIL_CloseFile(player->fp);
  275. player->fp = NULL;
  276. return;
  277. }
  278. }
  279. else {
  280. stage = STAGE_PAGEOUT;
  281. }
  282. }
  283. break;
  284. }
  285. case STAGE_PCMOUT:
  286. if ((samples = vorbis_synthesis_pcmout(&player->vd, &pcm)) > 0) {
  287. int bout;
  288. if (player->fUseResampler) { /* Resampler is available and should be used */
  289. bout = 0;
  290. while (total_bytes < len && samples > 0) { /* Fill as many samples into resampler as possible */
  291. int i, j, to_write = resampler_get_free_count(player->resampler[0]);
  292. if (to_write > 0) {
  293. if (to_write >= samples) to_write = samples;
  294. for (i = 0; i < min(player->vi.channels, 2); i++) {
  295. float *mono = pcm[i] + bout;
  296. for (j = 0; j < to_write; j++) {
  297. resampler_write_sample(player->resampler[i], OGG_GetSample(mono[j], volume));
  298. }
  299. }
  300. }
  301. /* Fetch resampled samples if available */
  302. j = resampler_get_sample_count(player->resampler[0]);
  303. while (total_bytes < len && resampler_get_sample_count(player->resampler[0]) > 0) {
  304. OGG_FillResample(player, (ogg_int16_t *)(stream + total_bytes));
  305. total_bytes += gpGlobals->iAudioChannels * sizeof(ogg_int16_t);
  306. }
  307. samples -= to_write; bout += to_write;
  308. }
  309. }
  310. else {
  311. int i;
  312. ogg_int16_t *ptr = (ogg_int16_t *)(stream + total_bytes);
  313. bout = (len - total_bytes) / gpGlobals->iAudioChannels / sizeof(ogg_int16_t);
  314. if (bout > samples) bout = samples;
  315. for (i = 0; i < bout; i++) {
  316. if (gpGlobals->iAudioChannels == 2) {
  317. ptr[0] = SDL_SwapLE16(OGG_GetSample(pcm[0][i], volume));
  318. ptr[1] = (player->vi.channels > 1) ? SDL_SwapLE16(OGG_GetSample(pcm[1][i], volume)) : ptr[0];
  319. }
  320. else {
  321. if (player->vi.channels > 1) {
  322. ptr[0] = SDL_SwapLE16((short)((int)(OGG_GetSample(pcm[0][i], volume) + OGG_GetSample(pcm[1][i], volume)) >> 1));
  323. }
  324. else {
  325. ptr[0] = SDL_SwapLE16(OGG_GetSample(pcm[0][i], volume));
  326. }
  327. }
  328. ptr += gpGlobals->iAudioChannels;
  329. }
  330. total_bytes += bout * gpGlobals->iAudioChannels * sizeof(ogg_int16_t);
  331. }
  332. /* tell libvorbis how many samples we actually consumed */
  333. vorbis_synthesis_read(&player->vd, bout);
  334. }
  335. else {
  336. stage = STAGE_PACKETOUT;
  337. }
  338. break;
  339. case STAGE_REWIND:
  340. if (player->vi.rate != gpGlobals->iSampleRate) { /* If there are samples in the resampler, fetch them first */
  341. while (total_bytes < len && resampler_get_sample_count(player->resampler[0]) > 0) {
  342. OGG_FillResample(player, (ogg_int16_t *)(stream + total_bytes));
  343. total_bytes += gpGlobals->iAudioChannels * sizeof(ogg_int16_t);
  344. }
  345. /* Break out if there are still samples in the resampler */
  346. if (resampler_get_sample_count(player->resampler[0]) > 0) break;
  347. }
  348. OGG_Rewind(player);
  349. stage = player->iStage;
  350. break;
  351. default:
  352. return;
  353. }
  354. }
  355. player->iStage = stage;
  356. }
  357. }
  358. static BOOL
  359. OGG_Play(
  360. VOID *object,
  361. INT iNum,
  362. BOOL fLoop,
  363. FLOAT flFadeTime
  364. )
  365. {
  366. char filename[256];
  367. LPOGGPLAYER player = (LPOGGPLAYER)object;
  368. //
  369. // Check for NULL pointer.
  370. //
  371. if (player == NULL)
  372. {
  373. return FALSE;
  374. }
  375. player->fLoop = fLoop;
  376. if (iNum == player->iMusic)
  377. {
  378. return TRUE;
  379. }
  380. player->fReady = FALSE;
  381. OGG_Cleanup(player);
  382. if (player->fp)
  383. {
  384. UTIL_CloseFile(player->fp);
  385. player->fp = NULL;
  386. }
  387. if (iNum == -1)
  388. {
  389. return TRUE;
  390. }
  391. player->fp = UTIL_OpenFile(strcpy(filename, va("ogg/%.2d.ogg", iNum)));
  392. if (player->fp == NULL)
  393. {
  394. return FALSE;
  395. }
  396. else
  397. {
  398. player->iMusic = iNum;
  399. }
  400. if (!OGG_Rewind(player))
  401. {
  402. UTIL_CloseFile(player->fp);
  403. player->fp = NULL;
  404. return FALSE;
  405. }
  406. return TRUE;
  407. }
  408. static VOID
  409. OGG_Shutdown(
  410. VOID *object
  411. )
  412. {
  413. if (object)
  414. {
  415. LPOGGPLAYER player = (LPOGGPLAYER)object;
  416. OGG_Cleanup(player);
  417. resampler_delete(player->resampler[0]);
  418. resampler_delete(player->resampler[1]);
  419. UTIL_CloseFile(player->fp);
  420. free(player);
  421. }
  422. }
  423. LPMUSICPLAYER
  424. OGG_Init(
  425. LPCSTR szFileName
  426. )
  427. {
  428. LPOGGPLAYER player;
  429. if (player = (LPOGGPLAYER)malloc(sizeof(OGGPLAYER)))
  430. {
  431. memset(player, 0, sizeof(LPOGGPLAYER));
  432. player->FillBuffer = OGG_FillBuffer;
  433. player->Play = OGG_Play;
  434. player->Shutdown = OGG_Shutdown;
  435. player->fp = NULL;
  436. player->iMusic = -1;
  437. player->iFlags = 0;
  438. player->iStage = 0;
  439. player->fLoop = FALSE;
  440. player->fReady = FALSE;
  441. player->fUseResampler = FALSE;
  442. player->resampler[0] = resampler_create();
  443. if (player->resampler[0])
  444. {
  445. player->resampler[1] = resampler_create();
  446. if (player->resampler[1] == NULL)
  447. {
  448. resampler_delete(player->resampler[0]);
  449. player->resampler[0] = NULL;
  450. }
  451. }
  452. return (LPMUSICPLAYER)player;
  453. }
  454. else
  455. {
  456. return NULL;
  457. }
  458. }
  459. #endif