DecodeThread.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  1. /*
  2. ** Copyright (C) 2007-2011 Nullsoft, Inc.
  3. **
  4. ** This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held
  5. ** liable for any damages arising from the use of this software.
  6. **
  7. ** Permission is granted to anyone to use this software for any purpose, including commercial applications, and to
  8. ** alter it and redistribute it freely, subject to the following restrictions:
  9. **
  10. ** 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software.
  11. ** If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
  12. **
  13. ** 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
  14. **
  15. ** 3. This notice may not be removed or altered from any source distribution.
  16. **
  17. ** Author: Ben Allison [email protected]
  18. ** Created: March 1, 2007
  19. **
  20. */
  21. #ifndef WIN32_LEAN_AND_MEAN
  22. #define WIN32_LEAN_AND_MEAN
  23. #endif
  24. #include "main.h"
  25. #include <windows.h>
  26. #include <math.h>
  27. #include <assert.h>
  28. #include <locale.h>
  29. #include <FLAC/all.h>
  30. #include "StreamFileWin32.h"
  31. #include "../Winamp/wa_ipc.h"
  32. #include "QuickBuf.h"
  33. #include "api__in_flv.h"
  34. #include "../nu/AudioOutput.h"
  35. #include "../Agave/Language/api_language.h"
  36. #include "FLACFileCallbacks.h"
  37. #include "nx/nxpath.h"
  38. int m_force_seek = -1; // el hacko grande
  39. const DWORD PAUSE_TIMEOUT = 100; // number of milliseconds to sleep for when paused
  40. static bool paused = false;
  41. // could probably move this inside client_data
  42. int realbits;
  43. int bps;
  44. int samplerate;
  45. int channels;
  46. volatile int currentSongLength=-1000;
  47. int averageBitrate;
  48. // if input plugins weren't single-instance only, we could put this in thread-local-storage
  49. static FLAC__StreamDecoder *decoder = 0;
  50. static uint64_t fileSize = 0;
  51. static FLAC__uint64 decodePosition = 0;
  52. double gain = 1.0;
  53. static double buffer_scale=1.0;
  54. class FLACWait
  55. {
  56. public:
  57. int WaitOrAbort(int time_in_ms)
  58. {
  59. if (WaitForSingleObject(killswitch, time_in_ms) == WAIT_OBJECT_0)
  60. return 1;
  61. return 0;
  62. }
  63. };
  64. volatile int bufferCount=0;
  65. static void Buffering(int bufStatus, const wchar_t *displayString)
  66. {
  67. if (bufStatus < 0 || bufStatus > 100)
  68. return;
  69. char tempdata[75*2] = {0, };
  70. int csa = plugin.SAGetMode();
  71. if (csa & 1)
  72. {
  73. for (int x = 0; x < bufStatus*75 / 100; x ++)
  74. tempdata[x] = x * 16 / 75;
  75. }
  76. else if (csa&2)
  77. {
  78. int offs = (csa & 1) ? 75 : 0;
  79. int x = 0;
  80. while (x < bufStatus*75 / 100)
  81. {
  82. tempdata[offs + x++] = -6 + x * 14 / 75;
  83. }
  84. while (x < 75)
  85. {
  86. tempdata[offs + x++] = 0;
  87. }
  88. }
  89. else if (csa == 4)
  90. {
  91. tempdata[0] = tempdata[1] = (bufStatus * 127 / 100);
  92. }
  93. if (csa) plugin.SAAdd(tempdata, ++bufferCount, (csa == 3) ? 0x80000003 : csa);
  94. /*
  95. TODO
  96. wchar_t temp[64] = {0};
  97. StringCchPrintf(temp, 64, L"%s: %d%%",displayString, bufStatus);
  98. SetStatus(temp);
  99. */
  100. //SetVideoStatusText(temp); // TODO: find a way to set the old status back
  101. // videoOutput->notifyBufferState(static_cast<int>(bufStatus*2.55f));
  102. }
  103. static nu::AudioOutput<FLACWait> audio_output(&plugin);
  104. #pragma region Truncaters
  105. inline static void clip(double &x, double a, double b)
  106. {
  107. double x1 = fabs(x - a);
  108. double x2 = fabs(x - b);
  109. x = x1 + (a + b);
  110. x -= x2;
  111. x *= 0.5;
  112. }
  113. static void InterleaveAndTruncate32(const FLAC__int32 *const buffer[], void *_output, int bps, int channels, int blocksize, double gain)
  114. {
  115. // TODO: this can be sped up significantly
  116. FLAC__int32 *output = (FLAC__int32 *)_output;
  117. for (int b = 0;b < blocksize;b++)
  118. {
  119. for (int c = 0;c < channels;c++)
  120. {
  121. double appliedGain = gain * (double)buffer[c][b];
  122. // TODO: add dither
  123. clip(appliedGain, -2147483648., 2147483647.);
  124. *output = (FLAC__int32)appliedGain;
  125. output++;
  126. }
  127. }
  128. }
  129. static void InterleaveAndTruncate24(const FLAC__int32 *const buffer[], void *_output, int bps, int channels, int blocksize, double gain)
  130. {
  131. char *output = (char *)_output;
  132. for (int b = 0;b < blocksize;b++)
  133. {
  134. for (int c = 0;c < channels;c++)
  135. {
  136. double appliedGain = gain * (double)buffer[c][b];
  137. // TODO: add dither
  138. clip(appliedGain, -8388608., 8388607.);
  139. FLAC__int32 sample = (FLAC__int32)appliedGain;
  140. // little endian specific code
  141. output[0] = (unsigned char)(sample);
  142. output[1] = (unsigned char)(sample >> 8);
  143. output[2] = (unsigned char)(sample >> 16);
  144. output += 3;
  145. }
  146. }
  147. }
  148. static void InterleaveAndTruncate16(const FLAC__int32 *const buffer[], void *_output, int bps, int channels, int blocksize, double gain)
  149. {
  150. short *output = (short *)_output;
  151. for (int b = 0;b < blocksize;b++)
  152. {
  153. for (int c = 0;c < channels;c++)
  154. {
  155. double appliedGain = gain * (double)buffer[c][b];
  156. // TODO: add dither
  157. clip(appliedGain, -32768., 32767.);
  158. FLAC__int32 sample = (FLAC__int32)appliedGain;
  159. *output = (short) sample ;
  160. output ++;
  161. }
  162. }
  163. }
  164. static void InterleaveAndTruncate8(const FLAC__int32 *const buffer[], void *_output, int bps, int channels, int blocksize, double gain)
  165. {
  166. unsigned char *output = (unsigned char *)_output;
  167. for (int b = 0;b < blocksize;b++)
  168. {
  169. for (int c = 0;c < channels;c++)
  170. {
  171. double appliedGain = gain * (double)buffer[c][b];
  172. // TODO: add dither
  173. clip(appliedGain, -128., 127.);
  174. FLAC__int32 sample = (FLAC__int32)appliedGain;
  175. *output = (unsigned char)(sample + 128);
  176. output++;
  177. }
  178. }
  179. }
  180. /* --- Versions without gain adjustment --- */
  181. static void InterleaveAndTruncate32(const FLAC__int32 *const buffer[], void *_output, int bps, int channels, int blocksize)
  182. {
  183. FLAC__int32 *output = (FLAC__int32 *)_output;
  184. for (int b = 0;b < blocksize;b++)
  185. {
  186. for (int c = 0;c < channels;c++)
  187. {
  188. *output = buffer[c][b];
  189. output++;
  190. }
  191. }
  192. }
  193. static void InterleaveAndTruncate24(const FLAC__int32 *const buffer[], void *_output, int bps, int channels, int blocksize)
  194. {
  195. char *output = (char *)_output;
  196. for (int b = 0;b < blocksize;b++)
  197. {
  198. for (int c = 0;c < channels;c++)
  199. {
  200. FLAC__int32 sample = buffer[c][b];
  201. // little endian specific code
  202. output[0] = (unsigned char)(sample);
  203. output[1] = (unsigned char)(sample >> 8);
  204. output[2] = (unsigned char)(sample >> 16);
  205. output += 3;
  206. }
  207. }
  208. }
  209. static void InterleaveAndTruncate16(const FLAC__int32 *const buffer[], void *_output, int bps, int channels, int blocksize)
  210. {
  211. short *output = (short *)_output;
  212. for (int b = 0;b < blocksize;b++)
  213. {
  214. for (int c = 0;c < channels;c++)
  215. {
  216. *output = (short) buffer[c][b];
  217. output ++;
  218. }
  219. }
  220. }
  221. static void InterleaveAndTruncate8(const FLAC__int32 *const buffer[], void *_output, int bps, int channels, int blocksize)
  222. {
  223. unsigned char *output = (unsigned char *)_output;
  224. for (int b = 0;b < blocksize;b++)
  225. {
  226. for (int c = 0;c < channels;c++)
  227. {
  228. *output = (unsigned char)(buffer[c][b] + 128);
  229. output++;
  230. }
  231. }
  232. }
  233. void InterleaveAndTruncate(const FLAC__int32 *const buffer[], void *_output, int bps, int channels, int blocksize, double gain)
  234. {
  235. if (gain == 1.0) // if it's EXACTLY 1.0, i.e. from a hardcoded value. not meant to be a "RG happens to be 1.0" check
  236. {
  237. switch(bps)
  238. {
  239. case 8:
  240. InterleaveAndTruncate8(buffer, _output, bps, channels, blocksize);
  241. break;
  242. case 16:
  243. InterleaveAndTruncate16(buffer, _output, bps, channels, blocksize);
  244. break;
  245. case 24:
  246. InterleaveAndTruncate24(buffer, _output, bps, channels, blocksize);
  247. break;
  248. case 32:
  249. InterleaveAndTruncate32(buffer, _output, bps, channels, blocksize);
  250. break;
  251. }
  252. }
  253. else // apply replay gain
  254. {
  255. switch(bps)
  256. {
  257. case 8:
  258. InterleaveAndTruncate8(buffer, _output, bps, channels, blocksize, gain);
  259. break;
  260. case 16:
  261. InterleaveAndTruncate16(buffer, _output, bps, channels, blocksize, gain);
  262. break;
  263. case 24:
  264. InterleaveAndTruncate24(buffer, _output, bps, channels, blocksize, gain);
  265. break;
  266. case 32:
  267. InterleaveAndTruncate32(buffer, _output, bps, channels, blocksize, gain);
  268. break;
  269. }
  270. }
  271. }
  272. #pragma endregion
  273. QuickBuf output;
  274. FLAC__uint64 lastoutputtime;
  275. static FLAC__StreamDecoderWriteStatus OnAudio(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 *const buffer[], void *client_data)
  276. {
  277. // TODO: if frame bps/samplerate/channels doesn't equal our own, we'll probably have to close & re-open the audio output
  278. // mux buffer into interleaved samples
  279. FLAC__uint64 newPosition;
  280. FLAC__stream_decoder_get_decode_position(decoder, &newPosition);
  281. FLAC__uint64 delta = newPosition - decodePosition;
  282. decodePosition = newPosition;
  283. if (!config_average_bitrate)
  284. plugin.SetInfo((int)(delta / (125.*frame->header.blocksize / samplerate)), -1, -1, -1);
  285. else if (fixBitrate)
  286. {
  287. fixBitrate = false;
  288. plugin.SetInfo(averageBitrate, -1, -1, -1);
  289. }
  290. if (frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER)
  291. lastoutputtime = 1000ULL*frame->header.number.sample_number / (FLAC__uint64)samplerate;
  292. else
  293. lastoutputtime = 0;
  294. int byteLength = (bps / 8) * channels * frame->header.blocksize;
  295. output.Reserve(byteLength*2);
  296. InterleaveAndTruncate(buffer, output, bps, channels, frame->header.blocksize, gain);
  297. audio_output.Write(output, byteLength);
  298. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  299. }
  300. static int GetBits(int incoming)
  301. {
  302. int bits = AGAVE_API_CONFIG->GetUnsigned(playbackConfigGroupGUID, L"bits", 16);
  303. if (bits > 16 && AGAVE_API_CONFIG->GetBool(playbackConfigGroupGUID, L"replaygain", false))
  304. return bits;
  305. return min(bits, incoming);
  306. }
  307. static double GetGain(const FLAC__StreamMetadata *metadata)
  308. {
  309. if (AGAVE_API_CONFIG->GetBool(playbackConfigGroupGUID, L"replaygain", false))
  310. {
  311. if (metadata)
  312. {
  313. int gainPos = -1, peakPos = -1;
  314. switch (AGAVE_API_CONFIG->GetUnsigned(playbackConfigGroupGUID, L"replaygain_source", 0))
  315. {
  316. case 0: // track
  317. gainPos = FLAC__metadata_object_vorbiscomment_find_entry_from(metadata, 0, "REPLAYGAIN_TRACK_GAIN");
  318. if (gainPos < 0 && !AGAVE_API_CONFIG->GetBool(playbackConfigGroupGUID, L"replaygain_preferred_only", false))
  319. gainPos = FLAC__metadata_object_vorbiscomment_find_entry_from(metadata, 0, "REPLAYGAIN_ALBUM_GAIN");
  320. peakPos = FLAC__metadata_object_vorbiscomment_find_entry_from(metadata, 0, "REPLAYGAIN_TRACK_PEAK");
  321. if (peakPos < 0 && !AGAVE_API_CONFIG->GetBool(playbackConfigGroupGUID, L"replaygain_preferred_only", false))
  322. peakPos = FLAC__metadata_object_vorbiscomment_find_entry_from(metadata, 0, "REPLAYGAIN_ALBUM_PEAK");
  323. break;
  324. case 1:
  325. gainPos = FLAC__metadata_object_vorbiscomment_find_entry_from(metadata, 0, "REPLAYGAIN_ALBUM_GAIN");
  326. if (gainPos < 0 && !AGAVE_API_CONFIG->GetBool(playbackConfigGroupGUID, L"replaygain_preferred_only", false))
  327. gainPos = FLAC__metadata_object_vorbiscomment_find_entry_from(metadata, 0, "REPLAYGAIN_TRACK_GAIN");
  328. peakPos = FLAC__metadata_object_vorbiscomment_find_entry_from(metadata, 0, "REPLAYGAIN_ALBUM_PEAK");
  329. if (peakPos < 0 && !AGAVE_API_CONFIG->GetBool(playbackConfigGroupGUID, L"replaygain_preferred_only", false))
  330. peakPos = FLAC__metadata_object_vorbiscomment_find_entry_from(metadata, 0, "REPLAYGAIN_TRACK_PEAK");
  331. break;
  332. }
  333. double dB = 0, peak = 1.0;
  334. _locale_t C_locale = WASABI_API_LNG->Get_C_NumericLocale();
  335. if (gainPos >= 0)
  336. {
  337. const char *entry = (const char *)metadata->data.vorbis_comment.comments[gainPos].entry;
  338. const char *value = strchr(entry, '='); // find the first equal
  339. if (value++)
  340. {
  341. if (value[0] == '+')
  342. dB = _atof_l(&value[1], C_locale);
  343. else
  344. dB = _atof_l(value, C_locale);
  345. }
  346. }
  347. else
  348. {
  349. dB = AGAVE_API_CONFIG->GetFloat(playbackConfigGroupGUID, L"non_replaygain", -6.0);
  350. return pow(10.0, dB / 20.0);
  351. }
  352. if (peakPos >= 0)
  353. {
  354. const char *entry = (const char *)metadata->data.vorbis_comment.comments[peakPos].entry;
  355. const char *value = strchr(entry, '='); // find the first equal
  356. if (value++)
  357. {
  358. peak = _atof_l(value, C_locale);
  359. }
  360. }
  361. switch (AGAVE_API_CONFIG->GetUnsigned(playbackConfigGroupGUID, L"replaygain_mode", 1))
  362. {
  363. case 0: // apply gain
  364. return pow(10.0, dB / 20.0);
  365. break;
  366. case 1: // apply gain, but don't clip
  367. return min(pow(10.0, dB / 20.0), 1.0 / peak);
  368. break;
  369. case 2: // normalize
  370. return 1.0 / peak;
  371. break;
  372. case 3: // prevent clipping
  373. if (peak > 1.0)
  374. return 1.0 / peak;
  375. else
  376. return 1.0;
  377. }
  378. }
  379. else
  380. {
  381. double dB = AGAVE_API_CONFIG->GetFloat(playbackConfigGroupGUID, L"non_replaygain", -6.0);
  382. return pow(10.0, dB / 20.0);
  383. }
  384. }
  385. return 1.0;
  386. }
  387. static void OnMetadata(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  388. {
  389. switch (metadata->type)
  390. {
  391. case FLAC__METADATA_TYPE_STREAMINFO:
  392. {
  393. realbits = metadata->data.stream_info.bits_per_sample;
  394. channels = metadata->data.stream_info.channels;
  395. samplerate = metadata->data.stream_info.sample_rate;
  396. bps = GetBits(metadata->data.stream_info.bits_per_sample);
  397. gain = GetGain(0) * pow(2., (double)(bps - realbits));
  398. if (metadata->data.stream_info.total_samples)
  399. {
  400. currentSongLength = (int)((metadata->data.stream_info.total_samples*1000ULL)/(uint64_t)samplerate);
  401. averageBitrate = (int)(fileSize / (125 * metadata->data.stream_info.total_samples / (__int64)samplerate));
  402. }
  403. else
  404. {
  405. currentSongLength=-1000;
  406. averageBitrate=0;
  407. }
  408. }
  409. break;
  410. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  411. gain = GetGain(metadata) * pow(2., (double)(bps - realbits));
  412. break;
  413. }
  414. }
  415. static void OnError(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  416. {
  417. //client_data = client_data; // dummy line so i can set a breakpoint
  418. }
  419. void CALLBACK APCPause(ULONG_PTR data)
  420. {
  421. paused = !!data;
  422. plugin.outMod->Pause(!!paused);
  423. }
  424. void CALLBACK APCSeek(ULONG_PTR data)
  425. {
  426. // TODO: break out of end-of-file handling if necessary
  427. buffer_scale=1.0;
  428. int time_in_ms = (int)data;
  429. lastoutputtime=time_in_ms; // cheating a bit here :)
  430. audio_output.Flush(time_in_ms);
  431. __int64 frames = Int32x32To64(time_in_ms, samplerate) / 1000;
  432. FLAC__StreamDecoderState state = FLAC__stream_decoder_get_state(decoder);
  433. plugin.outMod->Pause(0);
  434. FLAC__stream_decoder_seek_absolute(decoder, frames);
  435. plugin.outMod->Pause(paused);
  436. if (FLAC__stream_decoder_get_state(decoder) == FLAC__STREAM_DECODER_SEEK_ERROR)
  437. {
  438. FLAC__stream_decoder_flush(decoder);
  439. }
  440. }
  441. static const double prebuffer_seconds = 0.5;
  442. static bool DoBuffering(nx_file_t file)
  443. {
  444. // TODO: check for disconnect, etc.
  445. // anything less than half-a-second and we'll rebuffer. but when we rebuffer, we'll get 2 seconds worth of audio
  446. // also, every time we're forced to re-buffer, we'll double the buffer amount
  447. uint64_t required;
  448. if (averageBitrate > 0)
  449. {
  450. required = (uint64_t)((double)averageBitrate * 1000.0 * buffer_scale * prebuffer_seconds / 8.0);
  451. }
  452. else /* no bitrate specified, let's assume 1000kbps */
  453. {
  454. required = (uint64_t)(1000.0 * 1000.0 * buffer_scale * prebuffer_seconds / 8.0);
  455. }
  456. uint64_t available;
  457. if (NXFileProgressiveDownloaderAvailable(file, required, &available) == NErr_True)
  458. return true;
  459. Buffering(0, 0);
  460. bufferCount=lastoutputtime;
  461. required *= 4;
  462. buffer_scale *= 2.0;
  463. while (NXFileProgressiveDownloaderAvailable(file, required, &available) == NErr_False)
  464. {
  465. int percent = (int)((double)available * 100.0 / (double)required);
  466. if (percent <= 0)
  467. percent=1;
  468. if (percent > 99)
  469. percent=99;
  470. Buffering(percent, 0);
  471. if (WaitForSingleObject(killswitch, 10) == WAIT_OBJECT_0)
  472. {
  473. return false;
  474. }
  475. }
  476. Buffering(100, 0);
  477. bufferCount=0;
  478. return true;
  479. }
  480. extern HANDLE threadStarted;
  481. DWORD CALLBACK FLACThread(LPVOID param)
  482. {
  483. buffer_scale=1.0;
  484. bool streaming=false;
  485. nx_file_t file;
  486. FLACClientData state;
  487. audio_output.Init(plugin.outMod);
  488. paused=false;
  489. SetEvent(threadStarted);
  490. nx_uri_t filename = (nx_uri_t)param;
  491. decodePosition = 0;
  492. gain = 1.0;
  493. bufferCount = 0;
  494. decoder = FLAC__stream_decoder_new();
  495. if (decoder == 0)
  496. {
  497. if (WaitForSingleObject(killswitch, 200) != WAIT_OBJECT_0)
  498. PostMessage(plugin.hMainWindow, WM_WA_MPEG_EOF, 0, 0);
  499. free(filename);
  500. return 0;
  501. }
  502. FLAC__stream_decoder_set_md5_checking(decoder, false);
  503. FLAC__stream_decoder_set_metadata_respond(decoder, FLAC__METADATA_TYPE_VORBIS_COMMENT);
  504. plugin.is_seekable = 1;
  505. int ret;
  506. if (NXPathIsURL(filename) == NErr_True)
  507. {
  508. // Display a window to request to download
  509. //
  510. MessageBox(NULL, L"Cannot stream flac file, please download it", NULL, 0);
  511. /*
  512. char agent[256] = { 0 };
  513. snprintf(agent, 256, "User-Agent: %S/%S", "Winamp", "5.9.1");
  514. ret = NXFileOpenProgressiveDownloader(&file, filename, nx_file_FILE_read_binary, 0, agent); // TODO: calculate real user agent
  515. */
  516. return NErr_Disabled;
  517. }
  518. else
  519. {
  520. ret = NXFileOpenFile(&file, filename, nx_file_FILE_read_binary);
  521. }
  522. if (ret != NErr_Success)
  523. {
  524. FLAC__stream_decoder_delete(decoder);
  525. if (WaitForSingleObject(killswitch, 200) != WAIT_OBJECT_0)
  526. PostMessage(plugin.hMainWindow, WM_WA_MPEG_EOF, 0, 0);
  527. NXURIRelease(filename);
  528. return 0;
  529. }
  530. state.SetFile(file);
  531. NXFileLength(file, &fileSize);
  532. if (FLAC__stream_decoder_init_stream(
  533. decoder,
  534. FLAC_NXFile_Read,
  535. FLAC_NXFile_Seek,
  536. FLAC_NXFile_Tell,
  537. FLAC_NXFile_Length,
  538. FLAC_NXFile_EOF,
  539. OnAudio,
  540. OnMetadata, // or NULL
  541. OnError,
  542. &state
  543. ) != FLAC__STREAM_DECODER_INIT_STATUS_OK)
  544. {
  545. FLAC__stream_decoder_delete(decoder);
  546. NXFileRelease(file);
  547. if (WaitForSingleObject(killswitch, 200) != WAIT_OBJECT_0)
  548. PostMessage(plugin.hMainWindow, WM_WA_MPEG_EOF, 0, 0);
  549. NXURIRelease(filename);
  550. return 0;
  551. }
  552. FLAC__stream_decoder_process_until_end_of_metadata(decoder);
  553. if (!audio_output.Open(0, channels, samplerate, bps))
  554. {
  555. FLAC__stream_decoder_finish(decoder);
  556. FLAC__stream_decoder_delete(decoder);
  557. NXFileRelease(file);
  558. if (WaitForSingleObject(killswitch, 200) != WAIT_OBJECT_0)
  559. PostMessage(plugin.hMainWindow, WM_WA_MPEG_EOF, 0, 0);
  560. NXURIRelease(filename);
  561. return 0;
  562. }
  563. plugin.SetInfo(averageBitrate, -1, -1, -1);
  564. plugin.outMod->SetVolume(volume);
  565. plugin.outMod->SetPan(pan);
  566. if (streaming && !DoBuffering(file))
  567. {
  568. FLAC__stream_decoder_finish(decoder);
  569. FLAC__stream_decoder_delete(decoder);
  570. NXFileRelease(file);
  571. NXURIRelease(filename);
  572. return 0;
  573. }
  574. if (m_force_seek != -1)
  575. APCSeek((ULONG_PTR)m_force_seek);
  576. m_force_seek = -1;
  577. HANDLE events[] = {killswitch};
  578. DWORD timeout = 0;
  579. while (true)
  580. {
  581. DWORD result = WaitForMultipleObjectsEx(sizeof(events) / sizeof(*events), events, FALSE, timeout, TRUE);
  582. switch (result)
  583. {
  584. case WAIT_OBJECT_0:// kill thread
  585. FLAC__stream_decoder_finish(decoder);
  586. FLAC__stream_decoder_delete(decoder);
  587. NXFileRelease(file);
  588. NXURIRelease(filename);
  589. return 0;
  590. case WAIT_TIMEOUT:
  591. timeout = paused ? PAUSE_TIMEOUT : 0;
  592. if (streaming && !DoBuffering(file))
  593. {
  594. FLAC__stream_decoder_finish(decoder);
  595. FLAC__stream_decoder_delete(decoder);
  596. NXFileRelease(file);
  597. NXURIRelease(filename);
  598. return 0;
  599. }
  600. if (!paused)
  601. {
  602. FLAC__bool decode_successful = FLAC__stream_decoder_process_single(decoder);
  603. FLAC__StreamDecoderState FLACstate = FLAC__stream_decoder_get_state(decoder);
  604. if (FLACstate == FLAC__STREAM_DECODER_END_OF_STREAM)
  605. {
  606. audio_output.Write(0, 0);
  607. if (audio_output.WaitWhilePlaying())
  608. {
  609. FLAC__stream_decoder_finish(decoder);
  610. FLAC__stream_decoder_delete(decoder);
  611. NXFileRelease(file);
  612. NXURIRelease(filename);
  613. return 0;
  614. }
  615. PostMessage(plugin.hMainWindow, WM_WA_MPEG_EOF, 0, 0);
  616. timeout = INFINITE; // sit and wait for killswitch
  617. }
  618. else if (!decode_successful)
  619. {
  620. // some other error - abort playback
  621. // if we can find FLAC files with errors, we might be able to gracefully handle some errors
  622. PostMessage(plugin.hMainWindow, WM_WA_MPEG_EOF, 0, 0);
  623. timeout = INFINITE; // sit and wait for killswitch
  624. }
  625. }
  626. break;
  627. }
  628. }
  629. return 0;
  630. }