SHARE
TWEET

pt2play v1.60

8bitbubsy Sep 29th, 2013 (edited) 1,673 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. ** pt2play v1.60 - 11th of May 2020 - https://16-bits.org
  3. ** ======================================================
  4. **              - NOT BIG ENDIAN SAFE! -
  5. **
  6. ** Very accurate C port of ProTracker 2.3D's replayer, by
  7. ** Olav "8bitbubsy" Sorensen. Based on a ProTracker 2.3D disassembly
  8. ** using the PT1.2A source code for labels (names).
  9. **
  10. ** NOTE: This replayer does not support 15-sample formats!
  11. **
  12. ** The BLEP (Band-Limited Step) and filter routines were coded by aciddose.
  13. ** This makes the replayer sound much closer to a real Amiga.
  14. **
  15. ** You need to link winmm.lib for this to compile (-lwinmm).
  16. ** Alternatively, you can change out the mixer functions at the bottom with
  17. ** your own for your OS.
  18. **
  19. ** Example of pt2play usage:
  20. ** #include "pt2play.h"
  21. ** #include "songdata.h"
  22. **
  23. ** pt2play_PlaySong(songData, songDataLength, CIA_TEMPO_MODE, 48000);
  24. ** mainLoop();
  25. ** pt2play_Close();
  26. **
  27. ** To turn a song into an include file like in the example, you can use my win32
  28. ** bin2h tool from here: https://16-bits.org/etc/bin2h.zip
  29. **
  30. ** Changes in v1.60:
  31. ** - Removed fiter cutoff tweaks, and added new RC filter + "LED" filter routines
  32. ** - The arpeggio effect is now 100% accurate in its overflow behavior
  33. ** - Some cosmetic changes to the code
  34. **
  35. ** Changes in v1.59:
  36. ** - Added pt2play_SetMasterVol() and pt2play_GetMasterVol()
  37. **
  38. ** Changes in v1.58:
  39. ** - Fixed a serious bug where most songs would not play unless they had a tempo
  40. **   command issued.
  41. ** - Audio mixer has been slightly optimized
  42. ** - Audio dithering has been improved (rectangular -> triangular)
  43. **
  44. ** Changes in v1.57:
  45. ** - Audio signal phase is now inverted on output, like on A500/1200.
  46. **   This can actually change the bass response depending on your speaker elements.
  47. **   In my case, on Sennheiser HD598, I get deeper bass (same as on my Amigas).
  48. ** - All filters (low-pass, "LED", high-pass) have been hand-tweaked to better
  49. **   match A500 and A1200 from intensive testing and waveform comparison.
  50. **   Naturally, the analog filters vary from unit to unit because of component
  51. **   tolerance and aging components, but I am quite confident that this is a
  52. **   closer match than before anyway.
  53. ** - Added audio mixer dithering
  54. **
  55. ** Changes in v1.56:
  56. ** - Fixed EDx (Note Delay) not working
  57. ** - Minor code cleanup
  58. **
  59. ** Changes in v1.55:
  60. ** - Mixer is now using double-precision instead of single-precision accuracy.
  61. **
  62. ** Changes in v1.54:
  63. ** - Code cleanup (uses the "bool" type now, spaces -> tabs, comment style change)
  64. **
  65. ** Changes in v1.53:
  66. ** - Some code cleanup
  67. ** - Small optimziation to audio mixer
  68. **
  69. ** Changes in v1.52:
  70. ** - Added a function to retrieve song name
  71. **
  72. ** Changes in v1.51:
  73. ** - WinMM mixer has been rewritten to be safe (don't use syscalls in callback)
  74. ** - Some small changes to the pt2play functions (easier to use and safer!)
  75. */
  76.  
  77. /* pt2play.h:
  78.  
  79. #pragma once
  80.  
  81. #include <stdint.h>
  82. #include <stdbool.h>
  83.  
  84. enum
  85. {
  86.     CIA_TEMPO_MODE = 0, // default
  87.     VBLANK_TEMPO_MODE = 1
  88. };
  89.  
  90. bool pt2play_PlaySong(const uint8_t *moduleData, uint32_t dataLength, int8_t tempoMode, uint32_t audioFreq);
  91. void pt2play_Close(void);
  92. void pt2play_PauseSong(bool flag); // true/false
  93. void pt2play_TogglePause(void);
  94. void pt2play_SetStereoSep(uint8_t percentage); // 0..100
  95. void pt2play_SetMasterVol(uint16_t vol); // 0..256
  96. uint16_t pt2play_GetMasterVol(void); // 0..256
  97. char *pt2play_GetSongName(void); // max 20 chars (21 with '\0'), string is in latin1
  98. uint32_t pt2play_GetMixerTicks(void); // returns the amount of milliseconds of mixed audio (not realtime)
  99. */
  100.  
  101. // == USER ADJUSTABLE SETTINGS ==
  102. #define STEREO_SEP (20)    /* --> Stereo separation in percent - 0 = mono, 100 = hard pan (like Amiga) */
  103. #define USE_HIGHPASS       /* --> ~5.2Hz HP filter present in all Amigas */
  104. //#define USE_LOWPASS      /* --> ~4.42kHz LP filter present in all Amigas (except A1200) - comment out for sharper sound */
  105. #define USE_BLEP           /* --> Reduces some aliasing in the sound (closer to real Amiga) - comment out for a speed-up */
  106. //#define ENABLE_E8_EFFECT /* --> Enable E8x (Karplus-Strong) - comment out this line if E8x is used for something else */
  107. #define LED_FILTER         /* --> Process the Amiga "LED" filter - comment out to disable */
  108. #define MIX_BUF_SAMPLES 4096
  109.  
  110. #include <stdio.h>
  111. #include <stdlib.h>
  112. #include <string.h>
  113. #include <stdint.h>
  114. #include <stdbool.h>
  115. #include <math.h> // tan()
  116.  
  117. enum
  118. {
  119.     CIA_TEMPO_MODE = 0,
  120.     VBLANK_TEMPO_MODE = 1
  121. };
  122.  
  123. // main crystal oscillator
  124. #define AMIGA_PAL_XTAL_HZ 28375160
  125.  
  126. #define PAULA_PAL_CLK (AMIGA_PAL_XTAL_HZ / 8)
  127. #define CIA_PAL_CLK (AMIGA_PAL_XTAL_HZ / 40)
  128.  
  129. #define MAX_SAMPLE_LEN (0xFFFF*2)
  130. #define AMIGA_VOICES 4
  131.  
  132. #define INITIAL_DITHER_SEED 0x12345000
  133.  
  134. #ifdef USE_BLEP // do not change these!
  135. #define BLEP_ZC 16
  136. #define BLEP_OS 16
  137. #define BLEP_SP 16
  138. #define BLEP_NS (BLEP_ZC * BLEP_OS / BLEP_SP)
  139. #define BLEP_RNS 31 // RNS = (2^ > NS) - 1
  140. #endif
  141.  
  142. #ifdef USE_BLEP
  143. typedef struct blep_t
  144. {
  145.     int32_t index, samplesLeft;
  146.     double dBuffer[BLEP_RNS + 1], dLastValue;
  147. } blep_t;
  148. #endif
  149.  
  150. typedef struct ptChannel_t
  151. {
  152.     int8_t *n_start, *n_wavestart, *n_loopstart, n_chanindex, n_volume;
  153.     int8_t n_toneportdirec, n_pattpos, n_loopcount;
  154.     uint8_t n_wavecontrol, n_glissfunk, n_sampleoffset, n_toneportspeed;
  155.     uint8_t n_vibratocmd, n_tremolocmd, n_finetune, n_funkoffset;
  156.     uint8_t n_vibratopos, n_tremolopos;
  157.     int16_t n_period, n_note, n_wantedperiod;
  158.     uint16_t n_cmd, n_length, n_replen;
  159. } ptChannel_t;
  160.  
  161. typedef struct paulaVoice_t
  162. {
  163.     volatile bool active;
  164.     const int8_t *data, *newData;
  165.     int32_t length, newLength, pos;
  166.     double dVolume, dDelta, dPhase, dPanL, dPanR;
  167. #ifdef USE_BLEP
  168.     double dDeltaMul, dLastDelta, dLastPhase, dLastDeltaMul;
  169. #endif
  170. } paulaVoice_t;
  171.  
  172. #if defined(USE_HIGHPASS) || defined(USE_LOWPASS)
  173. typedef struct rcFilter_t
  174. {
  175.     double buffer[2];
  176.     double c, c2, g, cg;
  177. } rcFilter_t;
  178. #endif
  179.  
  180. #ifdef LED_FILTER
  181.  
  182. #define DENORMAL_OFFSET 1e-10
  183. typedef struct ledFilter_t
  184. {
  185.     double buffer[4];
  186.     double c, ci, feedback, bg, cg, c2;
  187. } ledFilter_t;
  188. #endif
  189.  
  190. static char songName[20 + 1];
  191. static volatile bool musicPaused, SongPlaying;
  192. static bool PBreakFlag, PosJumpAssert;
  193. static int8_t *SampleStarts[31], *SampleData, TempoMode, SongPosition, EmptySample[MAX_SAMPLE_LEN];
  194. static int8_t PBreakPosition, PattDelTime, PattDelTime2;
  195. static uint8_t SetBPMFlag, *SongDataPtr, LowMask, Counter, CurrSpeed, stereoSep = STEREO_SEP;
  196. static uint16_t PatternPos, bpmTab[256-32];
  197. static int32_t soundBufferSize, audioRate, samplesPerTickLeft, samplesPerTick, oldPeriod;
  198. static int32_t randSeed = INITIAL_DITHER_SEED, masterVol = 256;
  199. static uint32_t PattPosOff, sampleCounter;
  200. static double dOldVoiceDelta, dPeriodToDeltaDiv, *dMixBufferL, *dMixBufferR;
  201. static double dPrngStateL, dPrngStateR;
  202. static ptChannel_t ChanTemp[AMIGA_VOICES];
  203. static paulaVoice_t paula[AMIGA_VOICES];
  204. #ifdef USE_BLEP
  205. static double dOldVoiceDeltaMul;
  206. static blep_t blep[AMIGA_VOICES], blepVol[AMIGA_VOICES];
  207. #endif
  208. #ifdef USE_HIGHPASS
  209. static rcFilter_t filterHi;
  210. #endif
  211. #ifdef USE_LOWPASS
  212. static rcFilter_t filterLo;
  213. #endif
  214. #ifdef LED_FILTER
  215. static ledFilter_t filterLED;
  216. static bool LEDFilterOn;
  217. #endif
  218.  
  219. static const uint8_t ArpTickTable[32] = // not from PT2 replayer
  220. {
  221.     0,1,2,0,1,2,0,1,2,0,1,2,0,1,2,
  222.     0,1,2,0,1,2,0,1,2,0,1,2,0,1,2,
  223.     0,1
  224. };
  225.  
  226. static const uint8_t FunkTable[16] =
  227. {
  228.     0x00, 0x05, 0x06, 0x07, 0x08, 0x0A, 0x0B, 0x0D,
  229.     0x10, 0x13, 0x16, 0x1A, 0x20, 0x2B, 0x40, 0x80
  230. };
  231.  
  232. static const uint8_t VibratoTable[32] =
  233. {
  234.     0x00, 0x18, 0x31, 0x4A, 0x61, 0x78, 0x8D, 0xA1,
  235.     0xB4, 0xC5, 0xD4, 0xE0, 0xEB, 0xF4, 0xFA, 0xFD,
  236.     0xFF, 0xFD, 0xFA, 0xF4, 0xEB, 0xE0, 0xD4, 0xC5,
  237.     0xB4, 0xA1, 0x8D, 0x78, 0x61, 0x4A, 0x31, 0x18
  238. };
  239.  
  240. static const int16_t PeriodTable[(37*16)+15] =
  241. {
  242.     856,808,762,720,678,640,604,570,538,508,480,453,
  243.     428,404,381,360,339,320,302,285,269,254,240,226,
  244.     214,202,190,180,170,160,151,143,135,127,120,113,0,
  245.     850,802,757,715,674,637,601,567,535,505,477,450,
  246.     425,401,379,357,337,318,300,284,268,253,239,225,
  247.     213,201,189,179,169,159,150,142,134,126,119,113,0,
  248.     844,796,752,709,670,632,597,563,532,502,474,447,
  249.     422,398,376,355,335,316,298,282,266,251,237,224,
  250.     211,199,188,177,167,158,149,141,133,125,118,112,0,
  251.     838,791,746,704,665,628,592,559,528,498,470,444,
  252.     419,395,373,352,332,314,296,280,264,249,235,222,
  253.     209,198,187,176,166,157,148,140,132,125,118,111,0,
  254.     832,785,741,699,660,623,588,555,524,495,467,441,
  255.     416,392,370,350,330,312,294,278,262,247,233,220,
  256.     208,196,185,175,165,156,147,139,131,124,117,110,0,
  257.     826,779,736,694,655,619,584,551,520,491,463,437,
  258.     413,390,368,347,328,309,292,276,260,245,232,219,
  259.     206,195,184,174,164,155,146,138,130,123,116,109,0,
  260.     820,774,730,689,651,614,580,547,516,487,460,434,
  261.     410,387,365,345,325,307,290,274,258,244,230,217,
  262.     205,193,183,172,163,154,145,137,129,122,115,109,0,
  263.     814,768,725,684,646,610,575,543,513,484,457,431,
  264.     407,384,363,342,323,305,288,272,256,242,228,216,
  265.     204,192,181,171,161,152,144,136,128,121,114,108,0,
  266.     907,856,808,762,720,678,640,604,570,538,508,480,
  267.     453,428,404,381,360,339,320,302,285,269,254,240,
  268.     226,214,202,190,180,170,160,151,143,135,127,120,0,
  269.     900,850,802,757,715,675,636,601,567,535,505,477,
  270.     450,425,401,379,357,337,318,300,284,268,253,238,
  271.     225,212,200,189,179,169,159,150,142,134,126,119,0,
  272.     894,844,796,752,709,670,632,597,563,532,502,474,
  273.     447,422,398,376,355,335,316,298,282,266,251,237,
  274.     223,211,199,188,177,167,158,149,141,133,125,118,0,
  275.     887,838,791,746,704,665,628,592,559,528,498,470,
  276.     444,419,395,373,352,332,314,296,280,264,249,235,
  277.     222,209,198,187,176,166,157,148,140,132,125,118,0,
  278.     881,832,785,741,699,660,623,588,555,524,494,467,
  279.     441,416,392,370,350,330,312,294,278,262,247,233,
  280.     220,208,196,185,175,165,156,147,139,131,123,117,0,
  281.     875,826,779,736,694,655,619,584,551,520,491,463,
  282.     437,413,390,368,347,328,309,292,276,260,245,232,
  283.     219,206,195,184,174,164,155,146,138,130,123,116,0,
  284.     868,820,774,730,689,651,614,580,547,516,487,460,
  285.     434,410,387,365,345,325,307,290,274,258,244,230,
  286.     217,205,193,183,172,163,154,145,137,129,122,115,0,
  287.     862,814,768,725,684,646,610,575,543,513,484,457,
  288.     431,407,384,363,342,323,305,288,272,256,242,228,
  289.     216,203,192,181,171,161,152,144,136,128,121,114,0,
  290.  
  291.     /* Arpeggio on -1 finetuned samples can do an overflown read from
  292.     ** the period table. Here's the correct overflow values from the
  293.     ** "CursorPosTable" and "UnshiftedKeymap" table, which are located
  294.     ** right after the period table. These tables and their order didn't
  295.     ** seem to change in the different PT1.x/PT2.x versions (I checked
  296.     ** the source codes).
  297.     ** PS: This is not a guess, these values *are* correct!
  298.     */
  299.     774,1800,2314,3087,4113,4627,5400,6426,6940,7713,
  300.     8739,9253,24625,12851,13365
  301. };
  302.  
  303. #ifdef USE_BLEP
  304. /* Why this table is not represented as readable floating-point numbers:
  305. ** Accurate double representation in string format requires at least 14 digits and normalized
  306. ** (scientific) notation, notwithstanding compiler issues with precision or rounding error.
  307. ** Also, don't touch this table ever, just keep it exactly identical!
  308. */
  309. static const uint64_t minblepdata[] =
  310. {
  311.     0x3FF000320C7E95A6,0x3FF00049BE220FD5,0x3FF0001B92A41ACA,0x3FEFFF4425AA9724,
  312.     0x3FEFFDABDF6CF05C,0x3FEFFB5AF233EF1A,0x3FEFF837E2AE85F3,0x3FEFF4217B80E938,
  313.     0x3FEFEEECEB4E0444,0x3FEFE863A8358B5F,0x3FEFE04126292670,0x3FEFD63072A0D592,
  314.     0x3FEFC9C9CD36F56F,0x3FEFBA90594BD8C3,0x3FEFA7F008BA9F13,0x3FEF913BE2A0E0E2,
  315.     0x3FEF75ACCB01A327,0x3FEF5460F06A4E8F,0x3FEF2C5C0389BD3C,0x3FEEFC8859BF6BCB,
  316.     0x3FEEC3B916FD8D19,0x3FEE80AD74F0AD16,0x3FEE32153552E2C7,0x3FEDD69643CB9778,
  317.     0x3FED6CD380FFA864,0x3FECF374A4D2961A,0x3FEC692F19B34E54,0x3FEBCCCFA695DD5C,
  318.     0x3FEB1D44B168764A,0x3FEA59A8D8E4527F,0x3FE9814D9B10A9A3,0x3FE893C5B62135F2,
  319.     0x3FE790EEEBF9DABD,0x3FE678FACDEE27FF,0x3FE54C763699791A,0x3FE40C4F1B1EB7A3,
  320.     0x3FE2B9D863D4E0F3,0x3FE156CB86586B0B,0x3FDFCA8F5005B828,0x3FDCCF9C3F455DAC,
  321.     0x3FD9C2787F20D06E,0x3FD6A984CAD0F3E5,0x3FD38BB0C452732E,0x3FD0705EC7135366,
  322.     0x3FCABE86754E238F,0x3FC4C0801A6E9A04,0x3FBDECF490C5EA17,0x3FB2DFFACE9CE44B,
  323.     0x3FA0EFD4449F4620,0xBF72F4A65E22806D,0xBFA3F872D761F927,0xBFB1D89F0FD31F7C,
  324.     0xBFB8B1EA652EC270,0xBFBE79B82A37C92D,0xBFC1931B697E685E,0xBFC359383D4C8ADA,
  325.     0xBFC48F3BFF81B06B,0xBFC537BBA8D6B15C,0xBFC557CEF2168326,0xBFC4F6F781B3347A,
  326.     0xBFC41EF872F0E009,0xBFC2DB9F119D54D3,0xBFC13A7E196CB44F,0xBFBE953A67843504,
  327.     0xBFBA383D9C597E74,0xBFB57FBD67AD55D6,0xBFB08E18234E5CB3,0xBFA70B06D699FFD1,
  328.     0xBF9A1CFB65370184,0xBF7B2CEB901D2067,0x3F86D5DE2C267C78,0x3F9C1D9EF73F384D,
  329.     0x3FA579C530950503,0x3FABD1E5FFF9B1D0,0x3FB07DCDC3A4FB5B,0x3FB2724A856EEC1B,
  330.     0x3FB3C1F7199FC822,0x3FB46D0979F5043B,0x3FB47831387E0110,0x3FB3EC4A58A3D527,
  331.     0x3FB2D5F45F8889B3,0x3FB145113E25B749,0x3FAE9860D18779BC,0x3FA9FFD5F5AB96EA,
  332.     0x3FA4EC6C4F47777E,0x3F9F16C5B2604C3A,0x3F9413D801124DB7,0x3F824F668CBB5BDF,
  333.     0xBF55B3FA2EE30D66,0xBF86541863B38183,0xBF94031BBBD551DE,0xBF9BAFC27DC5E769,
  334.     0xBFA102B3683C57EC,0xBFA3731E608CC6E4,0xBFA520C9F5B5DEBD,0xBFA609DC89BE6ECE,
  335.     0xBFA632B83BC5F52F,0xBFA5A58885841AD4,0xBFA471A5D2FF02F3,0xBFA2AAD5CD0377C7,
  336.     0xBFA0686FFE4B9B05,0xBF9B88DE413ACB69,0xBF95B4EF6D93F1C5,0xBF8F1B72860B27FA,
  337.     0xBF8296A865CDF612,0xBF691BEEDABE928B,0x3F65C04E6AF9D4F1,0x3F8035D8FFCDB0F8,
  338.     0x3F89BED23C431BE3,0x3F90E737811A1D21,0x3F941C2040BD7CB1,0x3F967046EC629A09,
  339.     0x3F97DE27ECE9ED89,0x3F98684DE31E7040,0x3F9818C4B07718FA,0x3F97005261F91F60,
  340.     0x3F95357FDD157646,0x3F92D37C696C572A,0x3F8FF1CFF2BEECB5,0x3F898D20C7A72AC4,
  341.     0x3F82BC5B3B0AE2DF,0x3F7784A1B8E9E667,0x3F637BB14081726B,0xBF4B2DACA70C60A9,
  342.     0xBF6EFB00AD083727,0xBF7A313758DC6AE9,0xBF819D6A99164BE0,0xBF8533F57533403B,
  343.     0xBF87CD120DB5D340,0xBF89638549CD25DE,0xBF89FB8B8D37B1BB,0xBF89A21163F9204E,
  344.     0xBF886BA8931297D4,0xBF8673477783D71E,0xBF83D8E1CB165DB8,0xBF80BFEA7216142A,
  345.     0xBF7A9B9BC2E40EBF,0xBF7350E806435A7E,0xBF67D35D3734AB5E,0xBF52ADE8FEAB8DB9,
  346.     0x3F415669446478E4,0x3F60C56A092AFB48,0x3F6B9F4334A4561F,0x3F724FB908FD87AA,
  347.     0x3F75CC56DFE382EA,0x3F783A0C23969A7B,0x3F799833C40C3B82,0x3F79F02721981BF3,
  348.     0x3F7954212AB35261,0x3F77DDE0C5FC15C9,0x3F75AD1C98FE0777,0x3F72E5DACC0849F2,
  349.     0x3F6F5D7E69DFDE1B,0x3F685EC2CA09E1FD,0x3F611D750E54DF3A,0x3F53C6E392A46D17,
  350.     0x3F37A046885F3365,0xBF3BB034D2EE45C2,0xBF5254267B04B482,0xBF5C0516F9CECDC6,
  351.     0xBF61E5736853564D,0xBF64C464B9CC47AB,0xBF669C1AEF258F56,0xBF67739985DD0E60,
  352.     0xBF675AFD6446395B,0xBF666A0C909B4F78,0xBF64BE9879A7A07B,0xBF627AC74B119DBD,
  353.     0xBF5F86B04069DC9B,0xBF597BE8F754AF5E,0xBF531F3EAAE9A1B1,0xBF496D3DE6AD7EA3,
  354.     0xBF3A05FFDE4670CF,0xBF06DF95C93A85CA,0x3F31EE2B2C6547AC,0x3F41E694A378C129,
  355.     0x3F4930BF840E23C9,0x3F4EBB5D05A0D47D,0x3F51404DA0539855,0x3F524698F56B3F33,
  356.     0x3F527EF85309E28F,0x3F51FE70FE2513DE,0x3F50DF1642009B74,0x3F4E7CDA93517CAE,
  357.     0x3F4A77AE24F9A533,0x3F45EE226AA69E10,0x3F411DB747374F52,0x3F387F39D229D97F,
  358.     0x3F2E1B3D39AF5F8B,0x3F18F557BB082715,0xBEFAC04896E68DDB,0xBF20F5BC77DF558A,
  359.     0xBF2C1B6DF3EE94A4,0xBF3254602A816876,0xBF354E90F6EAC26B,0xBF3709F2E5AF1624,
  360.     0xBF379FCCB331CE8E,0xBF37327192ADDAD3,0xBF35EA998A894237,0xBF33F4C4977B3489,
  361.     0xBF317EC5F68E887B,0xBF2D6B1F793EB773,0xBF2786A226B076D9,0xBF219BE6CEC2CA36,
  362.     0xBF17D7F36D2A3A18,0xBF0AAEC5BBAB42AB,0xBEF01818DC224040,0x3EEF2F6E21093846,
  363.     0x3F049D6E0060B71F,0x3F0E598CCAFABEFD,0x3F128BC14BE97261,0x3F148703BC70EF6A,
  364.     0x3F1545E1579CAA25,0x3F14F7DDF5F8D766,0x3F13D10FF9A1BE0C,0x3F1206D5738ECE3A,
  365.     0x3F0F99F6BF17C5D4,0x3F0AA6D7EA524E96,0x3F0588DDF740E1F4,0x3F0086FB6FEA9839,
  366.     0x3EF7B28F6D6F5EED,0x3EEEA300DCBAF74A,0x3EE03F904789777C,0x3EC1BFEB320501ED,
  367.     0xBEC310D8E585A031,0xBED6F55ECA7E151F,0xBEDFDAA5DACDD0B7,0xBEE26944F3CF6E90,
  368.     0xBEE346894453BD1F,0xBEE2E099305CD5A8,0xBEE190385A7EA8B2,0xBEDF4D5FA2FB6BA2,
  369.     0xBEDAD4F371257BA0,0xBED62A9CDEB0AB32,0xBED1A6DF97B88316,0xBECB100096894E58,
  370.     0xBEC3E8A76257D275,0xBEBBF6C29A5150C9,0xBEB296292998088E,0xBEA70A10498F0E5E,
  371.     0xBE99E52D02F887A1,0xBE88C17F4066D432,0xBE702A716CFF56CA,0x3E409F820F781F78,
  372.     0x3E643EA99B770FE7,0x3E67DE40CDE0A550,0x3E64F4D534A2335C,0x3E5F194536BDDF7A,
  373.     0x3E5425CEBE1FA40A,0x3E46D7B7CC631E73,0x3E364746B6582E54,0x3E21FC07B13031DE,
  374.     0x3E064C3D91CF7665,0x3DE224F901A0AFC7,0x3DA97D57859C74A4,0x0000000000000000,
  375.  
  376.     // extra padding needed for interpolation
  377.     0x0000000000000000
  378. };
  379.  
  380. #define LERP(x, y, z) ((x) + ((y) - (x)) * (z))
  381. const double *get_minblep_table(void) { return (const double *)minblepdata; }
  382. #endif
  383.  
  384. #define SWAP16(x) ((uint16_t)(((x) << 8) | ((x) >> 8)))
  385. #define PTR2WORD(x) ((uint16_t *)(x))
  386. #define CLAMP(x, low, high) (((x) > (high)) ? (high) : (((x) < (low)) ? (low) : (x)))
  387. #define CLAMP16(i) if ((int16_t)i != i) i = 0x7FFF ^ (i >> 31);
  388.  
  389. static bool openMixer(uint32_t audioFreq);
  390. static void closeMixer(void);
  391.  
  392. static void paulaStartDMA(int32_t ch)
  393. {
  394.     const int8_t *data;
  395.     int32_t length;
  396.     paulaVoice_t *v = &paula[ch];
  397.  
  398.     data = v->newData;
  399.     if (data == NULL)
  400.         data = EmptySample;
  401.  
  402.     length = v->newLength;
  403.     if (length < 2)
  404.         length = 2; // for safety
  405.  
  406.     v->dPhase = 0.0;
  407.     v->pos = 0;
  408.     v->data = data;
  409.     v->length = length;
  410.     v->active = true;
  411. }
  412.  
  413. static void paulaSetPeriod(int32_t ch, uint16_t period)
  414. {
  415.     int32_t realPeriod;
  416.     paulaVoice_t *v = &paula[ch];
  417.  
  418.     if (period == 0)
  419.         realPeriod = 1+65535; // confirmed behavior on real Amiga
  420.     else if (period < 113)
  421.         realPeriod = 113; // close to what happens on real Amiga (and needed for BLEP synthesis)
  422.     else
  423.         realPeriod = period;
  424.  
  425.     // if the new period was the same as the previous period, use cached deltas
  426.     if (realPeriod != oldPeriod)
  427.     {
  428.         oldPeriod = realPeriod;
  429.  
  430.         // cache these
  431.         dOldVoiceDelta = dPeriodToDeltaDiv / realPeriod;
  432. #ifdef USE_BLEP
  433.         dOldVoiceDeltaMul = 1.0 / dOldVoiceDelta;
  434. #endif
  435.     }
  436.  
  437.     v->dDelta = dOldVoiceDelta;
  438.  
  439. #ifdef USE_BLEP
  440.     v->dDeltaMul = dOldVoiceDeltaMul;
  441.     if (v->dLastDelta == 0.0) v->dLastDelta = v->dDelta;
  442.     if (v->dLastDeltaMul == 0.0) v->dLastDeltaMul = v->dDeltaMul;
  443. #endif
  444. }
  445.  
  446. static void paulaSetVolume(int32_t ch, uint16_t vol)
  447. {
  448.     vol &= 127; // confirmed behavior on real Amiga
  449.  
  450.     if (vol > 64)
  451.         vol = 64; // confirmed behavior on real Amiga
  452.  
  453.     paula[ch].dVolume = vol * (1.0 / 64.0);
  454. }
  455.  
  456. static void paulaSetLength(int32_t ch, uint16_t len)
  457. {
  458.     paula[ch].newLength = len << 1; // our mixer works with bytes, not words
  459. }
  460.  
  461. static void paulaSetData(int32_t ch, const int8_t *src)
  462. {
  463.     if (src == NULL)
  464.         src = EmptySample;
  465.  
  466.     paula[ch].newData = src;
  467. }
  468.  
  469. #if defined(USE_HIGHPASS) || defined(USE_LOWPASS)
  470. static void calcRCFilterCoeffs(double dSr, double dHz, rcFilter_t *f)
  471. {
  472.     f->c = tan((M_PI * dHz) / dSr);
  473.     f->c2 = f->c * 2.0;
  474.     f->g = 1.0 / (1.0 + f->c);
  475.     f->cg = f->c * f->g;
  476. }
  477.  
  478. void clearRCFilterState(rcFilter_t *f)
  479. {
  480.     f->buffer[0] = 0.0; // left channel
  481.     f->buffer[1] = 0.0; // right channel
  482. }
  483.  
  484. // aciddose: input 0 is resistor side of capacitor (low-pass), input 1 is reference side (high-pass)
  485. static inline double getLowpassOutput(rcFilter_t *f, const double input_0, const double input_1, const double buffer)
  486. {
  487.     return buffer * f->g + input_0 * f->cg + input_1 * (1.0 - f->cg);
  488. }
  489.  
  490. static void inline RCLowPassFilter(rcFilter_t *f, const double *in, double *out)
  491. {
  492.     double output;
  493.  
  494.     // left channel RC low-pass
  495.     output = getLowpassOutput(f, in[0], 0.0, f->buffer[0]);
  496.     f->buffer[0] += (in[0] - output) * f->c2;
  497.     out[0] = output;
  498.  
  499.     // right channel RC low-pass
  500.     output = getLowpassOutput(f, in[1], 0.0, f->buffer[1]);
  501.     f->buffer[1] += (in[1] - output) * f->c2;
  502.     out[1] = output;
  503. }
  504.  
  505. void RCHighPassFilter(rcFilter_t *f, const double *in, double *out)
  506. {
  507.     double low[2];
  508.  
  509.     RCLowPassFilter(f, in, low);
  510.  
  511.     out[0] = in[0] - low[0]; // left channel high-pass
  512.     out[1] = in[1] - low[1]; // right channel high-pass
  513. }
  514. #endif
  515.  
  516. #ifdef LED_FILTER
  517. static void clearLEDFilterState(void)
  518. {
  519.     filterLED.buffer[0] = 0.0; // left channel
  520.     filterLED.buffer[1] = 0.0;
  521.     filterLED.buffer[2] = 0.0; // right channel
  522.     filterLED.buffer[3] = 0.0;
  523. }
  524.  
  525. /* Imperfect "LED" filter implementation. This may be further improved in the future.
  526. ** Based upon ideas posted by mystran @ the kvraudio.com forum.
  527. **
  528. ** This filter may not function correctly used outside the fixed-cutoff context here!
  529. */
  530.  
  531. static double sigmoid(double x, double coefficient)
  532. {
  533.     /* Coefficient from:
  534.     **   0.0 to  inf (linear)
  535.     **  -1.0 to -inf (linear)
  536.     */
  537.     return x / (x + coefficient) * (coefficient + 1.0);
  538. }
  539.  
  540. static void calcLEDFilterCoeffs(const double sr, const double hz, const double fb, ledFilter_t *filter)
  541. {
  542.     /* tan() may produce NaN or other bad results in some cases!
  543.     ** It appears to work correctly with these specific coefficients.
  544.     */
  545.     const double c = (hz < (sr / 2.0)) ? tan((M_PI * hz) / sr) : 1.0;
  546.     const double g = 1.0 / (1.0 + c);
  547.  
  548.     // dirty compensation
  549.     const double s = 0.5;
  550.     const double t = 0.5;
  551.     const double ic = c > t ? 1.0 / ((1.0 - s*t) + s*c) : 1.0;
  552.     const double cg = c * g;
  553.     const double fbg = 1.0 / (1.0 + fb * cg*cg);
  554.  
  555.     filter->c = c;
  556.     filter->ci = g;
  557.     filter->feedback = 2.0 * sigmoid(fb, 0.5);
  558.     filter->bg = fbg * filter->feedback * ic;
  559.     filter->cg = cg;
  560.     filter->c2 = c * 2.0;
  561. }
  562.  
  563. static inline void LEDFilter(ledFilter_t *f, const double *in, double *out)
  564. {
  565.     const double in_1 = DENORMAL_OFFSET;
  566.     const double in_2 = DENORMAL_OFFSET;
  567.  
  568.     const double c = f->c;
  569.     const double g = f->ci;
  570.     const double cg = f->cg;
  571.     const double bg = f->bg;
  572.     const double c2 = f->c2;
  573.  
  574.     double *v = f->buffer;
  575.  
  576.     // left channel
  577.     const double estimate_L = in_2 + g*(v[1] + c*(in_1 + g*(v[0] + c*in[0])));
  578.     const double y0_L = v[0]*g + in[0]*cg + in_1 + estimate_L * bg;
  579.     const double y1_L = v[1]*g + y0_L*cg + in_2;
  580.  
  581.     v[0] += c2 * (in[0] - y0_L);
  582.     v[1] += c2 * (y0_L - y1_L);
  583.     out[0] = y1_L;
  584.  
  585.     // right channel
  586.     const double estimate_R = in_2 + g*(v[3] + c*(in_1 + g*(v[2] + c*in[1])));
  587.     const double y0_R = v[2]*g + in[1]*cg + in_1 + estimate_R * bg;
  588.     const double y1_R = v[3]*g + y0_R*cg + in_2;
  589.  
  590.     v[2] += c2 * (in[1] - y0_R);
  591.     v[3] += c2 * (y0_R - y1_R);
  592.     out[1] = y1_R;
  593. }
  594. #endif
  595.  
  596. #ifdef USE_BLEP
  597. static inline void blepAdd(blep_t *b, double dOffset, double dAmplitude)
  598. {
  599.     double f = dOffset * BLEP_SP;
  600.  
  601.     int32_t i = (int32_t)f; // get integer part of f
  602.     const double *dBlepSrc = get_minblep_table() + i;
  603.     f -= i; // remove integer part from f
  604.  
  605.     i = b->index;
  606.     for (int32_t n = 0; n < BLEP_NS; n++)
  607.     {
  608.         b->dBuffer[i] += dAmplitude * LERP(dBlepSrc[0], dBlepSrc[1], f);
  609.         dBlepSrc += BLEP_SP;
  610.  
  611.         i = (i + 1) & BLEP_RNS;
  612.     }
  613.  
  614.     b->samplesLeft = BLEP_NS;
  615. }
  616.  
  617. /* 8bitbubsy: simplified, faster version of blepAdd for blep'ing voice volume.
  618. ** Result is identical! (confirmed with binary comparison)
  619. */
  620. void blepVolAdd(blep_t *b, double dAmplitude)
  621. {
  622.     const double *dBlepSrc = get_minblep_table();
  623.  
  624.     int32_t i = b->index;
  625.     for (int32_t n = 0; n < BLEP_NS; n++)
  626.     {
  627.         b->dBuffer[i] += dAmplitude * (*dBlepSrc);
  628.         dBlepSrc += BLEP_SP;
  629.  
  630.         i = (i + 1) & BLEP_RNS;
  631.     }
  632.  
  633.     b->samplesLeft = BLEP_NS;
  634. }
  635.  
  636. static inline double blepRun(blep_t *b, double dInput)
  637. {
  638.     double dBlepOutput = dInput + b->dBuffer[b->index];
  639.     b->dBuffer[b->index] = 0.0;
  640.  
  641.     b->index = (b->index + 1) & BLEP_RNS;
  642.  
  643.     b->samplesLeft--;
  644.     return dBlepOutput;
  645. }
  646. #endif
  647.  
  648. static void SetReplayerBPM(uint8_t bpm)
  649. {
  650.     if (bpm < 32)
  651.         return;
  652.  
  653.     samplesPerTick = bpmTab[bpm-32];
  654. }
  655.  
  656. static void UpdateFunk(ptChannel_t *ch)
  657. {
  658.     const int8_t funkspeed = ch->n_glissfunk >> 4;
  659.     if (funkspeed == 0)
  660.         return;
  661.  
  662.     ch->n_funkoffset += FunkTable[funkspeed];
  663.     if (ch->n_funkoffset >= 128)
  664.     {
  665.         ch->n_funkoffset = 0;
  666.  
  667.         if (ch->n_loopstart != NULL && ch->n_wavestart != NULL) // non-PT2 bug fix
  668.         {
  669.             if (++ch->n_wavestart >= ch->n_loopstart + (ch->n_replen << 1))
  670.                 ch->n_wavestart = ch->n_loopstart;
  671.  
  672.             *ch->n_wavestart = -1 - *ch->n_wavestart;
  673.         }
  674.     }
  675. }
  676.  
  677. static void SetGlissControl(ptChannel_t *ch)
  678. {
  679.     ch->n_glissfunk = (ch->n_glissfunk & 0xF0) | (ch->n_cmd & 0x0F);
  680. }
  681.  
  682. static void SetVibratoControl(ptChannel_t *ch)
  683. {
  684.     ch->n_wavecontrol = (ch->n_wavecontrol & 0xF0) | (ch->n_cmd & 0x0F);
  685. }
  686.  
  687. static void SetFineTune(ptChannel_t *ch)
  688. {
  689.     ch->n_finetune = ch->n_cmd & 0xF;
  690. }
  691.  
  692. static void JumpLoop(ptChannel_t *ch)
  693. {
  694.     if (Counter != 0)
  695.         return;
  696.  
  697.     if ((ch->n_cmd & 0xF) == 0)
  698.     {
  699.         ch->n_pattpos = (PatternPos >> 4) & 63;
  700.     }
  701.     else
  702.     {
  703.         if (ch->n_loopcount == 0)
  704.             ch->n_loopcount = ch->n_cmd & 0xF;
  705.         else if (--ch->n_loopcount == 0)
  706.             return;
  707.  
  708.         PBreakPosition = ch->n_pattpos;
  709.         PBreakFlag = true;
  710.     }
  711. }
  712.  
  713. static void SetTremoloControl(ptChannel_t *ch)
  714. {
  715.     ch->n_wavecontrol = ((ch->n_cmd & 0xF) << 4) | (ch->n_wavecontrol & 0xF);
  716. }
  717.  
  718. static void KarplusStrong(ptChannel_t *ch)
  719. {
  720. #ifdef ENABLE_E8_EFFECT
  721.     int8_t *smpPtr;
  722.     uint16_t len;
  723.  
  724.     smpPtr = ch->n_loopstart;
  725.     if (smpPtr != NULL) // SAFETY BUG FIX
  726.     {
  727.         len = ((ch->n_replen * 2) & 0xFFFF) - 1;
  728.         while (len--)
  729.             *smpPtr++ = (int8_t)((smpPtr[1] + smpPtr[0]) >> 1);
  730.  
  731.         *smpPtr = (int8_t)((ch->n_loopstart[0] + smpPtr[0]) >> 1);
  732.     }
  733. #else
  734.     (void)(ch);
  735. #endif
  736. }
  737.  
  738. static void DoRetrg(ptChannel_t *ch)
  739. {
  740.     paulaSetData(ch->n_chanindex, ch->n_start); // n_start is increased on 9xx
  741.     paulaSetLength(ch->n_chanindex, ch->n_length);
  742.     paulaSetPeriod(ch->n_chanindex, ch->n_period);
  743.     paulaStartDMA(ch->n_chanindex);
  744.  
  745.     // these take effect after the current cycle is done
  746.     paulaSetData(ch->n_chanindex, ch->n_loopstart);
  747.     paulaSetLength(ch->n_chanindex, ch->n_replen);
  748. }
  749.  
  750. static void RetrigNote(ptChannel_t *ch)
  751. {
  752.     if ((ch->n_cmd & 0xF) > 0)
  753.     {
  754.         if (Counter == 0 && (ch->n_note & 0xFFF) > 0)
  755.             return;
  756.  
  757.         if (Counter % (ch->n_cmd & 0xF) == 0)
  758.             DoRetrg(ch);
  759.     }
  760. }
  761.  
  762. static void VolumeSlide(ptChannel_t *ch)
  763. {
  764.     uint8_t cmd = ch->n_cmd & 0xFF;
  765.  
  766.     if ((cmd & 0xF0) == 0)
  767.     {
  768.         ch->n_volume -= cmd & 0xF;
  769.         if (ch->n_volume < 0)
  770.             ch->n_volume = 0;
  771.     }
  772.     else
  773.     {
  774.         ch->n_volume += cmd >> 4;
  775.         if (ch->n_volume > 64)
  776.             ch->n_volume = 64;
  777.     }
  778. }
  779.  
  780. static void VolumeFineUp(ptChannel_t *ch)
  781. {
  782.     if (Counter == 0)
  783.     {
  784.         ch->n_volume += ch->n_cmd & 0xF;
  785.         if (ch->n_volume > 64)
  786.             ch->n_volume = 64;
  787.     }
  788. }
  789.  
  790. static void VolumeFineDown(ptChannel_t *ch)
  791. {
  792.     if (Counter == 0)
  793.     {
  794.         ch->n_volume -= ch->n_cmd & 0xF;
  795.         if (ch->n_volume < 0)
  796.             ch->n_volume = 0;
  797.     }
  798. }
  799.  
  800. static void NoteCut(ptChannel_t *ch)
  801. {
  802.     if (Counter == (ch->n_cmd & 0xF))
  803.         ch->n_volume = 0;
  804. }
  805.  
  806. static void NoteDelay(ptChannel_t *ch)
  807. {
  808.     if (Counter == (ch->n_cmd & 0xF) && (ch->n_note & 0xFFF) > 0)
  809.         DoRetrg(ch);
  810. }
  811.  
  812. static void PatternDelay(ptChannel_t *ch)
  813. {
  814.     if (Counter == 0 && PattDelTime2 == 0)
  815.         PattDelTime = (ch->n_cmd & 0xF) + 1;
  816. }
  817.  
  818. static void FunkIt(ptChannel_t *ch)
  819. {
  820.     if (Counter == 0)
  821.     {
  822.         ch->n_glissfunk = ((ch->n_cmd & 0xF) << 4) | (ch->n_glissfunk & 0xF);
  823.         if ((ch->n_glissfunk & 0xF0) > 0)
  824.             UpdateFunk(ch);
  825.     }
  826. }
  827.  
  828. static void PositionJump(ptChannel_t *ch)
  829. {
  830.     SongPosition = (ch->n_cmd & 0xFF) - 1; // 0xFF (B00) jumps to pat 0
  831.     PBreakPosition = 0;
  832.     PosJumpAssert = true;
  833. }
  834.  
  835. static void VolumeChange(ptChannel_t *ch)
  836. {
  837.     ch->n_volume = ch->n_cmd & 0xFF;
  838.     if ((uint8_t)ch->n_volume > 64)
  839.         ch->n_volume = 64;
  840. }
  841.  
  842. static void PatternBreak(ptChannel_t *ch)
  843. {
  844.     PBreakPosition = (((ch->n_cmd & 0xF0) >> 4) * 10) + (ch->n_cmd & 0x0F);
  845.     if ((uint8_t)PBreakPosition > 63)
  846.         PBreakPosition = 0;
  847.  
  848.     PosJumpAssert = true;
  849. }
  850.  
  851. static void SetSpeed(ptChannel_t *ch)
  852. {
  853.     if ((ch->n_cmd & 0xFF) > 0)
  854.     {
  855.         Counter = 0;
  856.  
  857.         if (TempoMode == VBLANK_TEMPO_MODE || (ch->n_cmd & 0xFF) < 32)
  858.             CurrSpeed = ch->n_cmd & 0xFF;
  859.         else
  860.             SetBPMFlag = ch->n_cmd & 0xFF; // CIA doesn't refresh its registers until the next interrupt, so change it later
  861.     }
  862. }
  863.  
  864. static void Arpeggio(ptChannel_t *ch)
  865. {
  866.     uint8_t arpTick, arpNote;
  867.     const int16_t *periods;
  868.  
  869.     arpTick = ArpTickTable[Counter]; // 0, 1, 2
  870.     if (arpTick == 1)
  871.     {
  872.         arpNote = (uint8_t)(ch->n_cmd >> 4);
  873.     }
  874.     else if (arpTick == 2)
  875.     {
  876.         arpNote = ch->n_cmd & 0xF;
  877.     }
  878.     else // arpTick 0
  879.     {
  880.         paulaSetPeriod(ch->n_chanindex, ch->n_period);
  881.         return;
  882.     }
  883.  
  884.     /* 8bitbubsy: If the finetune is -1, this can overflow up to
  885.     ** 15 words outside of the table. The table is padded with
  886.     ** the correct overflow values to allow this to safely happen
  887.     ** and sound correct at the same time.
  888.     */
  889.     periods = &PeriodTable[ch->n_finetune * 37];
  890.     for (int32_t baseNote = 0; baseNote < 37; baseNote++)
  891.     {
  892.         if (ch->n_period >= periods[baseNote])
  893.         {
  894.             paulaSetPeriod(ch->n_chanindex, periods[baseNote+arpNote]);
  895.             break;
  896.         }
  897.     }
  898. }
  899.  
  900. static void PortaUp(ptChannel_t *ch)
  901. {
  902.     ch->n_period -= (ch->n_cmd & 0xFF) & LowMask;
  903.     LowMask = 0xFF;
  904.  
  905.     if ((ch->n_period & 0xFFF) < 113)
  906.         ch->n_period = (ch->n_period & 0xF000) | 113;
  907.  
  908.     paulaSetPeriod(ch->n_chanindex, ch->n_period & 0xFFF);
  909. }
  910.  
  911. static void PortaDown(ptChannel_t *ch)
  912. {
  913.     ch->n_period += (ch->n_cmd & 0xFF) & LowMask;
  914.     LowMask = 0xFF;
  915.  
  916.     if ((ch->n_period & 0xFFF) > 856)
  917.         ch->n_period = (ch->n_period & 0xF000) | 856;
  918.  
  919.     paulaSetPeriod(ch->n_chanindex, ch->n_period & 0xFFF);
  920. }
  921.  
  922. static void FilterOnOff(ptChannel_t *ch)
  923. {
  924. #ifdef LED_FILTER
  925.     LEDFilterOn = !(ch->n_cmd & 1);
  926. #else
  927.     (void)ch;
  928. #endif
  929. }
  930.  
  931. static void FinePortaUp(ptChannel_t *ch)
  932. {
  933.     if (Counter == 0)
  934.     {
  935.         LowMask = 0xF;
  936.         PortaUp(ch);
  937.     }
  938. }
  939.  
  940. static void FinePortaDown(ptChannel_t *ch)
  941. {
  942.     if (Counter == 0)
  943.     {
  944.         LowMask = 0xF;
  945.         PortaDown(ch);
  946.     }
  947. }
  948.  
  949. static void SetTonePorta(ptChannel_t *ch)
  950. {
  951.     uint8_t i;
  952.     const int16_t *portaPointer;
  953.     uint16_t note;
  954.  
  955.     note = ch->n_note & 0xFFF;
  956.     portaPointer = &PeriodTable[ch->n_finetune * 37];
  957.  
  958.     i = 0;
  959.     while (true)
  960.     {
  961.         // portaPointer[36] = 0, so i=36 is safe
  962.         if (note >= portaPointer[i])
  963.             break;
  964.  
  965.         if (++i >= 37)
  966.         {
  967.             i = 35;
  968.             break;
  969.         }
  970.     }
  971.  
  972.     if ((ch->n_finetune & 8) && i > 0)
  973.         i--;
  974.  
  975.     ch->n_wantedperiod  = portaPointer[i];
  976.     ch->n_toneportdirec = 0;
  977.  
  978.          if (ch->n_period == ch->n_wantedperiod) ch->n_wantedperiod = 0;
  979.     else if (ch->n_period > ch->n_wantedperiod) ch->n_toneportdirec = 1;
  980. }
  981.  
  982. static void TonePortNoChange(ptChannel_t *ch)
  983. {
  984.     uint8_t i;
  985.     const int16_t *portaPointer;
  986.  
  987.     if (ch->n_wantedperiod <= 0)
  988.         return;
  989.  
  990.     if (ch->n_toneportdirec > 0)
  991.     {
  992.         ch->n_period -= ch->n_toneportspeed;
  993.         if (ch->n_period <= ch->n_wantedperiod)
  994.         {
  995.             ch->n_period = ch->n_wantedperiod;
  996.             ch->n_wantedperiod = 0;
  997.         }
  998.     }
  999.     else
  1000.     {
  1001.         ch->n_period += ch->n_toneportspeed;
  1002.         if (ch->n_period >= ch->n_wantedperiod)
  1003.         {
  1004.             ch->n_period = ch->n_wantedperiod;
  1005.             ch->n_wantedperiod = 0;
  1006.         }
  1007.     }
  1008.  
  1009.     if ((ch->n_glissfunk & 0xF) == 0)
  1010.     {
  1011.         paulaSetPeriod(ch->n_chanindex, ch->n_period);
  1012.     }
  1013.     else
  1014.     {
  1015.         portaPointer = &PeriodTable[ch->n_finetune * 37];
  1016.  
  1017.         i = 0;
  1018.         while (true)
  1019.         {
  1020.             // portaPointer[36] = 0, so i=36 is safe
  1021.             if (ch->n_period >= portaPointer[i])
  1022.                 break;
  1023.  
  1024.             if (++i >= 37)
  1025.             {
  1026.                 i = 35;
  1027.                 break;
  1028.             }
  1029.         }
  1030.  
  1031.         paulaSetPeriod(ch->n_chanindex, portaPointer[i]);
  1032.     }
  1033. }
  1034.  
  1035. static void TonePortamento(ptChannel_t *ch)
  1036. {
  1037.     if ((ch->n_cmd & 0xFF) > 0)
  1038.     {
  1039.         ch->n_toneportspeed = ch->n_cmd & 0xFF;
  1040.         ch->n_cmd &= 0xFF00;
  1041.     }
  1042.  
  1043.     TonePortNoChange(ch);
  1044. }
  1045.  
  1046. static void Vibrato2(ptChannel_t *ch)
  1047. {
  1048.     uint16_t vibratoData;
  1049.  
  1050.     const uint8_t vibratoPos = (ch->n_vibratopos >> 2) & 0x1F;
  1051.     const uint8_t vibratoType = ch->n_wavecontrol & 3;
  1052.  
  1053.     if (vibratoType == 0) // Sine
  1054.     {
  1055.         vibratoData = VibratoTable[vibratoPos];
  1056.     }
  1057.     else
  1058.     {
  1059.         if (vibratoType == 1) // Ramp
  1060.         {
  1061.             if (ch->n_vibratopos < 128)
  1062.                 vibratoData = vibratoPos << 3;
  1063.             else
  1064.                 vibratoData = 255 - (vibratoPos << 3);
  1065.         }
  1066.         else // Square
  1067.         {
  1068.             vibratoData = 255;
  1069.         }
  1070.     }
  1071.  
  1072.     vibratoData = (vibratoData * (ch->n_vibratocmd & 0xF)) >> 7;
  1073.  
  1074.     if (ch->n_vibratopos < 128)
  1075.         vibratoData = ch->n_period + vibratoData;
  1076.     else
  1077.         vibratoData = ch->n_period - vibratoData;
  1078.  
  1079.     paulaSetPeriod(ch->n_chanindex, vibratoData);
  1080.  
  1081.     ch->n_vibratopos += (ch->n_vibratocmd >> 2) & 0x3C;
  1082. }
  1083.  
  1084. static void Vibrato(ptChannel_t *ch)
  1085. {
  1086.     if ((ch->n_cmd & 0x0F) > 0)
  1087.         ch->n_vibratocmd = (ch->n_vibratocmd & 0xF0) | (ch->n_cmd & 0x0F);
  1088.  
  1089.     if ((ch->n_cmd & 0xF0) > 0)
  1090.         ch->n_vibratocmd = (ch->n_cmd & 0xF0) | (ch->n_vibratocmd & 0x0F);
  1091.  
  1092.     Vibrato2(ch);
  1093. }
  1094.  
  1095. static void TonePlusVolSlide(ptChannel_t *ch)
  1096. {
  1097.     TonePortNoChange(ch);
  1098.     VolumeSlide(ch);
  1099. }
  1100.  
  1101. static void VibratoPlusVolSlide(ptChannel_t *ch)
  1102. {
  1103.     Vibrato2(ch);
  1104.     VolumeSlide(ch);
  1105. }
  1106.  
  1107. static void Tremolo(ptChannel_t *ch)
  1108. {
  1109.     int16_t tremoloData;
  1110.  
  1111.     if ((ch->n_cmd & 0x0F) > 0)
  1112.         ch->n_tremolocmd = (ch->n_tremolocmd & 0xF0) | (ch->n_cmd & 0x0F);
  1113.  
  1114.     if ((ch->n_cmd & 0xF0) > 0)
  1115.         ch->n_tremolocmd = (ch->n_cmd & 0xF0) | (ch->n_tremolocmd & 0x0F);
  1116.  
  1117.     const uint8_t tremoloPos = (ch->n_tremolopos >> 2) & 0x1F;
  1118.     const uint8_t tremoloType = (ch->n_wavecontrol >> 4) & 3;
  1119.  
  1120.     if (tremoloType == 0) // Sine
  1121.     {
  1122.         tremoloData = VibratoTable[tremoloPos];
  1123.     }
  1124.     else
  1125.     {
  1126.         if (tremoloType == 1) // Ramp
  1127.         {
  1128.             if (ch->n_vibratopos < 128) // PT bug, should've been n_tremolopos
  1129.                 tremoloData = tremoloPos << 3;
  1130.             else
  1131.                 tremoloData = 255 - (tremoloPos << 3);
  1132.         }
  1133.         else // Square
  1134.         {
  1135.             tremoloData = 255;
  1136.         }
  1137.     }
  1138.  
  1139.     tremoloData = ((uint16_t)tremoloData * (ch->n_tremolocmd & 0xF)) >> 6;
  1140.  
  1141.     if (ch->n_tremolopos < 128)
  1142.     {
  1143.         tremoloData = ch->n_volume + tremoloData;
  1144.         if (tremoloData > 64)
  1145.             tremoloData = 64;
  1146.     }
  1147.     else
  1148.     {
  1149.         tremoloData = ch->n_volume - tremoloData;
  1150.         if (tremoloData < 0)
  1151.             tremoloData = 0;
  1152.     }
  1153.  
  1154.     paulaSetVolume(ch->n_chanindex, tremoloData);
  1155.  
  1156.     ch->n_tremolopos += (ch->n_tremolocmd >> 2) & 0x3C;
  1157. }
  1158.  
  1159. static void SampleOffset(ptChannel_t *ch)
  1160. {
  1161.     if ((ch->n_cmd & 0xFF) > 0)
  1162.         ch->n_sampleoffset = ch->n_cmd & 0xFF;
  1163.  
  1164.     uint16_t newOffset = ch->n_sampleoffset << 7;
  1165.  
  1166.     if ((int16_t)newOffset < ch->n_length)
  1167.     {
  1168.         ch->n_length -= newOffset;
  1169.         ch->n_start += newOffset << 1;
  1170.     }
  1171.     else
  1172.     {
  1173.         ch->n_length = 1;
  1174.     }
  1175. }
  1176.  
  1177. static void E_Commands(ptChannel_t *ch)
  1178. {
  1179.     switch ((ch->n_cmd & 0xF0) >> 4)
  1180.     {
  1181.         case 0x0: FilterOnOff(ch);       break;
  1182.         case 0x1: FinePortaUp(ch);       break;
  1183.         case 0x2: FinePortaDown(ch);     break;
  1184.         case 0x3: SetGlissControl(ch);   break;
  1185.         case 0x4: SetVibratoControl(ch); break;
  1186.         case 0x5: SetFineTune(ch);       break;
  1187.         case 0x6: JumpLoop(ch);          break;
  1188.         case 0x7: SetTremoloControl(ch); break;
  1189.         case 0x8: KarplusStrong(ch);     break;
  1190.         case 0x9: RetrigNote(ch);        break;
  1191.         case 0xA: VolumeFineUp(ch);      break;
  1192.         case 0xB: VolumeFineDown(ch);    break;
  1193.         case 0xC: NoteCut(ch);           break;
  1194.         case 0xD: NoteDelay(ch);         break;
  1195.         case 0xE: PatternDelay(ch);      break;
  1196.         case 0xF: FunkIt(ch);            break;
  1197.         default: break;
  1198.     }
  1199. }
  1200.  
  1201. static void CheckMoreEffects(ptChannel_t *ch)
  1202. {
  1203.     switch ((ch->n_cmd & 0xF00) >> 8)
  1204.     {
  1205.         case 0x9: SampleOffset(ch); break;
  1206.         case 0xB: PositionJump(ch); break;
  1207.         case 0xD: PatternBreak(ch); break;
  1208.         case 0xE: E_Commands(ch);   break;
  1209.         case 0xF: SetSpeed(ch);     break;
  1210.         case 0xC: VolumeChange(ch); break;
  1211.  
  1212.         default: paulaSetPeriod(ch->n_chanindex, ch->n_period); break;
  1213.     }
  1214. }
  1215.  
  1216. static void CheckEffects(ptChannel_t *ch)
  1217. {
  1218.     uint8_t effect;
  1219.  
  1220.     UpdateFunk(ch);
  1221.  
  1222.     effect = (ch->n_cmd & 0xF00) >> 8;
  1223.     if ((ch->n_cmd & 0xFFF) > 0)
  1224.     {
  1225.         switch (effect)
  1226.         {
  1227.             case 0x0: Arpeggio(ch);            break;
  1228.             case 0x1: PortaUp(ch);             break;
  1229.             case 0x2: PortaDown(ch);           break;
  1230.             case 0x3: TonePortamento(ch);      break;
  1231.             case 0x4: Vibrato(ch);             break;
  1232.             case 0x5: TonePlusVolSlide(ch);    break;
  1233.             case 0x6: VibratoPlusVolSlide(ch); break;
  1234.             case 0xE: E_Commands(ch);          break;
  1235.             case 0x7:
  1236.                 paulaSetPeriod(ch->n_chanindex, ch->n_period);
  1237.                 Tremolo(ch);
  1238.             break;
  1239.             case 0xA:
  1240.                 paulaSetPeriod(ch->n_chanindex, ch->n_period);
  1241.                 VolumeSlide(ch);
  1242.             break;
  1243.  
  1244.             default: paulaSetPeriod(ch->n_chanindex, ch->n_period); break;
  1245.         }
  1246.     }
  1247.  
  1248.     if (effect != 0x7)
  1249.         paulaSetVolume(ch->n_chanindex, ch->n_volume);
  1250. }
  1251.  
  1252. static void SetPeriod(ptChannel_t *ch)
  1253. {
  1254.     int32_t i;
  1255.  
  1256.     uint16_t note = ch->n_note & 0xFFF;
  1257.     for (i = 0; i < 37; i++)
  1258.     {
  1259.         // PeriodTable[36] = 0, so i=36 is safe
  1260.         if (note >= PeriodTable[i])
  1261.             break;
  1262.     }
  1263.  
  1264.     // yes it's safe if i=37 because of zero-padding
  1265.     ch->n_period = PeriodTable[(ch->n_finetune * 37) + i];
  1266.  
  1267.     if ((ch->n_cmd & 0xFF0) != 0xED0) // no note delay
  1268.     {
  1269.         if ((ch->n_wavecontrol & 0x04) == 0) ch->n_vibratopos = 0;
  1270.         if ((ch->n_wavecontrol & 0x40) == 0) ch->n_tremolopos = 0;
  1271.  
  1272.         paulaSetLength(ch->n_chanindex, ch->n_length);
  1273.         paulaSetData(ch->n_chanindex, ch->n_start);
  1274.  
  1275.         if (ch->n_start == NULL)
  1276.         {
  1277.             ch->n_loopstart = NULL;
  1278.             paulaSetLength(ch->n_chanindex, 1);
  1279.             ch->n_replen = 1;
  1280.         }
  1281.  
  1282.         paulaSetPeriod(ch->n_chanindex, ch->n_period);
  1283.         paulaStartDMA(ch->n_chanindex);
  1284.     }
  1285.  
  1286.     CheckMoreEffects(ch);
  1287. }
  1288.  
  1289. static void PlayVoice(ptChannel_t *ch)
  1290. {
  1291.     uint8_t *dataPtr, sample, cmd;
  1292.     uint16_t sampleOffset, repeat;
  1293.  
  1294.     if (ch->n_note == 0 && ch->n_cmd == 0)
  1295.         paulaSetPeriod(ch->n_chanindex, ch->n_period);
  1296.  
  1297.     dataPtr = &SongDataPtr[PattPosOff];
  1298.  
  1299.     ch->n_note = (dataPtr[0] << 8) | dataPtr[1];
  1300.     ch->n_cmd  = (dataPtr[2] << 8) | dataPtr[3];
  1301.  
  1302.     sample = (dataPtr[0] & 0xF0) | (dataPtr[2] >> 4);
  1303.     if (sample >= 1 && sample <= 31) // SAFETY BUG FIX: don't handle sample-numbers >31
  1304.     {
  1305.         sample--;
  1306.         sampleOffset = 42 + (30 * sample);
  1307.  
  1308.         ch->n_start = SampleStarts[sample];
  1309.         ch->n_finetune = SongDataPtr[sampleOffset + 2] & 0xF;
  1310.         ch->n_volume = SongDataPtr[sampleOffset + 3];
  1311.         ch->n_length = *PTR2WORD(&SongDataPtr[sampleOffset + 0]);
  1312.         ch->n_replen = *PTR2WORD(&SongDataPtr[sampleOffset + 6]);
  1313.  
  1314.         repeat = *PTR2WORD(&SongDataPtr[sampleOffset + 4]);
  1315.         if (repeat > 0)
  1316.         {
  1317.             ch->n_loopstart = ch->n_start + (repeat << 1);
  1318.             ch->n_wavestart = ch->n_loopstart;
  1319.             ch->n_length = repeat + ch->n_replen;
  1320.         }
  1321.         else
  1322.         {
  1323.             ch->n_loopstart = ch->n_start;
  1324.             ch->n_wavestart = ch->n_start;
  1325.         }
  1326.  
  1327.         // non-PT2 quirk
  1328.         if (ch->n_length == 0)
  1329.             ch->n_loopstart = ch->n_wavestart = EmptySample;
  1330.     }
  1331.  
  1332.     if ((ch->n_note & 0xFFF) > 0)
  1333.     {
  1334.         if ((ch->n_cmd & 0xFF0) == 0xE50) // set finetune
  1335.         {
  1336.             SetFineTune(ch);
  1337.             SetPeriod(ch);
  1338.         }
  1339.         else
  1340.         {
  1341.             cmd = (ch->n_cmd & 0xF00) >> 8;
  1342.             if (cmd == 3 || cmd == 5)
  1343.             {
  1344.                 SetTonePorta(ch);
  1345.                 CheckMoreEffects(ch);
  1346.             }
  1347.             else if (cmd == 9)
  1348.             {
  1349.                 CheckMoreEffects(ch);
  1350.                 SetPeriod(ch);
  1351.             }
  1352.             else
  1353.             {
  1354.                 SetPeriod(ch);
  1355.             }
  1356.         }
  1357.     }
  1358.     else
  1359.     {
  1360.         CheckMoreEffects(ch);
  1361.     }
  1362.  
  1363.     PattPosOff += 4;
  1364. }
  1365.  
  1366. static void NextPosition(void)
  1367. {
  1368.     PatternPos = (uint8_t)PBreakPosition << 4;
  1369.     PBreakPosition = 0;
  1370.     PosJumpAssert = false;
  1371.  
  1372.     SongPosition = (SongPosition + 1) & 0x7F;
  1373.     if (SongPosition >= SongDataPtr[950])
  1374.         SongPosition = 0;
  1375. }
  1376.  
  1377. static void tickReplayer(void)
  1378. {
  1379.     int32_t i;
  1380.  
  1381.     if (!SongPlaying)
  1382.         return;
  1383.  
  1384.     // PT quirk: CIA refreshes its timer values on the next interrupt, so do the real tempo change here
  1385.     if (SetBPMFlag != 0)
  1386.     {
  1387.         SetReplayerBPM(SetBPMFlag);
  1388.         SetBPMFlag = 0;
  1389.     }
  1390.  
  1391.     Counter++;
  1392.     if (Counter >= CurrSpeed)
  1393.     {
  1394.         Counter = 0;
  1395.  
  1396.         if (PattDelTime2 == 0)
  1397.         {
  1398.             PattPosOff = (1084 + (SongDataPtr[952 + SongPosition] * 1024)) + PatternPos;
  1399.  
  1400.             for (i = 0; i < AMIGA_VOICES; i++)
  1401.             {
  1402.                 PlayVoice(&ChanTemp[i]);
  1403.                 paulaSetVolume(i, ChanTemp[i].n_volume);
  1404.  
  1405.                 // these take effect after the current cycle is done
  1406.                 paulaSetData(i, ChanTemp[i].n_loopstart);
  1407.                 paulaSetLength(i, ChanTemp[i].n_replen);
  1408.             }
  1409.         }
  1410.         else
  1411.         {
  1412.             for (i = 0; i < AMIGA_VOICES; i++)
  1413.                 CheckEffects(&ChanTemp[i]);
  1414.         }
  1415.  
  1416.         PatternPos += 16;
  1417.  
  1418.         if (PattDelTime > 0)
  1419.         {
  1420.             PattDelTime2 = PattDelTime;
  1421.             PattDelTime = 0;
  1422.         }
  1423.  
  1424.         if (PattDelTime2 > 0)
  1425.         {
  1426.             if (--PattDelTime2 > 0)
  1427.                 PatternPos -= 16;
  1428.         }
  1429.  
  1430.         if (PBreakFlag)
  1431.         {
  1432.             PBreakFlag = false;
  1433.  
  1434.             PatternPos = PBreakPosition * 16;
  1435.             PBreakPosition = 0;
  1436.         }
  1437.  
  1438.         if (PatternPos >= 1024 || PosJumpAssert)
  1439.             NextPosition();
  1440.     }
  1441.     else
  1442.     {
  1443.         for (i = 0; i < AMIGA_VOICES; i++)
  1444.             CheckEffects(&ChanTemp[i]);
  1445.  
  1446.         if (PosJumpAssert)
  1447.             NextPosition();
  1448.     }
  1449. }
  1450.  
  1451. static int8_t moduleInit(const uint8_t *moduleData, uint32_t dataLength)
  1452. {
  1453.     int8_t pattNum, *songSampleData;
  1454.     uint8_t i;
  1455.     uint16_t *p;
  1456.     int32_t loopOverflowVal, totalSampleSize, sampleDataOffset;
  1457.     ptChannel_t *ch;
  1458.  
  1459.     if (SampleData != NULL)
  1460.     {
  1461.         free(SampleData);
  1462.         SampleData = NULL;
  1463.     }
  1464.  
  1465.     for (i = 0; i < AMIGA_VOICES; i++)
  1466.     {
  1467.         ch = &ChanTemp[i];
  1468.  
  1469.         ch->n_chanindex = i;
  1470.         ch->n_start = NULL;
  1471.         ch->n_wavestart = NULL;
  1472.         ch->n_loopstart = NULL;
  1473.     }
  1474.  
  1475.     SongDataPtr = (uint8_t *)malloc(dataLength);
  1476.     if (SongDataPtr == NULL)
  1477.         return false;
  1478.  
  1479.     memcpy(SongDataPtr, moduleData, dataLength);
  1480.  
  1481.     memcpy(songName, SongDataPtr, 20);
  1482.     songName[20] = '\0';
  1483.  
  1484.     pattNum = 0;
  1485.     for (i = 0; i < 128; i++)
  1486.     {
  1487.         if (SongDataPtr[952+i] > pattNum)
  1488.             pattNum = SongDataPtr[952+i];
  1489.     }
  1490.     pattNum++;
  1491.  
  1492.     // first count total sample size to allocate
  1493.     totalSampleSize = 0;
  1494.     for (i = 0; i < 31; i++)
  1495.     {
  1496.         p = PTR2WORD(&SongDataPtr[42 + (i * 30)]);
  1497.         totalSampleSize += (SWAP16(p[0]) * 2);
  1498.     }
  1499.  
  1500.     SampleData = (int8_t *)malloc(totalSampleSize);
  1501.     if (SampleData == NULL)
  1502.         return false;
  1503.  
  1504.     // setup and load samples
  1505.     songSampleData = (int8_t *)&SongDataPtr[1084 + (pattNum * 1024)];
  1506.  
  1507.     sampleDataOffset = 0;
  1508.     for (i = 0; i < 31; i++)
  1509.     {
  1510.         p = PTR2WORD(&SongDataPtr[42 + (i * 30)]);
  1511.  
  1512.         // swap bytes in words (Amiga word -> Intel word)
  1513.         p[0] = SWAP16(p[0]); // n_length
  1514.         p[2] = SWAP16(p[2]); // n_repeat
  1515.         p[3] = SWAP16(p[3]); // n_replen
  1516.  
  1517.         // set up sample pointer and load sample
  1518.         if (p[0] == 0)
  1519.         {
  1520.             SampleStarts[i] = EmptySample;
  1521.         }
  1522.         else
  1523.         {
  1524.             SampleStarts[i] = &SampleData[sampleDataOffset];
  1525.             memcpy(SampleStarts[i], songSampleData, p[0] * 2);
  1526.  
  1527.             sampleDataOffset += p[0] * 2;
  1528.             songSampleData += p[0] * 2;
  1529.         }
  1530.  
  1531.         if (p[3] == 0)
  1532.             p[3] = 1; // fix illegal loop length (f.ex. from "Fasttracker II" .MODs)
  1533.  
  1534.         // adjust sample length if loop was overflowing
  1535.         if (p[3] > 1 && p[2]+p[3] > p[0])
  1536.         {
  1537.             loopOverflowVal = (p[2] + p[3]) - p[0];
  1538.             if ((p[0] + loopOverflowVal) <= MAX_SAMPLE_LEN/2)
  1539.             {
  1540.                 p[0] += (uint16_t)loopOverflowVal;
  1541.             }
  1542.             else
  1543.             {
  1544.                 p[2] = 0;
  1545.                 p[3] = 2;
  1546.             }
  1547.         }
  1548.  
  1549.         if (p[0] >= 1 && p[2]+p[3] <= 1)
  1550.         {
  1551.             // if no loop, zero first two samples of data to prevent "beep"
  1552.             SampleStarts[i][0] = 0;
  1553.             SampleStarts[i][1] = 0;
  1554.         }
  1555.     }
  1556.  
  1557.     return true;
  1558. }
  1559.  
  1560. // MIXER RELATED CODE
  1561.  
  1562. // these are used to create equal powered stereo separation
  1563. static double sinApx(double fX)
  1564. {
  1565.     fX = fX * (2.0 - fX);
  1566.     return fX * 1.09742972 + fX * fX * 0.31678383;
  1567. }
  1568.  
  1569. static double cosApx(double fX)
  1570. {
  1571.     fX = (1.0 - fX) * (1.0 + fX);
  1572.     return fX * 1.09742972 + fX * fX * 0.31678383;
  1573. }
  1574. // -------------------------------------------------
  1575.  
  1576. static void calculatePans(int8_t stereoSeparation)
  1577. {
  1578.     uint8_t scaledPanPos;
  1579.     double p;
  1580.  
  1581.     if (stereoSeparation > 100)
  1582.         stereoSeparation = 100;
  1583.  
  1584.     scaledPanPos = (stereoSeparation * 128) / 100;
  1585.  
  1586.     p = (128 - scaledPanPos) * (1.0 / 256.0);
  1587.     paula[0].dPanL = cosApx(p);
  1588.     paula[0].dPanR = sinApx(p);
  1589.     paula[3].dPanL = cosApx(p);
  1590.     paula[3].dPanR = sinApx(p);
  1591.  
  1592.     p = (128 + scaledPanPos) * (1.0 / 256.0);
  1593.     paula[1].dPanL = cosApx(p);
  1594.     paula[1].dPanR = sinApx(p);
  1595.     paula[2].dPanL = cosApx(p);
  1596.     paula[2].dPanR = sinApx(p);
  1597. }
  1598.  
  1599. static void resetAudioDithering(void)
  1600. {
  1601.     randSeed = INITIAL_DITHER_SEED;
  1602.     dPrngStateL = 0.0;
  1603.     dPrngStateR = 0.0;
  1604. }
  1605.  
  1606. static inline int32_t random32(void)
  1607. {
  1608.     // LCG random 32-bit generator (quite good and fast)
  1609.     randSeed = randSeed * 134775813 + 1;
  1610.     return randSeed;
  1611. }
  1612.  
  1613. #define POST_MIX_STAGE_1 \
  1614.     dOut[0] = dMixBufferL[i]; \
  1615.     dOut[1] = dMixBufferR[i]; \
  1616.  
  1617. #define POST_MIX_STAGE_2 \
  1618.     /* normalize and flip phase (A500/A1200 has an inverted audio signal) */ \
  1619.     dOut[0] *= (-INT16_MAX / (double)AMIGA_VOICES); \
  1620.     dOut[1] *= (-INT16_MAX / (double)AMIGA_VOICES); \
  1621.     \
  1622.     /* left channel - 1-bit triangular dithering (high-pass filtered) */ \
  1623.     dPrng = random32() * (0.5 / INT32_MAX); /* -0.5..0.5 */ \
  1624.     dOut[0] = (dOut[0] + dPrng) - dPrngStateL; \
  1625.     dPrngStateL = dPrng; \
  1626.     smp32 = (int32_t)dOut[0]; \
  1627.     smp32 = (smp32 * masterVol) >> 8; \
  1628.     CLAMP16(smp32); \
  1629.     *stream++ = (int16_t)smp32; \
  1630.     \
  1631.     /* right channel */ \
  1632.     dPrng = random32() * (0.5 / INT32_MAX); \
  1633.     dOut[1] = (dOut[1] + dPrng) - dPrngStateR; \
  1634.     dPrngStateR = dPrng; \
  1635.     smp32 = (int32_t)dOut[1]; \
  1636.     smp32 = (smp32 * masterVol) >> 8; \
  1637.     CLAMP16(smp32); \
  1638.     *stream++ = (int16_t)smp32; \
  1639.  
  1640. static void mixAudio(int16_t *stream, int32_t sampleBlockLength)
  1641. {
  1642.     int32_t i, j, smp32;
  1643.     double dPrng, dSmp, dVol, dOut[2];
  1644.     paulaVoice_t *v;
  1645. #ifdef USE_BLEP
  1646.     blep_t *bSmp, *bVol;
  1647. #endif
  1648.  
  1649.     memset(dMixBufferL, 0, sampleBlockLength * sizeof (double));
  1650.     memset(dMixBufferR, 0, sampleBlockLength * sizeof (double));
  1651.  
  1652.     if (musicPaused)
  1653.     {
  1654.         memset(stream, 0, sampleBlockLength * (sizeof (int16_t) * 2));
  1655.         return;
  1656.     }
  1657.  
  1658.     v = paula;
  1659.     for (i = 0; i < AMIGA_VOICES; i++, v++)
  1660.     {
  1661.         if (!v->active)
  1662.             continue;
  1663.  
  1664. #ifdef USE_BLEP
  1665.         bSmp = &blep[i];
  1666.         bVol = &blepVol[i];
  1667. #endif
  1668.         for (j = 0; j < sampleBlockLength; j++)
  1669.         {
  1670.             dSmp = v->data[v->pos] * (1.0 / 128.0);
  1671.             dVol = v->dVolume;
  1672.  
  1673. #ifdef USE_BLEP
  1674.             if (dSmp != bSmp->dLastValue)
  1675.             {
  1676.                 if (v->dLastDelta > v->dLastPhase)
  1677.                 {
  1678.                     // div->mul trick: v->dLastDeltaMul is 1.0 / v->dLastDelta
  1679.                     blepAdd(bSmp, v->dLastPhase * v->dLastDeltaMul, bSmp->dLastValue - dSmp);
  1680.                 }
  1681.  
  1682.                 bSmp->dLastValue = dSmp;
  1683.             }
  1684.  
  1685.             if (dVol != bVol->dLastValue)
  1686.             {
  1687.                 blepVolAdd(bVol, bVol->dLastValue - dVol);
  1688.                 bVol->dLastValue = dVol;
  1689.             }
  1690.  
  1691.             if (bSmp->samplesLeft > 0) dSmp = blepRun(bSmp, dSmp);
  1692.             if (bVol->samplesLeft > 0) dVol = blepRun(bVol, dVol);
  1693. #endif
  1694.             dSmp *= dVol;
  1695.  
  1696.             dMixBufferL[j] += dSmp * v->dPanL;
  1697.             dMixBufferR[j] += dSmp * v->dPanR;
  1698.  
  1699.             v->dPhase += v->dDelta;
  1700.             if (v->dPhase >= 1.0)
  1701.             {
  1702.                 v->dPhase -= 1.0;
  1703. #ifdef USE_BLEP
  1704.                 v->dLastPhase = v->dPhase;
  1705.                 v->dLastDelta = v->dDelta;
  1706.                 v->dLastDeltaMul = v->dDeltaMul;
  1707. #endif
  1708.                 if (++v->pos >= v->length)
  1709.                 {
  1710.                     v->pos = 0;
  1711.  
  1712.                     // re-fetch Paula register values now
  1713.                     v->length = v->newLength;
  1714.                     v->data = v->newData;
  1715.                 }
  1716.             }
  1717.         }
  1718.     }
  1719.  
  1720. #ifdef LED_FILTER
  1721.     if (LEDFilterOn)
  1722.     {
  1723.         for (i = 0; i < sampleBlockLength; i++)
  1724.         {
  1725.             POST_MIX_STAGE_1
  1726.  
  1727. #ifdef USE_LOWPASS
  1728.             RCLowPassFilter(&filterLo, dOut, dOut);
  1729. #endif
  1730.  
  1731. #ifdef LED_FILTER
  1732.             LEDFilter(&filterLED, dOut, dOut);
  1733. #endif
  1734.  
  1735. #ifdef USE_HIGHPASS
  1736.             RCHighPassFilter(&filterHi, dOut, dOut);
  1737. #endif
  1738.  
  1739.             POST_MIX_STAGE_2
  1740.         }
  1741.     }
  1742.     else
  1743. #endif
  1744.     {
  1745.         for (i = 0; i < sampleBlockLength; i++)
  1746.         {
  1747.             POST_MIX_STAGE_1
  1748.  
  1749. #ifdef USE_LOWPASS
  1750.             RCLowPassFilter(&filterLo, dOut, dOut);
  1751. #endif
  1752.  
  1753. #ifdef USE_HIGHPASS
  1754.             RCHighPassFilter(&filterHi, dOut, dOut);
  1755. #endif
  1756.  
  1757.             POST_MIX_STAGE_2
  1758.         }
  1759.     }
  1760. }
  1761.  
  1762. void pt2play_PauseSong(bool flag)
  1763. {
  1764.     musicPaused = flag;
  1765. }
  1766.  
  1767. void pt2play_TogglePause(void)
  1768. {
  1769.     musicPaused ^= 1;
  1770. }
  1771.  
  1772. void pt2play_Close(void)
  1773. {
  1774.     closeMixer();
  1775.  
  1776.     if (SampleData != NULL)
  1777.     {
  1778.         free(SampleData);
  1779.         SampleData = NULL;
  1780.     }
  1781.  
  1782.     if (dMixBufferL != NULL)
  1783.     {
  1784.         free(dMixBufferL);
  1785.         dMixBufferL = NULL;
  1786.     }
  1787.  
  1788.     if (dMixBufferR != NULL)
  1789.     {
  1790.         free(dMixBufferR);
  1791.         dMixBufferR = NULL;
  1792.     }
  1793.  
  1794.     if (SongDataPtr != NULL)
  1795.     {
  1796.         free(SongDataPtr);
  1797.         SongDataPtr = NULL;
  1798.     }
  1799. }
  1800.  
  1801. bool pt2play_PlaySong(const uint8_t *moduleData, uint32_t dataLength, int8_t tempoMode, uint32_t audioFreq)
  1802. {
  1803.     if (audioFreq == 0)
  1804.         audioFreq = 44100;
  1805.  
  1806.     musicPaused = true;
  1807.  
  1808.     pt2play_Close();
  1809.     memset(songName, 0, sizeof (songName));
  1810.  
  1811.     oldPeriod = -1;
  1812.     sampleCounter = 0;
  1813.     SongPlaying = false;
  1814.  
  1815.     dMixBufferL = (double *)malloc(MIX_BUF_SAMPLES * sizeof (double));
  1816.     dMixBufferR = (double *)malloc(MIX_BUF_SAMPLES * sizeof (double));
  1817.  
  1818.     if (dMixBufferL == NULL || dMixBufferR == NULL)
  1819.     {
  1820.         pt2play_Close();
  1821.         return false;
  1822.     }
  1823.  
  1824.     // rates below 32kHz will mess up the BLEP synthesis
  1825.     audioFreq = CLAMP(audioFreq, 32000, 96000);
  1826.  
  1827.     audioRate = audioFreq;
  1828.     dPeriodToDeltaDiv = (double)PAULA_PAL_CLK / audioRate;
  1829.     soundBufferSize = MIX_BUF_SAMPLES;
  1830.  
  1831. #if defined(USE_HIGHPASS) || defined(USE_LOWPASS)
  1832.     double R, C, fc;
  1833. #endif
  1834.  
  1835. #ifdef USE_LOWPASS
  1836.     // A500 one-pole 6db/oct static RC low-pass filter:
  1837.     R = 360.0; // R321 (360 ohm resistor)
  1838.     C = 1e-7;  // C321 (0.1uF capacitor)
  1839.     fc = 1.0 / (2.0 * M_PI * R * C); // ~4420.97Hz
  1840.     calcRCFilterCoeffs(audioRate, fc, &filterLo);
  1841. #endif
  1842.  
  1843. #ifdef LED_FILTER
  1844.     double R1, R2, C1, C2, fb;
  1845.  
  1846.     // A500/A1200 Sallen-Key filter ("LED"):
  1847.     R1 = 10000.0; // R322 (10K ohm resistor)
  1848.     R2 = 10000.0; // R323 (10K ohm resistor)
  1849.     C1 = 6.8e-9;  // C322 (6800pF capacitor)
  1850.     C2 = 3.9e-9;  // C323 (3900pF capacitor)
  1851.     fc = 1.0 / (2.0 * M_PI * sqrt(R1 * R2 * C1 * C2)); // ~3090.53Hz
  1852.     fb = 0.125; // Fb = 0.125 : Q ~= 1/sqrt(2) (Butterworth)
  1853.     calcLEDFilterCoeffs(audioRate, fc, fb, &filterLED);
  1854. #endif
  1855.  
  1856. #ifdef USE_HIGHPASS
  1857.     // A500/A1200 one-pole 6db/oct static RC high-pass filter:
  1858.     R = 1000.0 + 390.0; // R324 (1K ohm resistor) + R325 (390 ohm resistor)
  1859.     C = 2.2e-5;         // C334 (22uF capacitor) (+ C324 (0.33uF capacitor) if A500)
  1860.     fc = 1.0 / (2.0 * M_PI * R * C); // ~5.20Hz
  1861.     calcRCFilterCoeffs(audioRate, fc, &filterHi);
  1862. #endif
  1863.  
  1864.     if (!moduleInit(moduleData, dataLength))
  1865.     {
  1866.         pt2play_Close();
  1867.         return false;
  1868.     }
  1869.  
  1870.     memset(paula, 0, sizeof (paula));
  1871.     calculatePans(stereoSep);
  1872.  
  1873. #ifdef USE_BLEP
  1874.     memset(blep, 0, sizeof (blep));
  1875.     memset(blepVol, 0, sizeof (blepVol));
  1876. #endif
  1877.  
  1878. #ifdef USE_LOWPASS
  1879.     clearRCFilterState(&filterLo);
  1880. #endif
  1881.  
  1882. #ifdef LED_FILTER
  1883.     clearLEDFilterState();
  1884. #endif
  1885.  
  1886. #ifdef USE_HIGHPASS
  1887.     clearRCFilterState(&filterHi);
  1888. #endif
  1889.  
  1890.     resetAudioDithering();
  1891.  
  1892.     CurrSpeed = 6;
  1893.     Counter = 0;
  1894.     SongPosition = 0;
  1895.     PatternPos = 0;
  1896.     PattDelTime = 0;
  1897.     PattDelTime2 = 0;
  1898.     PBreakPosition = 0;
  1899.     PosJumpAssert = false;
  1900.     PBreakFlag = false;
  1901.     LowMask = 0xFF;
  1902.     TempoMode = tempoMode ? VBLANK_TEMPO_MODE : CIA_TEMPO_MODE;
  1903.     SongPlaying = true;
  1904.     musicPaused = false;
  1905.  
  1906. #ifdef LED_FILTER
  1907.     LEDFilterOn = false;
  1908. #endif
  1909.  
  1910.     if (!openMixer(audioRate))
  1911.     {
  1912.         pt2play_Close();
  1913.         return false;
  1914.     }
  1915.  
  1916.     SetReplayerBPM(125);
  1917.     musicPaused = false;
  1918.     return true;
  1919. }
  1920.  
  1921. void pt2play_SetStereoSep(uint8_t percentage)
  1922. {
  1923.     stereoSep = percentage;
  1924.     if (stereoSep > 100)
  1925.         stereoSep = 100;
  1926.  
  1927.     calculatePans(stereoSep);
  1928. }
  1929.  
  1930. void pt2play_SetMasterVol(uint16_t vol)
  1931. {
  1932.     masterVol = CLAMP(vol, 0, 256);
  1933. }
  1934.  
  1935. uint16_t pt2play_GetMasterVol(void)
  1936. {
  1937.     return (uint16_t)masterVol;
  1938. }
  1939.  
  1940. char *pt2play_GetSongName(void)
  1941. {
  1942.     return songName;
  1943. }
  1944.  
  1945. uint32_t pt2play_GetMixerTicks(void)
  1946. {
  1947.     if (audioRate < 1000)
  1948.         return 0;
  1949.  
  1950.     return sampleCounter / (audioRate / 1000);
  1951. }
  1952.  
  1953. static void pt2play_FillAudioBuffer(int16_t *buffer, int32_t samples)
  1954. {
  1955.     int32_t a, b;
  1956.  
  1957.     a = samples;
  1958.     while (a > 0)
  1959.     {
  1960.         if (samplesPerTickLeft == 0)
  1961.         {
  1962.             if (!musicPaused)
  1963.                 tickReplayer();
  1964.  
  1965.             samplesPerTickLeft = samplesPerTick;
  1966.         }
  1967.  
  1968.         b = a;
  1969.         if (b > samplesPerTickLeft)
  1970.             b = samplesPerTickLeft;
  1971.  
  1972.         mixAudio(buffer, b);
  1973.         buffer += (uint32_t)b << 1;
  1974.  
  1975.         a -= b;
  1976.         samplesPerTickLeft -= b;
  1977.     }
  1978.  
  1979.     sampleCounter += samples;
  1980. }
  1981.  
  1982. // the following must be changed if you want to use another audio API than WinMM
  1983.  
  1984. #ifndef WIN32_LEAN_AND_MEAN
  1985. #define WIN32_LEAN_AND_MEAN
  1986. #endif
  1987.  
  1988. #include <windows.h>
  1989. #include <mmsystem.h>
  1990.  
  1991. #define MIX_BUF_NUM 2
  1992.  
  1993. static volatile BOOL audioRunningFlag;
  1994. static uint8_t currBuffer;
  1995. static int16_t *mixBuffer[MIX_BUF_NUM];
  1996. static HANDLE hThread, hAudioSem;
  1997. static WAVEHDR waveBlocks[MIX_BUF_NUM];
  1998. static HWAVEOUT hWave;
  1999.  
  2000. static DWORD WINAPI mixThread(LPVOID lpParam)
  2001. {
  2002.     WAVEHDR *waveBlock;
  2003.  
  2004.     (void)lpParam;
  2005.  
  2006.     SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  2007.  
  2008.     while (audioRunningFlag)
  2009.     {
  2010.         waveBlock = &waveBlocks[currBuffer];
  2011.         pt2play_FillAudioBuffer((int16_t *)waveBlock->lpData, MIX_BUF_SAMPLES);
  2012.         waveOutWrite(hWave, waveBlock, sizeof (WAVEHDR));
  2013.         currBuffer = (currBuffer + 1) % MIX_BUF_NUM;
  2014.  
  2015.         // wait for buffer fill request
  2016.         WaitForSingleObject(hAudioSem, INFINITE);
  2017.     }
  2018.  
  2019.     return 0;
  2020. }
  2021.  
  2022. static void CALLBACK waveProc(HWAVEOUT hWaveOut, UINT uMsg, DWORD_PTR dwInstance, DWORD_PTR dwParam1, DWORD_PTR dwParam2)
  2023. {
  2024.     (void)hWaveOut;
  2025.     (void)uMsg;
  2026.     (void)dwInstance;
  2027.     (void)dwParam1;
  2028.     (void)dwParam2;
  2029.  
  2030.     if (uMsg == WOM_DONE)
  2031.         ReleaseSemaphore(hAudioSem, 1, NULL);
  2032. }
  2033.  
  2034. static void closeMixer(void)
  2035. {
  2036.     int32_t i;
  2037.  
  2038.     audioRunningFlag = false; // make thread end when it's done
  2039.  
  2040.     if (hAudioSem != NULL)
  2041.         ReleaseSemaphore(hAudioSem, 1, NULL);
  2042.  
  2043.     if (hThread != NULL)
  2044.     {
  2045.         WaitForSingleObject(hThread, INFINITE);
  2046.         CloseHandle(hThread);
  2047.         hThread = NULL;
  2048.     }
  2049.  
  2050.     if (hAudioSem != NULL)
  2051.     {
  2052.         CloseHandle(hAudioSem);
  2053.         hAudioSem = NULL;
  2054.     }
  2055.  
  2056.     if (hWave != NULL)
  2057.     {
  2058.         waveOutReset(hWave);
  2059.  
  2060.         for (i = 0; i < MIX_BUF_NUM; i++)
  2061.         {
  2062.             if (waveBlocks[i].dwUser != 0xFFFF)
  2063.                 waveOutUnprepareHeader(hWave, &waveBlocks[i], sizeof (WAVEHDR));
  2064.         }
  2065.  
  2066.         waveOutClose(hWave);
  2067.         hWave = NULL;
  2068.     }
  2069.  
  2070.     for (i = 0; i < MIX_BUF_NUM; i++)
  2071.     {
  2072.         if (mixBuffer[i] != NULL)
  2073.         {
  2074.             free(mixBuffer[i]);
  2075.             mixBuffer[i] = NULL;
  2076.         }
  2077.     }
  2078. }
  2079.  
  2080. static uint16_t bpm2SmpsPerTick(uint32_t bpm, uint32_t audioFreq)
  2081. {
  2082.     uint32_t ciaVal;
  2083.     double dFreqMul;
  2084.  
  2085.     if (bpm == 0)
  2086.         return 0;
  2087.  
  2088.     ciaVal = (uint32_t)(1773447 / bpm); // yes, PT truncates here
  2089.     dFreqMul = ciaVal * (1.0 / CIA_PAL_CLK);
  2090.  
  2091.     return (uint16_t)((audioFreq * dFreqMul) + 0.5);
  2092. }
  2093.  
  2094. static bool openMixer(uint32_t audioFreq)
  2095. {
  2096.     int32_t i;
  2097.     DWORD threadID;
  2098.     WAVEFORMATEX wfx;
  2099.  
  2100.     // don't unprepare headers on error
  2101.     for (i = 0; i < MIX_BUF_NUM; i++)
  2102.         waveBlocks[i].dwUser = 0xFFFF;
  2103.  
  2104.     closeMixer();
  2105.  
  2106.     ZeroMemory(&wfx, sizeof (wfx));
  2107.     wfx.nSamplesPerSec = audioFreq;
  2108.     wfx.wBitsPerSample = 16;
  2109.     wfx.nChannels = 2;
  2110.     wfx.wFormatTag = WAVE_FORMAT_PCM;
  2111.     wfx.nBlockAlign = wfx.nChannels * (wfx.wBitsPerSample / 8);
  2112.     wfx.nAvgBytesPerSec = wfx.nSamplesPerSec * wfx.nBlockAlign;
  2113.  
  2114.     samplesPerTickLeft = 0;
  2115.     currBuffer = 0;
  2116.  
  2117.     if (waveOutOpen(&hWave, WAVE_MAPPER, &wfx, (DWORD_PTR)&waveProc, 0, CALLBACK_FUNCTION) != MMSYSERR_NOERROR)
  2118.         goto omError;
  2119.  
  2120.     // create semaphore for buffer fill requests
  2121.     hAudioSem = CreateSemaphore(NULL, MIX_BUF_NUM - 1, MIX_BUF_NUM, NULL);
  2122.     if (hAudioSem == NULL)
  2123.         goto omError;
  2124.  
  2125.     // allocate WinMM mix buffers
  2126.     for (i = 0; i < MIX_BUF_NUM; i++)
  2127.     {
  2128.         mixBuffer[i] = (int16_t *)calloc(MIX_BUF_SAMPLES, wfx.nBlockAlign);
  2129.         if (mixBuffer[i] == NULL)
  2130.             goto omError;
  2131.     }
  2132.  
  2133.     // initialize WinMM mix headers
  2134.     memset(waveBlocks, 0, sizeof (waveBlocks));
  2135.     for (i = 0; i < MIX_BUF_NUM; i++)
  2136.     {
  2137.         waveBlocks[i].lpData = (LPSTR)mixBuffer[i];
  2138.         waveBlocks[i].dwBufferLength = MIX_BUF_SAMPLES * wfx.nBlockAlign;
  2139.         waveBlocks[i].dwFlags = WHDR_DONE;
  2140.  
  2141.         if (waveOutPrepareHeader(hWave, &waveBlocks[i], sizeof (WAVEHDR)) != MMSYSERR_NOERROR)
  2142.             goto omError;
  2143.     }
  2144.  
  2145.     // create main mixer thread
  2146.     audioRunningFlag = true;
  2147.     hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)mixThread, NULL, 0, &threadID);
  2148.     if (hThread == NULL)
  2149.         goto omError;
  2150.  
  2151.     for (i = 32; i <= 255; i++)
  2152.         bpmTab[i-32] = bpm2SmpsPerTick(i, audioFreq);
  2153.  
  2154.     return TRUE;
  2155.  
  2156. omError:
  2157.     closeMixer();
  2158.     return FALSE;
  2159. }
  2160. // ---------------------------------------------------------------------------
  2161.  
  2162. // END OF FILE
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top