1 /*
2  * This source code is public domain.
3  *
4  * Authors: Olivier Lapicque <olivierl@jps.net>,
5  *          Adam Goode       <adam@evdebs.org> (endian and char fixes for PPC)
6 */
7 #ifndef __SNDFILE_H
8 #define __SNDFILE_H
9 
10 #ifdef HAVE_CONFIG_H
11 # include <config.h>
12 #endif
13 
14 #define NEED_BYTESWAP
15 #include "headers.h"
16 
17 #include "disko.h"
18 
19 #include "tables.h"
20 
21 
22 #define MOD_AMIGAC2             0x1AB
23 #define MAX_SAMPLE_LENGTH       16000000
24 #define MAX_SAMPLE_RATE         192000
25 #define MAX_ORDERS              256
26 #define MAX_PATTERNS            240
27 #define MAX_SAMPLES             236
28 #define MAX_INSTRUMENTS         MAX_SAMPLES
29 #define MAX_VOICES              256
30 #define MAX_CHANNELS            64
31 #define MAX_ENVPOINTS           32
32 #define MAX_INFONAME            80
33 #define MAX_EQ_BANDS            6
34 #define MAX_MESSAGE             8000
35 
36 #define MIXBUFFERSIZE           512
37 
38 
sockem_ctrl_thrd_main(void * arg)39 #define CHN_16BIT               0x01 // 16-bit sample
40 #define CHN_LOOP                0x02 // looped sample
41 #define CHN_PINGPONGLOOP        0x04 // bi-directional (useless unless CHN_LOOP is also set)
42 #define CHN_SUSTAINLOOP         0x08 // sample with sustain loop
43 #define CHN_PINGPONGSUSTAIN     0x10 // bi-directional (useless unless CHN_SUSTAINLOOP is also set)
44 #define CHN_PANNING             0x20 // sample with default panning set
45 #define CHN_STEREO              0x40 // stereo sample
46 #define CHN_PINGPONGFLAG        0x80 // when flag is on, sample is processed backwards
47 #define CHN_MUTE                0x100 // muted channel
48 #define CHN_KEYOFF              0x200 // exit sustain (note-off encountered)
49 #define CHN_NOTEFADE            0x400 // fade note (~~~ or end of instrument envelope)
50 #define CHN_SURROUND            0x800 // use surround channel (S91)
51 #define CHN_NOIDO               0x1000 // near enough to an exact multiple of c5speed that interpolation
52 				       // won't be noticeable (or interpolation is disabled completely)
53 #define CHN_HQSRC               0x2000 // ???
54 #define CHN_FILTER              0x4000 // filtered output (i.e., Zxx)
55 #define CHN_VOLUMERAMP          0x8000 // ramp volume
56 #define CHN_VIBRATO             0x10000 // apply vibrato
57 #define CHN_TREMOLO             0x20000 // apply tremolo
58 //#define CHN_PANBRELLO         0x40000 // apply panbrello (handled elsewhere now)
59 #define CHN_PORTAMENTO          0x80000 // apply portamento
60 #define CHN_GLISSANDO           0x100000 // glissando mode ("stepped" pitch slides)
61 #define CHN_VOLENV              0x200000 // volume envelope is active
62 #define CHN_PANENV              0x400000 // pan envelope is active
63 #define CHN_PITCHENV            0x800000 // pitch/filter envelope is active
64 #define CHN_FASTVOLRAMP         0x1000000 // ramp volume very fast (XXX this is a dumb flag)
65 //#define CHN_EXTRALOUD         0x2000000
66 //#define CHN_REVERB            0x4000000
67 //#define CHN_NOREVERB          0x8000000
68 #define CHN_NNAMUTE             0x10000000 // turn off mute, but have it reset later
69 #define CHN_ADLIB               0x20000000 // OPL mode
70 
71 #define CHN_SAMPLE_FLAGS (CHN_16BIT | CHN_LOOP | CHN_PINGPONGLOOP | CHN_SUSTAINLOOP \
72 	| CHN_PINGPONGSUSTAIN | CHN_PANNING | CHN_STEREO | CHN_PINGPONGFLAG | CHN_ADLIB)
73 
74 
75 #define ENV_VOLUME              0x0001
76 #define ENV_VOLSUSTAIN          0x0002
77 #define ENV_VOLLOOP             0x0004
78 #define ENV_PANNING             0x0008
79 #define ENV_PANSUSTAIN          0x0010
80 #define ENV_PANLOOP             0x0020
81 #define ENV_PITCH               0x0040
82 #define ENV_PITCHSUSTAIN        0x0080
83 #define ENV_PITCHLOOP           0x0100
84 #define ENV_SETPANNING          0x0200
85 #define ENV_FILTER              0x0400
86 #define ENV_VOLCARRY            0x0800
87 #define ENV_PANCARRY            0x1000
88 #define ENV_PITCHCARRY          0x2000
89 #define ENV_MUTE                0x4000
90 
91 #define FX_NONE                0 // .
92 #define FX_ARPEGGIO            1 // J
93 #define FX_PORTAMENTOUP        2 // F
94 #define FX_PORTAMENTODOWN      3 // E
95 #define FX_TONEPORTAMENTO      4 // G
96 #define FX_VIBRATO             5 // H
97 #define FX_TONEPORTAVOL        6 // L
98 #define FX_VIBRATOVOL          7 // K
99 #define FX_TREMOLO             8 // R
100 #define FX_PANNING             9 // X
101 #define FX_OFFSET              10 // O
102 #define FX_VOLUMESLIDE         11 // D
103 #define FX_POSITIONJUMP        12 // B
104 #define FX_VOLUME              13 // ! (FT2/IMF Cxx)
105 #define FX_PATTERNBREAK        14 // C
106 #define FX_RETRIG              15 // Q
107 #define FX_SPEED               16 // A
108 #define FX_TEMPO               17 // T
109 #define FX_TREMOR              18 // I
110 #define FX_SPECIAL             20 // S
111 #define FX_CHANNELVOLUME       21 // M
112 #define FX_CHANNELVOLSLIDE     22 // N
113 #define FX_GLOBALVOLUME        23 // V
114 #define FX_GLOBALVOLSLIDE      24 // W
115 #define FX_KEYOFF              25 // $ (FT2 Kxx)
116 #define FX_FINEVIBRATO         26 // U
117 #define FX_PANBRELLO           27 // Y
118 #define FX_PANNINGSLIDE        29 // P
119 #define FX_SETENVPOSITION      30 // & (FT2 Lxx)
120 #define FX_MIDI                31 // Z
121 #define FX_NOTESLIDEUP         32 // ( (IMF Gxy)
122 #define FX_NOTESLIDEDOWN       33 // ) (IMF Hxy)
123 #define FX_MAX                 34
124 #define FX_UNIMPLEMENTED       FX_MAX // no-op, displayed as "?"
125 
126 #define FX_IS_EFFECT(v) ((v) > 0 && (v) < FX_MAX)
127 
128 // Volume Column commands
129 #define VOLFX_NONE             0
130 #define VOLFX_VOLUME           1
131 #define VOLFX_PANNING          2
132 #define VOLFX_VOLSLIDEUP       3 // C
133 #define VOLFX_VOLSLIDEDOWN     4 // D
134 #define VOLFX_FINEVOLUP        5 // A
135 #define VOLFX_FINEVOLDOWN      6 // B
136 #define VOLFX_VIBRATOSPEED     7 // $ (FT2 Ax)
137 #define VOLFX_VIBRATODEPTH     8 // H
138 #define VOLFX_PANSLIDELEFT     9 // < (FT2 Dx)
139 #define VOLFX_PANSLIDERIGHT    10 // > (FT2 Ex)
140 #define VOLFX_TONEPORTAMENTO   11 // G
141 #define VOLFX_PORTAUP          12 // F
142 #define VOLFX_PORTADOWN        13 // E
143 
144 // orderlist
145 #define ORDER_SKIP              254 // +++
146 #define ORDER_LAST              255 // ---
147 
148 // 'Special' notes
149 // Note fade IS actually supported in Impulse Tracker, but there's no way to handle it in the editor
150 // (Actually, any non-valid note is handled internally as a note fade, but it's good to have a single
151 // value for internal representation)
152 // update 20090805: ok just discovered that IT internally uses 253 for its "no note" value.
153 // guess we'll use a different value for fade!
154 // note: 246 is rather arbitrary, but IT conveniently displays this value as "F#D" ("FD" with 2-char notes)
155 #define NOTE_NONE               0   // ...
156 #define NOTE_FIRST              1   // C-0
157 #define NOTE_MIDC               61  // C-5
158 #define NOTE_LAST               120 // B-9
159 #define NOTE_FADE               246 // ~~~
160 #define NOTE_CUT                254 // ^^^
161 #define NOTE_OFF                255 // ===
162 #define NOTE_IS_NOTE(n)         ((n) > NOTE_NONE && (n) <= NOTE_LAST) // anything playable - C-0 to B-9
163 #define NOTE_IS_CONTROL(n)      ((n) > NOTE_LAST)                     // not a note, but non-empty
164 #define NOTE_IS_INVALID(n)      ((n) > NOTE_LAST && (n) < NOTE_CUT && (n) != NOTE_FADE) // ???
165 
166 // Auto-vibrato types
167 #define VIB_SINE                0
168 #define VIB_RAMP_DOWN           1
169 #define VIB_SQUARE              2
170 #define VIB_RANDOM              3
171 
172 // NNA types
173 #define NNA_NOTECUT             0
174 #define NNA_CONTINUE            1
175 #define NNA_NOTEOFF             2
176 #define NNA_NOTEFADE            3
177 
178 // DCT types
179 #define DCT_NONE                0
180 #define DCT_NOTE                1
181 #define DCT_SAMPLE              2
182 #define DCT_INSTRUMENT          3
183 
184 // DCA types
185 #define DCA_NOTECUT             0
186 #define DCA_NOTEOFF             1
187 #define DCA_NOTEFADE            2
188 
189 // Nothing innately special about this -- just needs to be above the max pattern length.
190 // process row is set to this in order to get the player to jump to the end of the pattern.
191 // (See ITTECH.TXT)
192 #define PROCESS_NEXT_ORDER      0xFFFE
193 
194 // Module flags
195 #define SONG_EMBEDMIDICFG       0x0001 // Embed MIDI macros (Shift-F1) in file
196 //#define SONG_FASTVOLSLIDES    0x0002
197 #define SONG_ITOLDEFFECTS       0x0004 // Old Impulse Tracker effect implementations
198 #define SONG_COMPATGXX          0x0008 // "Compatible Gxx" (handle portamento more like other trackers)
199 #define SONG_LINEARSLIDES       0x0010 // Linear slides vs. Amiga slides
200 #define SONG_PATTERNPLAYBACK    0x0020 // Only playing current pattern
201 //#define SONG_STEP             0x0040
202 #define SONG_PAUSED             0x0080 // Playback paused (Shift-F8)
203 //#define SONG_FADINGSONG       0x0100
204 #define SONG_ENDREACHED         0x0200 // Song is finished (standalone keyjazz mode)
205 //#define SONG_GLOBALFADE       0x0400
206 //#define SONG_CPUVERYHIGH      0x0800
207 #define SONG_FIRSTTICK          0x1000 // Current tick is the first tick of the row (dopey flow-control flag)
208 //#define SONG_MPTFILTERMODE    0x2000
209 //#define SONG_SURROUNDPAN      0x4000
210 //#define SONG_EXFILTERRANGE    0x8000
211 //#define SONG_AMIGALIMITS      0x10000
212 #define SONG_INSTRUMENTMODE     0x20000 // Process instruments
213 #define SONG_ORDERLOCKED        0x40000 // Don't advance orderlist *(Alt-F11)
214 #define SONG_NOSTEREO           0x80000 // secret code for "mono"
215 #define SONG_PATTERNLOOP        (SONG_PATTERNPLAYBACK | SONG_ORDERLOCKED) // Loop current pattern (F6)
216 
217 // Global Options (Renderer)
218 #define SNDMIX_REVERSESTEREO    0x0001 // swap L/R audio channels
219 //#define SNDMIX_NOISEREDUCTION 0x0002 // reduce hiss (do not use, it's just a simple low-pass filter)
220 //#define SNDMIX_AGC            0x0004 // automatic gain control
221 #define SNDMIX_NORESAMPLING     0x0008 // force no resampling (uninterpolated)
222 #define SNDMIX_HQRESAMPLER      0x0010 // cubic resampling
223 //#define SNDMIX_MEGABASS       0x0020
224 //#define SNDMIX_SURROUND       0x0040
225 //#define SNDMIX_REVERB         0x0080
226 //#define SNDMIX_EQ             0x0100 // apply EQ (always on)
227 //#define SNDMIX_SOFTPANNING    0x0200
228 #define SNDMIX_ULTRAHQSRCMODE   0x0400 // polyphase resampling (or FIR? I don't know)
229 // Misc Flags (can safely be turned on or off)
230 #define SNDMIX_DIRECTTODISK     0x10000 // disk writer mode
231 #define SNDMIX_NOBACKWARDJUMPS  0x40000 // disallow Bxx jumps from going backward in the orderlist
232 //#define SNDMIX_MAXDEFAULTPAN  0x80000 // (no longer) Used by the MOD loader
233 #define SNDMIX_MUTECHNMODE      0x100000 // Notes are not played on muted channels
234 #define SNDMIX_NOSURROUND       0x200000 // ignore S91
235 //#define SNDMIX_NOMIXING       0x400000
236 #define SNDMIX_NORAMPING        0x800000 // don't apply ramping on volume change (causes clicks)
237 
238 enum {
239 	SRCMODE_NEAREST,
240 	SRCMODE_LINEAR,
241 	SRCMODE_SPLINE,
242 	SRCMODE_POLYPHASE,
243 	NUM_SRC_MODES
244 };
245 
246 // ------------------------------------------------------------------------------------------------------------
247 // Flags for csf_read_sample
248 
249 // Sample data characteristics
250 // Note:
251 // - None of these constants are zero
252 // - The format specifier must have a value set for each "section"
253 // - csf_read_sample DOES check the values for validity
254 
255 // Bit width (8 bits for simplicity)
256 #define _SDV_BIT(n)            ((n) << 0)
257 #define SF_BIT_MASK            0xff
258 #define SF_7                   _SDV_BIT(7)  // 7-bit (weird!)
259 #define SF_8                   _SDV_BIT(8)  // 8-bit
260 #define SF_16                  _SDV_BIT(16) // 16-bit
261 #define SF_24                  _SDV_BIT(24) // 24-bit
262 #define SF_32                  _SDV_BIT(32) // 32-bit
263 
264 // Channels (4 bits)
265 #define _SDV_CHN(n)            ((n) << 8)
266 #define SF_CHN_MASK            0xf00
267 #define SF_M                   _SDV_CHN(1) // mono
268 #define SF_SI                  _SDV_CHN(2) // stereo, interleaved
269 #define SF_SS                  _SDV_CHN(3) // stereo, split
270 
271 // Endianness (4 bits)
272 #define _SDV_END(n)            ((n) << 12)
273 #define SF_END_MASK            0xf000
274 #define SF_LE                  _SDV_END(1) // little-endian
275 #define SF_BE                  _SDV_END(2) // big-endian
276 
277 // Encoding (8 bits)
278 #define _SDV_ENC(n)            ((n) << 16)
279 #define SF_ENC_MASK            0xff0000
280 #define SF_PCMS                _SDV_ENC(1) // PCM, signed
281 #define SF_PCMU                _SDV_ENC(2) // PCM, unsigned
282 #define SF_PCMD                _SDV_ENC(3) // PCM, delta-encoded
283 #define SF_IT214               _SDV_ENC(4) // Impulse Tracker 2.14 compressed
284 #define SF_IT215               _SDV_ENC(5) // Impulse Tracker 2.15 compressed
285 #define SF_AMS                 _SDV_ENC(6) // AMS / Velvet Studio packed
286 #define SF_DMF                 _SDV_ENC(7) // DMF Huffman compression
287 #define SF_MDL                 _SDV_ENC(8) // MDL Huffman compression
288 #define SF_PTM                 _SDV_ENC(9) // PTM 8-bit delta value -> 16-bit sample
289 #define SF_PCMD16              _SDV_ENC(10) // PCM, 16-byte table delta-encoded
290 
291 // Sample format shortcut
292 #define SF(a,b,c,d) (SF_ ## a | SF_ ## b| SF_ ## c | SF_ ## d)
293 
294 // Deprecated constants
295 #define RS_AMS16        SF(AMS,16,M,LE)
296 #define RS_AMS8         SF(AMS,8,M,LE)
297 #define RS_DMF16        SF(DMF,16,M,LE)
298 #define RS_DMF8         SF(DMF,8,M,LE)
299 #define RS_IT21416      SF(IT214,16,M,LE)
300 #define RS_IT2148       SF(IT214,8,M,LE)
301 #define RS_IT21516      SF(IT215,16,M,LE)
302 #define RS_IT2158       SF(IT215,8,M,LE)
303 #define RS_IT21416S     SF(IT214,16,SS,LE)
304 #define RS_IT2148S      SF(IT214,8,SS,LE)
305 #define RS_IT21516S     SF(IT215,16,SS,LE)
306 #define RS_IT2158S      SF(IT215,8,SS,LE)
307 #define RS_MDL16        SF(MDL,16,M,LE)
308 #define RS_MDL8         SF(MDL,8,M,LE)
309 #define RS_PCM16D       SF(PCMD,16,M,LE)
310 #define RS_PCM16M       SF(PCMS,16,M,BE)
311 #define RS_PCM16S       SF(PCMS,16,M,LE)
312 #define RS_PCM16U       SF(PCMU,16,M,LE)
313 #define RS_PCM24S       SF(PCMS,24,M,LE)
314 #define RS_PCM32S       SF(PCMS,32,M,LE)
315 #define RS_PCM8D        SF(PCMD,8,M,LE)
316 #define RS_PCM8D16      SF(PCMD16,8,M,LE)
317 #define RS_PCM8S        SF(PCMS,8,M,LE)
318 #define RS_PCM8U        SF(PCMU,8,M,LE)
319 #define RS_PTM8DTO16    SF(PTM,16,M,LE)
320 #define RS_STIPCM16M    SF(PCMS,16,SI,BE)
321 #define RS_STIPCM16S    SF(PCMS,16,SI,LE)
322 #define RS_STIPCM16U    SF(PCMU,16,SI,LE)
323 #define RS_STIPCM24S    SF(PCMS,24,SI,LE)
324 #define RS_STIPCM32S    SF(PCMS,32,SI,LE)
325 #define RS_STIPCM8S     SF(PCMS,8,SI,LE)
326 #define RS_STIPCM8U     SF(PCMU,8,SI,LE)
327 #define RS_STPCM16D     SF(PCMD,16,SS,LE)
328 #define RS_STPCM16M     SF(PCMS,16,SS,BE)
329 #define RS_STPCM16S     SF(PCMS,16,SS,LE)
330 #define RS_STPCM16U     SF(PCMU,16,SS,LE)
331 #define RS_STPCM8D      SF(PCMD,8,SS,LE)
332 #define RS_STPCM8S      SF(PCMS,8,SS,LE)
333 #define RS_STPCM8U      SF(PCMU,8,SS,LE)
334 
335 // ------------------------------------------------------------------------------------------------------------
336 
337 typedef struct song_sample {
338 	uint32_t length;
339 	uint32_t loop_start;
340 	uint32_t loop_end;
341 	uint32_t sustain_start;
342 	uint32_t sustain_end;
343 	signed char *data;
344 	uint32_t c5speed;
345 	uint32_t panning;
346 	uint32_t volume;
347 	uint32_t global_volume;
348 	uint32_t flags;
349 	uint32_t vib_type;
350 	uint32_t vib_rate;
351 	uint32_t vib_depth;
352 	uint32_t vib_speed;
353 	char name[32];
354 	char filename[22];
355 	int played; // for note playback dots
356 	uint32_t globalvol_saved; // for muting individual samples
357 
358 	// This must be 12-bytes to work around a bug in some gcc4.2s (XXX why? what bug?)
359 	unsigned char adlib_bytes[12];
360 } song_sample_t;
361 
362 typedef struct song_envelope {
363 	int ticks[32];
364 	uint8_t values[32];
365 	int nodes;
366 	int loop_start;
367 	int loop_end;
368 	int sustain_start;
369 	int sustain_end;
370 } song_envelope_t;
371 
372 typedef struct song_instrument {
373 	uint32_t fadeout;
374 	uint32_t flags;
375 	unsigned int global_volume;
376 	unsigned int panning;
377 	uint8_t sample_map[128];
378 	uint8_t note_map[128];
379 	song_envelope_t vol_env;
380 	song_envelope_t pan_env;
381 	song_envelope_t pitch_env;
382 	unsigned int nna;
383 	unsigned int dct;
384 	unsigned int dca;
385 	unsigned int pan_swing;
386 	unsigned int vol_swing;
387 	unsigned int ifc;
388 	unsigned int ifr;
389 	int midi_bank; // TODO split this?
390 	int midi_program;
391 	unsigned int midi_channel_mask; // FIXME why is this a mask? why is a mask useful? does 2.15 use a mask?
392 	int pitch_pan_separation;
393 	unsigned int pitch_pan_center;
394 	char name[32];
395 	char filename[16];
396 	int played; // for note playback dots
397 } song_instrument_t;
398 
399 // (TODO write decent descriptions of what the various volume
400 // variables are used for - are all of them *really* necessary?)
401 // (TODO also the majority of this is irrelevant outside of the "main" 64 channels;
402 // this struct should really only be holding the stuff actually needed for mixing)
403 typedef struct song_voice {
404 	// First 32-bytes: Most used mixing information: don't change it
405 	signed char * current_sample_data;
406 	uint32_t position; // sample position, fixed-point -- integer part
407 	uint32_t position_frac; // fractional part
408 	int32_t increment; // 16.16 fixed point, how much to add to position per sample-frame of output
409 	int32_t right_volume; // ?
410 	int32_t left_volume; // ?
411 	int32_t right_ramp; // ?
412 	int32_t left_ramp; // ?
413 	// 2nd cache line
414 	uint32_t length; // only to the end of the loop
415 	uint32_t flags;
416 	uint32_t loop_start; // loop or sustain, whichever is active
417 	uint32_t loop_end;
418 	int32_t right_ramp_volume; // ?
419 	int32_t left_ramp_volume; // ?
420 	int32_t strike; // decremented to zero. this affects how long the initial hit on the playback marks lasts (bigger dot in instrument and sample list windows)
421 
422 	int32_t filter_y1, filter_y2, filter_y3, filter_y4;
423 	int32_t filter_a0, filter_b0, filter_b1;
424 
425 	int32_t rofs, lofs; // ?
426 	int32_t ramp_length;
427 	// Information not used in the mixer
428 	int32_t right_volume_new, left_volume_new; // ?
429 	int32_t final_volume; // range 0-16384 (?), accounting for sample+channel+global+etc. volumes
430 	int32_t final_panning; // range 0-256 (but can temporarily exceed that range during calculations)
431 	int32_t volume, panning; // range 0-256 (?); these are the current values set for the channel
432 	int32_t fadeout_volume;
433 	int32_t frequency;
434 	int32_t c5speed;
435 	int32_t sample_freq; // only used on the info page (F5)
436 	int32_t portamento_target;
437 	song_instrument_t *ptr_instrument;      // these two suck, and should
438 	song_sample_t *ptr_sample;              // be replaced with numbers
439 	int vol_env_position;
440 	int pan_env_position;
441 	int pitch_env_position;
442 	uint32_t master_channel; // nonzero = background/NNA voice, indicates what channel it "came from"
443 	uint32_t vu_meter;
444     // TODO: As noted elsewhere, this means current channel volume.
445 	int32_t global_volume;
446     // FIXME: Here instrument_volume means the value calculated from sample global volume and instrument global volume.
447     //  And we miss a value for "running envelope volume" for the page_info
448 	int32_t instrument_volume;
449 	int32_t autovib_depth;
450 	uint32_t autovib_position, vibrato_position, tremolo_position, panbrello_position;
451 	// 16-bit members
452 	int vol_swing, pan_swing;
453 	uint16_t channel_panning;
454 
455 	// formally 8-bit members
456 	unsigned int note; // the note that's playing
457 	unsigned int nna;
458 	unsigned int new_note, new_instrument; // ?
459 	// Effect memory and handling
460 	unsigned int n_command; // This sucks and needs to go away (dumb "flag" for arpeggio / tremor)
461 	unsigned int mem_vc_volslide; // Ax Bx Cx Dx (volume column)
462 	unsigned int mem_arpeggio; // Axx
463 	unsigned int mem_volslide; // Dxx
464 	unsigned int mem_pitchslide; // Exx Fxx (and Gxx maybe)
465 	int32_t mem_portanote; // Gxx (synced with mem_pitchslide if compat gxx is set)
466 	unsigned int mem_tremor; // Ixx
467 	unsigned int mem_channel_volslide; // Nxx
468 	unsigned int mem_offset; // final, combined yxx00h from Oxx and SAy
469 	unsigned int mem_panslide; // Pxx
470 	unsigned int mem_retrig; // Qxx
471 	unsigned int mem_special; // Sxx
472 	unsigned int mem_tempo; // Txx
473 	unsigned int mem_global_volslide; // Wxx
474 	unsigned int note_slide_counter, note_slide_speed, note_slide_step; // IMF effect
475 	unsigned int vib_type, vibrato_speed, vibrato_depth;
476 	unsigned int tremolo_type, tremolo_speed, tremolo_depth;
477 	unsigned int panbrello_type, panbrello_speed, panbrello_depth;
478 	int tremolo_delta, panbrello_delta;
479 
480 	unsigned int cutoff;
481 	unsigned int resonance;
482 	int cd_note_delay; // countdown: note starts when this hits zero
483 	int cd_note_cut; // countdown: note stops when this hits zero
484 	int cd_retrig; // countdown: note retrigs when this hits zero
485 	unsigned int cd_tremor; // (weird) countdown + flag: see snd_fx.c and sndmix.c
486 	unsigned int patloop_row; // row number that SB0 was on
487 	unsigned int cd_patloop; // countdown: pattern loops back when this hits zero
488 
489 	unsigned int row_note, row_instr;
490 	unsigned int row_voleffect, row_volparam;
491 	unsigned int row_effect, row_param;
492 	unsigned int active_macro, last_instrument;
493 } song_voice_t;
494 
495 typedef struct song_channel {
496 	uint32_t panning;
497 	uint32_t volume;
498 	uint32_t flags;
499 } song_channel_t;
500 
501 typedef struct song_note {
502 	uint8_t note;
503 	uint8_t instrument;
504 	uint8_t voleffect;
505 	uint8_t volparam;
506 	uint8_t effect;
507 	uint8_t param;
508 } song_note_t;
509 
510 ////////////////////////////////////////////////////////////////////
511 
512 typedef struct {
513 	char start[32];
514 	char stop[32];
515 	char tick[32];
516 	char note_on[32];
517 	char note_off[32];
518 	char set_volume[32];
519 	char set_panning[32];
520 	char set_bank[32];
521 	char set_program[32];
522 	char sfx[16][32];
523 	char zxx[128][32];
524 } midi_config_t;
525 
526 extern midi_config_t default_midi_config;
527 
528 
529 extern uint32_t max_voices;
530 extern uint32_t global_vu_left, global_vu_right;
531 
532 extern const song_note_t blank_pattern[64 * 64];
533 extern const song_note_t *blank_note;
534 
535 
536 struct multi_write {
537 	int used;
538 	void *data;
539 	/* Conveniently, this has the same prototype as disko_write :) */
540 	void (*write)(void *data, const uint8_t *buf, size_t bytes);
541 	/* this is optimization for channels that haven't had any data yet
542 	(nothing to convert/write, just seek ahead in the data stream) */
543 	void (*silence)(void *data, long bytes);
544 	int buffer[MIXBUFFERSIZE * 2];
545 };
546 
547 typedef struct song {
548 	int mix_buffer[MIXBUFFERSIZE * 2];
549 	float mix_buffer_float[MIXBUFFERSIZE * 2]; // is this needed?
550 
551 	song_voice_t voices[MAX_VOICES];                // Channels
552 	uint32_t voice_mix[MAX_VOICES];                 // Channels to be mixed
553 	song_sample_t samples[MAX_SAMPLES+1];           // Samples (1-based!)
554 	song_instrument_t *instruments[MAX_INSTRUMENTS+1]; // Instruments (1-based!)
555 	song_channel_t channels[MAX_CHANNELS];          // Channel settings
556 	song_note_t *patterns[MAX_PATTERNS];            // Patterns
557 	uint16_t pattern_size[MAX_PATTERNS];            // Pattern Lengths
558 	uint16_t pattern_alloc_size[MAX_PATTERNS];      // Allocated lengths (for async. resizing/playback)
559 	uint8_t orderlist[MAX_ORDERS + 1];              // Pattern Orders
560 	midi_config_t midi_config;                      // Midi macro config table
561 	uint32_t initial_speed;
562 	uint32_t initial_tempo;
563 	uint32_t initial_global_volume;
564 	uint32_t flags;                                 // Song flags SONG_XXXX
565 	uint32_t pan_separation;
566 	uint32_t num_voices; // how many are currently playing. (POTENTIALLY larger than global max_voices)
567 	uint32_t mix_stat; // number of channels being mixed (not really used)
568 	uint32_t buffer_count; // number of samples to mix per tick
569 	uint32_t tick_count;
570 	int32_t row_count; /* IMPORTANT needs to be signed */
571 	uint32_t current_speed;
572 	uint32_t current_tempo;
573 	uint32_t process_row;
574 	uint32_t row; // no analogue in pm.h? should be either renamed or factored out.
575 	uint32_t break_row;
576 	uint32_t current_pattern;
577 	uint32_t current_order;
578 	uint32_t process_order;
579 	uint32_t current_global_volume;
580 	uint32_t mixing_volume;
581 	uint32_t freq_factor; // not used -- for tweaking the song speed LP-style (interesting!)
582 	uint32_t tempo_factor; // ditto
583 	int32_t repeat_count; // 0 = first playback, etc. (note: set to -1 to stop instead of looping)
584 	uint8_t row_highlight_major;
585 	uint8_t row_highlight_minor;
586 	char message[MAX_MESSAGE + 1];
587 	char title[32];
588 	char tracker_id[32]; // irrelevant to the song, just used by some loaders (fingerprint)
589 
590 	// These store the existing IT save history from prior editing sessions.
591 	// Current session data is added at save time, and is NOT a part of histdata.
592 	int histlen; // How many session history data entries exist (each entry is eight bytes)
593 	uint8_t *histdata; // Preserved entries from prior sessions, might be NULL if histlen = 0
594 	struct timeval editstart; // When the song was loaded
595 
596 	// mixer stuff
597 	uint32_t mix_flags; // SNDMIX_*
598 	uint32_t mix_frequency, mix_bits_per_sample, mix_channels;
599 
600 	// noise reduction filter
601 	int32_t left_nr, right_nr;
602 
603 	// chaseback
604 	int stop_at_order;
605 	int stop_at_row;
606 	unsigned int stop_at_time;
607 
608 	// multi-write stuff -- NULL if no multi-write is in progress, else array of one struct per channel
609 	struct multi_write *multi_write;
610 } song_t;
611 
612 song_note_t *csf_allocate_pattern(uint32_t rows);
613 void csf_free_pattern(void *pat);
614 signed char *csf_allocate_sample(uint32_t nbytes);
615 void csf_free_sample(void *p);
616 song_instrument_t *csf_allocate_instrument(void);
617 void csf_init_instrument(song_instrument_t *ins, int samp);
618 void csf_free_instrument(song_instrument_t *p);
619 
620 uint32_t csf_read_sample(song_sample_t *sample, uint32_t flags, const void *filedata, uint32_t datalength);
621 uint32_t csf_write_sample(disko_t *fp, song_sample_t *sample, uint32_t flags, uint32_t maxlengthmask);
622 void csf_adjust_sample_loop(song_sample_t *sample);
623 
624 extern void (*csf_midi_out_note)(int chan, const song_note_t *m);
625 extern void (*csf_midi_out_raw)(const unsigned char *, unsigned int, unsigned int);
626 
627 void csf_import_mod_effect(song_note_t *m, int from_xm);
628 uint16_t csf_export_mod_effect(const song_note_t *m, int xm);
629 
630 void csf_import_s3m_effect(song_note_t *m, int it);
631 void csf_export_s3m_effect(uint8_t *pcmd, uint8_t *pprm, int it);
632 
633 
634 // counting stuff
635 
636 int csf_note_is_empty(song_note_t *note);
637 int csf_pattern_is_empty(song_t *csf, int n);
638 int csf_sample_is_empty(song_sample_t *smp);
639 int csf_instrument_is_empty(song_instrument_t *ins);
640 int csf_last_order(song_t *csf); // last order of "main" song (IT-style, only for display)
641 int csf_get_num_orders(song_t *csf); // last non-blank order (for saving)
642 int csf_get_num_patterns(song_t *csf);
643 int csf_get_num_samples(song_t *csf);
644 int csf_get_num_instruments(song_t *csf);
645 
646 // for these, 'start' indicates minimum sample/instrument to check
647 int csf_first_blank_sample(song_t *csf, int start);
648 int csf_first_blank_instrument(song_t *csf, int start);
649 
650 int csf_get_highest_used_channel(song_t *csf);
651 
652 
653 
654 int csf_set_wave_config(song_t *csf, uint32_t rate, uint32_t bits, uint32_t channels);
655 
656 // Mixer Config
657 int csf_init_player(song_t *csf, int reset); // bReset=false
658 int csf_set_resampling_mode(song_t *csf, uint32_t mode); // SRCMODE_XXXX
659 
660 
661 // sndmix
662 unsigned int csf_read(song_t *csf, void *v_buffer, unsigned int bufsize);
663 int csf_process_tick(song_t *csf);
664 int csf_read_note(song_t *csf);
665 
666 // snd_fx
667 unsigned int csf_get_length(song_t *csf); // (in seconds)
668 void csf_instrument_change(song_t *csf, song_voice_t *chn, uint32_t instr, int porta, int instr_column);
669 void csf_note_change(song_t *csf, uint32_t chan, int note, int porta, int retrig, int have_inst);
670 uint32_t csf_get_nna_channel(song_t *csf, uint32_t chan);
671 void csf_check_nna(song_t *csf, uint32_t chan, uint32_t instr, int note, int force_cut);
672 void csf_process_effects(song_t *csf, int firsttick);
673 int32_t csf_fx_do_freq_slide(uint32_t flags, int32_t frequency, int32_t slide, int is_tone_portamento);
674 
675 void fx_note_cut(song_t *csf, uint32_t chan, int clear_note);
676 void fx_key_off(song_t *csf, uint32_t chan);
677 void csf_midi_send(song_t *csf, const unsigned char *data, unsigned int len, uint32_t chan, int fake);
678 void csf_process_midi_macro(song_t *csf, uint32_t chan, const char *midi_macro, uint32_t param,
679 			uint32_t note, uint32_t velocity, uint32_t use_instr);
680 song_sample_t *csf_translate_keyboard(song_t *csf, song_instrument_t *ins, uint32_t note, song_sample_t *def);
681 
682 // various utility functions in snd_fx.c
683 int get_note_from_frequency(int frequency, unsigned int c5speed);
684 int get_frequency_from_note(int note, unsigned int c5speed);
685 unsigned int transpose_to_frequency(int transp, int ftune);
686 int frequency_to_transpose(unsigned int freq);
687 unsigned long calc_halftone(unsigned long hz, int rel);
688 
689 
690 // sndfile
691 song_t *csf_allocate(void);
692 void csf_free(song_t *csf);
693 
694 void csf_destroy(song_t *csf); /* erase everything -- equiv. to new song */
695 int csf_destroy_sample(song_t *csf, uint32_t smpnum);
696 
697 void csf_stop_sample(song_t *csf, song_sample_t *smp);
698 
699 void csf_reset_midi_cfg(song_t *csf);
700 void csf_copy_midi_cfg(song_t *dest, song_t *src);
701 void csf_set_current_order(song_t *csf, uint32_t position);
702 void csf_loop_pattern(song_t *csf, int pattern, int start_row);
703 void csf_reset_playmarks(song_t *csf);
704 
705 void csf_insert_restart_pos(song_t *csf, uint32_t restart_order); // hax
706 
707 void csf_forget_history(song_t *csf); // Send the edit log down the memory hole.
708 
709 /* apply a preset Adlib patch */
710 void adlib_patch_apply(song_sample_t *smp, int patchnum);
711 
712 ///////////////////////////////////////////////////////////
713 
714 // Return (a*b)/c - no divide error
715 static inline int _muldiv(int a, int b, int c)
716 {
717 	return ((unsigned long long) a * (unsigned long long) b ) / c;
718 }
719 
720 
721 // Return (a*b+c/2)/c - no divide error
722 static inline int _muldivr(int a, int b, int c)
723 {
724 	return ((unsigned long long) a * (unsigned long long) b + (c >> 1)) / c;
725 }
726 
727 
728 #endif
729 
730