Debian Codegraph @

src/external/jar_xm.h

raw symbols SCIP
1 // jar_xm.h
2 //
3 // ORIGINAL LICENSE - FOR LIBXM:
4 //
5 // Author: Romain "Artefact2" Dalmaso <[email protected]>
6 // Contributor: Dan Spencer <[email protected]>
7 // Repackaged into jar_xm.h By: Joshua Adam Reisenauer <[email protected]>
8 // This program is free software. It comes without any warranty, to the
9 // extent permitted by applicable law. You can redistribute it and/or
10 // modify it under the terms of the Do What The Fuck You Want To Public
11 // License, Version 2, as published by Sam Hocevar. See
12 // http://sam.zoy.org/wtfpl/COPYING for more details.
13 //
14 // HISTORY:
15 // v0.1.0 2016-02-22 jar_xm.h - development by Joshua Reisenauer, MAR 2016
16 // v0.2.1 2021-03-07 m4ntr0n1c: Fix clipping noise for "bad" xm's (they will always clip), avoid clip noise and just put a ceiling)
17 // v0.2.2 2021-03-09 m4ntr0n1c: Add complete debug solution (raylib.h must be included)
18 // v0.2.3 2021-03-11 m4ntr0n1c: Fix tempo, bpm and volume on song stop / start / restart / loop
19 // v0.2.4 2021-03-17 m4ntr0n1c: Sanitize code for readability
20 // v0.2.5 2021-03-22 m4ntr0n1c: Minor adjustments
21 // v0.2.6 2021-04-01 m4ntr0n1c: Minor fixes and optimisation
22 // v0.3.0 2021-04-03 m4ntr0n1c: Addition of Stereo sample support, Linear Interpolation and Ramping now addressable options in code
23 // v0.3.1 2021-04-04 m4ntr0n1c: Volume effects column adjustments, sample offset handling adjustments
24 //
25 // USAGE:
26 //
27 // In ONE source file, put:
28 //
29 // #define JAR_XM_IMPLEMENTATION
30 // #include "jar_xm.h"
31 //
32 // Other source files should just include jar_xm.h
33 //
34 // SAMPLE CODE:
35 //
36 // jar_xm_context_t *musicptr;
37 // float musicBuffer[48000 / 60];
38 // int intro_load(void)
39 // {
40 // jar_xm_create_context_from_file(&musicptr, 48000, "Song.XM");
41 // return 1;
42 // }
43 // int intro_unload(void)
44 // {
45 // jar_xm_free_context(musicptr);
46 // return 1;
47 // }
48 // int intro_tick(long counter)
49 // {
50 // jar_xm_generate_samples(musicptr, musicBuffer, (48000 / 60) / 2);
51 // if(IsKeyDown(KEY_ENTER))
52 // return 1;
53 // return 0;
54 // }
55 //
56 #ifndef INCLUDE_JAR_XM_H
57 #define INCLUDE_JAR_XM_H
58
59 #include <stdint.h>
60
61 #define JAR_XM_DEBUG 0
62 #define JAR_XM_DEFENSIVE 1
63 //#define JAR_XM_RAYLIB 0 // set to 0 to disable the RayLib visualizer extension
64
65 // Allow custom memory allocators
66 #ifndef JARXM_MALLOC
67 #define JARXM_MALLOC(sz) malloc(sz)
68 #endif
69 #ifndef JARXM_FREE
70 #define JARXM_FREE(p) free(p)
71 #endif
72
73 //-------------------------------------------------------------------------------
74 struct jar_xm_context_s;
75 typedef struct jar_xm_context_s jar_xm_context_t;
76
77 #ifdef __cplusplus
78 extern "C" {
79 #endif
80
81 //** Create a XM context.
82 // * @param moddata the contents of the module
83 // * @param rate play rate in Hz, recommended value of 48000
84 // * @returns 0 on success
85 // * @returns 1 if module data is not sane
86 // * @returns 2 if memory allocation failed
87 // * @returns 3 unable to open input file
88 // * @returns 4 fseek() failed
89 // * @returns 5 fread() failed
90 // * @returns 6 unkown error
91 // * @deprecated This function is unsafe!
92 // * @see jar_xm_create_context_safe()
93 int jar_xm_create_context_from_file(jar_xm_context_t** ctx, uint32_t rate, const char* filename);
94
95 //** Create a XM context.
96 // * @param moddata the contents of the module
97 // * @param rate play rate in Hz, recommended value of 48000
98 // * @returns 0 on success
99 // * @returns 1 if module data is not sane
100 // * @returns 2 if memory allocation failed
101 // * @deprecated This function is unsafe!
102 // * @see jar_xm_create_context_safe()
103 int jar_xm_create_context(jar_xm_context_t** ctx, const char* moddata, uint32_t rate);
104
105 //** Create a XM context.
106 // * @param moddata the contents of the module
107 // * @param moddata_length the length of the contents of the module, in bytes
108 // * @param rate play rate in Hz, recommended value of 48000
109 // * @returns 0 on success
110 // * @returns 1 if module data is not sane
111 // * @returns 2 if memory allocation failed
112 int jar_xm_create_context_safe(jar_xm_context_t** ctx, const char* moddata, size_t moddata_length, uint32_t rate);
113
114 //** Free a XM context created by jar_xm_create_context(). */
115 void jar_xm_free_context(jar_xm_context_t* ctx);
116
117 //** Play the module and put the sound samples in an output buffer.
118 // * @param output buffer of 2*numsamples elements (A left and right value for each sample)
119 // * @param numsamples number of samples to generate
120 void jar_xm_generate_samples(jar_xm_context_t* ctx, float* output, size_t numsamples);
121
122 //** Play the module, resample from float to 16 bit, and put the sound samples in an output buffer.
123 // * @param output buffer of 2*numsamples elements (A left and right value for each sample)
124 // * @param numsamples number of samples to generate
125 void jar_xm_generate_samples_16bit(jar_xm_context_t* ctx, short* output, size_t numsamples) {
126 float* musicBuffer = (float *)JARXM_MALLOC((2*numsamples)*sizeof(float));
127 jar_xm_generate_samples(ctx, musicBuffer, numsamples);
128
129 if(output){
130 for(int x=0;x<2*numsamples;x++) output[x] = (musicBuffer[x] * 32767.0f); // scale sample to signed small int
131 }
132 JARXM_FREE(musicBuffer);
133 }
134
135 //** Play the module, resample from float to 8 bit, and put the sound samples in an output buffer.
136 // * @param output buffer of 2*numsamples elements (A left and right value for each sample)
137 // * @param numsamples number of samples to generate
138 void jar_xm_generate_samples_8bit(jar_xm_context_t* ctx, char* output, size_t numsamples) {
139 float* musicBuffer = (float *)JARXM_MALLOC((2*numsamples)*sizeof(float));
140 jar_xm_generate_samples(ctx, musicBuffer, numsamples);
141
142 if(output){
143 for(int x=0;x<2*numsamples;x++) output[x] = (musicBuffer[x] * 127.0f); // scale sample to signed 8 bit
144 }
145 JARXM_FREE(musicBuffer);
146 }
147
148 //** Set the maximum number of times a module can loop. After the specified number of loops, calls to jar_xm_generate_samples will only generate silence. You can control the current number of loops with jar_xm_get_loop_count().
149 // * @param loopcnt maximum number of loops. Use 0 to loop indefinitely.
150 void jar_xm_set_max_loop_count(jar_xm_context_t* ctx, uint8_t loopcnt);
151
152 //** Get the loop count of the currently playing module. This value is 0 when the module is still playing, 1 when the module has looped once, etc.
153 uint8_t jar_xm_get_loop_count(jar_xm_context_t* ctx);
154
155 //** Mute or unmute a channel.
156 // * @note Channel numbers go from 1 to jar_xm_get_number_of_channels(...).
157 // * @return whether the channel was muted.
158 bool jar_xm_mute_channel(jar_xm_context_t* ctx, uint16_t, bool);
159
160 //** Mute or unmute an instrument.
161 // * @note Instrument numbers go from 1 to jar_xm_get_number_of_instruments(...).
162 // * @return whether the instrument was muted.
163 bool jar_xm_mute_instrument(jar_xm_context_t* ctx, uint16_t, bool);
164
165 //** Get the module name as a NUL-terminated string.
166 const char* jar_xm_get_module_name(jar_xm_context_t* ctx);
167
168 //** Get the tracker name as a NUL-terminated string.
169 const char* jar_xm_get_tracker_name(jar_xm_context_t* ctx);
170
171 //** Get the number of channels.
172 uint16_t jar_xm_get_number_of_channels(jar_xm_context_t* ctx);
173
174 //** Get the module length (in patterns).
175 uint16_t jar_xm_get_module_length(jar_xm_context_t*);
176
177 //** Get the number of patterns.
178 uint16_t jar_xm_get_number_of_patterns(jar_xm_context_t* ctx);
179
180 //** Get the number of rows of a pattern.
181 // * @note Pattern numbers go from 0 to jar_xm_get_number_of_patterns(...)-1.
182 uint16_t jar_xm_get_number_of_rows(jar_xm_context_t* ctx, uint16_t);
183
184 //** Get the number of instruments.
185 uint16_t jar_xm_get_number_of_instruments(jar_xm_context_t* ctx);
186
187 //** Get the number of samples of an instrument.
188 // * @note Instrument numbers go from 1 to jar_xm_get_number_of_instruments(...).
189 uint16_t jar_xm_get_number_of_samples(jar_xm_context_t* ctx, uint16_t);
190
191 //** Get the current module speed.
192 // * @param bpm will receive the current BPM
193 // * @param tempo will receive the current tempo (ticks per line)
194 void jar_xm_get_playing_speed(jar_xm_context_t* ctx, uint16_t* bpm, uint16_t* tempo);
195
196 //** Get the current position in the module being played.
197 // * @param pattern_index if not NULL, will receive the current pattern index in the POT (pattern order table)
198 // * @param pattern if not NULL, will receive the current pattern number
199 // * @param row if not NULL, will receive the current row
200 // * @param samples if not NULL, will receive the total number of
201 // * generated samples (divide by sample rate to get seconds of generated audio)
202 void jar_xm_get_position(jar_xm_context_t* ctx, uint8_t* pattern_index, uint8_t* pattern, uint8_t* row, uint64_t* samples);
203
204 //** Get the latest time (in number of generated samples) when a particular instrument was triggered in any channel.
205 // * @note Instrument numbers go from 1 to jar_xm_get_number_of_instruments(...).
206 uint64_t jar_xm_get_latest_trigger_of_instrument(jar_xm_context_t* ctx, uint16_t);
207
208 //** Get the latest time (in number of generated samples) when a particular sample was triggered in any channel.
209 // * @note Instrument numbers go from 1 to jar_xm_get_number_of_instruments(...).
210 // * @note Sample numbers go from 0 to jar_xm_get_nubmer_of_samples(...,instr)-1.
211 uint64_t jar_xm_get_latest_trigger_of_sample(jar_xm_context_t* ctx, uint16_t instr, uint16_t sample);
212
213 //** Get the latest time (in number of generated samples) when any instrument was triggered in a given channel.
214 // * @note Channel numbers go from 1 to jar_xm_get_number_of_channels(...).
215 uint64_t jar_xm_get_latest_trigger_of_channel(jar_xm_context_t* ctx, uint16_t);
216
217 //** Get the number of remaining samples. Divide by 2 to get the number of individual LR data samples.
218 // * @note This is the remaining number of samples before the loop starts module again, or halts if on last pass.
219 // * @note This function is very slow and should only be run once, if at all.
220 uint64_t jar_xm_get_remaining_samples(jar_xm_context_t* ctx);
221
222 #ifdef __cplusplus
223 }
224 #endif
225 //-------------------------------------------------------------------------------
226
227 #ifdef JAR_XM_IMPLEMENTATION
228
229 #include <math.h>
230 #include <stdio.h>
231 #include <stdlib.h>
232 #include <limits.h>
233 #include <string.h>
234
235 #ifdef DEBUG
236 // Undefine DEBUG to avoid external redefinition warnings/conflicts
237 // This is probably a common definition for
238 // many external build systems' debug configurations
239 #undef DEBUG
240 #endif
241
242 #if JAR_XM_DEBUG //JAR_XM_DEBUG defined as 0
243 #include <stdio.h>
244 #define DEBUG(fmt, ...) do { \
245 fprintf(stderr, "%s(): " fmt "\n", __func__, __VA_ARGS__); \
246 fflush(stderr); \
247 } while(0)
248 #else
249 #define DEBUG(...)
250 #endif
251
252 #if jar_xm_BIG_ENDIAN
253 #error "Big endian platforms are not yet supported, sorry"
254 /* Make sure the compiler stops, even if #error is ignored */
255 extern int __fail[-1];
256 #endif
257
258 /* ----- XM constants ----- */
259 #define SAMPLE_NAME_LENGTH 22
260 #define INSTRUMENT_NAME_LENGTH 22
261 #define MODULE_NAME_LENGTH 20
262 #define TRACKER_NAME_LENGTH 20
263 #define PATTERN_ORDER_TABLE_LENGTH 256
264 #define NUM_NOTES 96 // from 1 to 96, where 1 = C-0
265 #define NUM_ENVELOPE_POINTS 12 // to be verified if 12 is the max
266 #define MAX_NUM_ROWS 256
267
268 #define jar_xm_SAMPLE_RAMPING_POINTS 8
269
270 /* ----- Data types ----- */
271
272 enum jar_xm_waveform_type_e {
273 jar_xm_SINE_WAVEFORM = 0,
274 jar_xm_RAMP_DOWN_WAVEFORM = 1,
275 jar_xm_SQUARE_WAVEFORM = 2,
276 jar_xm_RANDOM_WAVEFORM = 3,
277 jar_xm_RAMP_UP_WAVEFORM = 4,
278 };
279 typedef enum jar_xm_waveform_type_e jar_xm_waveform_type_t;
280
281 enum jar_xm_loop_type_e {
282 jar_xm_NO_LOOP,
283 jar_xm_FORWARD_LOOP,
284 jar_xm_PING_PONG_LOOP,
285 };
286 typedef enum jar_xm_loop_type_e jar_xm_loop_type_t;
287
288 enum jar_xm_frequency_type_e {
289 jar_xm_LINEAR_FREQUENCIES,
290 jar_xm_AMIGA_FREQUENCIES,
291 };
292 typedef enum jar_xm_frequency_type_e jar_xm_frequency_type_t;
293
294 struct jar_xm_envelope_point_s {
295 uint16_t frame;
296 uint16_t value;
297 };
298 typedef struct jar_xm_envelope_point_s jar_xm_envelope_point_t;
299
300 struct jar_xm_envelope_s {
301 jar_xm_envelope_point_t points[NUM_ENVELOPE_POINTS];
302 uint8_t num_points;
303 uint8_t sustain_point;
304 uint8_t loop_start_point;
305 uint8_t loop_end_point;
306 bool enabled;
307 bool sustain_enabled;
308 bool loop_enabled;
309 };
310 typedef struct jar_xm_envelope_s jar_xm_envelope_t;
311
312 struct jar_xm_sample_s {
313 char name[SAMPLE_NAME_LENGTH + 1];
314 int8_t bits; /* Either 8 or 16 */
315 int8_t stereo;
316 uint32_t length;
317 uint32_t loop_start;
318 uint32_t loop_length;
319 uint32_t loop_end;
320 float volume;
321 int8_t finetune;
322 jar_xm_loop_type_t loop_type;
323 float panning;
324 int8_t relative_note;
325 uint64_t latest_trigger;
326
327 float* data;
328 };
329 typedef struct jar_xm_sample_s jar_xm_sample_t;
330
331 struct jar_xm_instrument_s {
332 char name[INSTRUMENT_NAME_LENGTH + 1];
333 uint16_t num_samples;
334 uint8_t sample_of_notes[NUM_NOTES];
335 jar_xm_envelope_t volume_envelope;
336 jar_xm_envelope_t panning_envelope;
337 jar_xm_waveform_type_t vibrato_type;
338 uint8_t vibrato_sweep;
339 uint8_t vibrato_depth;
340 uint8_t vibrato_rate;
341 uint16_t volume_fadeout;
342 uint64_t latest_trigger;
343 bool muted;
344
345 jar_xm_sample_t* samples;
346 };
347 typedef struct jar_xm_instrument_s jar_xm_instrument_t;
348
349 struct jar_xm_pattern_slot_s {
350 uint8_t note; /* 1-96, 97 = Key Off note */
351 uint8_t instrument; /* 1-128 */
352 uint8_t volume_column;
353 uint8_t effect_type;
354 uint8_t effect_param;
355 };
356 typedef struct jar_xm_pattern_slot_s jar_xm_pattern_slot_t;
357
358 struct jar_xm_pattern_s {
359 uint16_t num_rows;
360 jar_xm_pattern_slot_t* slots; /* Array of size num_rows * num_channels */
361 };
362 typedef struct jar_xm_pattern_s jar_xm_pattern_t;
363
364 struct jar_xm_module_s {
365 char name[MODULE_NAME_LENGTH + 1];
366 char trackername[TRACKER_NAME_LENGTH + 1];
367 uint16_t length;
368 uint16_t restart_position;
369 uint16_t num_channels;
370 uint16_t num_patterns;
371 uint16_t num_instruments;
372 uint16_t linear_interpolation;
373 uint16_t ramping;
374 jar_xm_frequency_type_t frequency_type;
375 uint8_t pattern_table[PATTERN_ORDER_TABLE_LENGTH];
376
377 jar_xm_pattern_t* patterns;
378 jar_xm_instrument_t* instruments; /* Instrument 1 has index 0, instrument 2 has index 1, etc. */
379 };
380 typedef struct jar_xm_module_s jar_xm_module_t;
381
382 struct jar_xm_channel_context_s {
383 float note;
384 float orig_note; /* The original note before effect modifications, as read in the pattern. */
385 jar_xm_instrument_t* instrument; /* Could be NULL */
386 jar_xm_sample_t* sample; /* Could be NULL */
387 jar_xm_pattern_slot_t* current;
388
389 float sample_position;
390 float period;
391 float frequency;
392 float step;
393 bool ping; /* For ping-pong samples: true is -->, false is <-- */
394
395 float volume; /* Ideally between 0 (muted) and 1 (loudest) */
396 float panning; /* Between 0 (left) and 1 (right); 0.5 is centered */
397
398 uint16_t autovibrato_ticks;
399
400 bool sustained;
401 float fadeout_volume;
402 float volume_envelope_volume;
403 float panning_envelope_panning;
404 uint16_t volume_envelope_frame_count;
405 uint16_t panning_envelope_frame_count;
406
407 float autovibrato_note_offset;
408
409 bool arp_in_progress;
410 uint8_t arp_note_offset;
411 uint8_t volume_slide_param;
412 uint8_t fine_volume_slide_param;
413 uint8_t global_volume_slide_param;
414 uint8_t panning_slide_param;
415 uint8_t portamento_up_param;
416 uint8_t portamento_down_param;
417 uint8_t fine_portamento_up_param;
418 uint8_t fine_portamento_down_param;
419 uint8_t extra_fine_portamento_up_param;
420 uint8_t extra_fine_portamento_down_param;
421 uint8_t tone_portamento_param;
422 float tone_portamento_target_period;
423 uint8_t multi_retrig_param;
424 uint8_t note_delay_param;
425 uint8_t pattern_loop_origin; /* Where to restart a E6y loop */
426 uint8_t pattern_loop_count; /* How many loop passes have been done */
427 bool vibrato_in_progress;
428 jar_xm_waveform_type_t vibrato_waveform;
429 bool vibrato_waveform_retrigger; /* True if a new note retriggers the waveform */
430 uint8_t vibrato_param;
431 uint16_t vibrato_ticks; /* Position in the waveform */
432 float vibrato_note_offset;
433 jar_xm_waveform_type_t tremolo_waveform;
434 bool tremolo_waveform_retrigger;
435 uint8_t tremolo_param;
436 uint8_t tremolo_ticks;
437 float tremolo_volume;
438 uint8_t tremor_param;
439 bool tremor_on;
440
441 uint64_t latest_trigger;
442 bool muted;
443
444 //* These values are updated at the end of each tick, to save a couple of float operations on every generated sample.
445 float target_panning;
446 float target_volume;
447
448 unsigned long frame_count;
449 float end_of_previous_sample_left[jar_xm_SAMPLE_RAMPING_POINTS];
450 float end_of_previous_sample_right[jar_xm_SAMPLE_RAMPING_POINTS];
451 float curr_left;
452 float curr_right;
453
454 float actual_panning;
455 float actual_volume;
456 };
457 typedef struct jar_xm_channel_context_s jar_xm_channel_context_t;
458
459 struct jar_xm_context_s {
460 void* allocated_memory;
461 jar_xm_module_t module;
462 uint32_t rate;
463
464 uint16_t default_tempo; // Number of ticks per row
465 uint16_t default_bpm;
466 float default_global_volume;
467
468 uint16_t tempo; // Number of ticks per row
469 uint16_t bpm;
470 float global_volume;
471
472 float volume_ramp; /* How much is a channel final volume allowed to change per sample; this is used to avoid abrubt volume changes which manifest as "clicks" in the generated sound. */
473 float panning_ramp; /* Same for panning. */
474
475 uint8_t current_table_index;
476 uint8_t current_row;
477 uint16_t current_tick; /* Can go below 255, with high tempo and a pattern delay */
478 float remaining_samples_in_tick;
479 uint64_t generated_samples;
480
481 bool position_jump;
482 bool pattern_break;
483 uint8_t jump_dest;
484 uint8_t jump_row;
485
486 uint16_t extra_ticks; /* Extra ticks to be played before going to the next row - Used for EEy effect */
487
488 uint8_t* row_loop_count; /* Array of size MAX_NUM_ROWS * module_length */
489 uint8_t loop_count;
490 uint8_t max_loop_count;
491
492 jar_xm_channel_context_t* channels;
493 };
494
495 #if JAR_XM_DEFENSIVE
496
497 //** Check the module data for errors/inconsistencies.
498 // * @returns 0 if everything looks OK. Module should be safe to load.
499 int jar_xm_check_sanity_preload(const char*, size_t);
500
501 //** Check a loaded module for errors/inconsistencies.
502 // * @returns 0 if everything looks OK.
503 int jar_xm_check_sanity_postload(jar_xm_context_t*);
504
505 #endif
506
507 //** Get the number of bytes needed to store the module data in a dynamically allocated blank context.
508 // * Things that are dynamically allocated:
509 // * - sample data
510 // * - sample structures in instruments
511 // * - pattern data
512 // * - row loop count arrays
513 // * - pattern structures in module
514 // * - instrument structures in module
515 // * - channel contexts
516 // * - context structure itself
517 // * @returns 0 if everything looks OK.
518 size_t jar_xm_get_memory_needed_for_context(const char*, size_t);
519
520 //** Populate the context from module data.
521 // * @returns pointer to the memory pool
522 char* jar_xm_load_module(jar_xm_context_t*, const char*, size_t, char*);
523
524 int jar_xm_create_context(jar_xm_context_t** ctxp, const char* moddata, uint32_t rate) {
525 return jar_xm_create_context_safe(ctxp, moddata, SIZE_MAX, rate);
526 }
527
528 #define ALIGN(x, b) (((x) + ((b) - 1)) & ~((b) - 1))
529 #define ALIGN_PTR(x, b) (void*)(((uintptr_t)(x) + ((b) - 1)) & ~((b) - 1))
530 int jar_xm_create_context_safe(jar_xm_context_t** ctxp, const char* moddata, size_t moddata_length, uint32_t rate) {
531 #if JAR_XM_DEFENSIVE
532 int ret;
533 #endif
534 size_t bytes_needed;
535 char* mempool;
536 jar_xm_context_t* ctx;
537
538 #if JAR_XM_DEFENSIVE
539 if((ret = jar_xm_check_sanity_preload(moddata, moddata_length))) {
540 DEBUG("jar_xm_check_sanity_preload() returned %i, module is not safe to load", ret);
541 return 1;
542 }
543 #endif
544
545 bytes_needed = jar_xm_get_memory_needed_for_context(moddata, moddata_length);
546 mempool = (char *)JARXM_MALLOC(bytes_needed);
547 if(mempool == NULL && bytes_needed > 0) { /* JARXM_MALLOC() failed, trouble ahead */
548 DEBUG("call to JARXM_MALLOC() failed, returned %p", (void*)mempool);
549 return 2;
550 }
551
552 /* Initialize most of the fields to 0, 0.f, NULL or false depending on type */
553 memset(mempool, 0, bytes_needed);
554
555 ctx = (*ctxp = (jar_xm_context_t *)mempool);
556 ctx->allocated_memory = mempool; /* Keep original pointer for JARXM_FREE() */
557 mempool += sizeof(jar_xm_context_t);
558
559 ctx->rate = rate;
560 mempool = jar_xm_load_module(ctx, moddata, moddata_length, mempool);
561 mempool = (char *)ALIGN_PTR(mempool, 16);
562
563 ctx->channels = (jar_xm_channel_context_t*)mempool;
564 mempool += ctx->module.num_channels * sizeof(jar_xm_channel_context_t);
565 mempool = (char *)ALIGN_PTR(mempool, 16);
566
567 ctx->default_global_volume = 1.f;
568 ctx->global_volume = ctx->default_global_volume;
569
570 ctx->volume_ramp = (1.f / 128.f);
571 ctx->panning_ramp = (1.f / 128.f);
572
573 for(uint8_t i = 0; i < ctx->module.num_channels; ++i) {
574 jar_xm_channel_context_t *ch = ctx->channels + i;
575 ch->ping = true;
576 ch->vibrato_waveform = jar_xm_SINE_WAVEFORM;
577 ch->vibrato_waveform_retrigger = true;
578 ch->tremolo_waveform = jar_xm_SINE_WAVEFORM;
579 ch->tremolo_waveform_retrigger = true;
580 ch->volume = ch->volume_envelope_volume = ch->fadeout_volume = 1.0f;
581 ch->panning = ch->panning_envelope_panning = .5f;
582 ch->actual_volume = .0f;
583 ch->actual_panning = .5f;
584 }
585
586 mempool = (char *)ALIGN_PTR(mempool, 16);
587 ctx->row_loop_count = (uint8_t *)mempool;
588 mempool += MAX_NUM_ROWS * sizeof(uint8_t);
589
590 #if JAR_XM_DEFENSIVE
591 if((ret = jar_xm_check_sanity_postload(ctx))) { DEBUG("jar_xm_check_sanity_postload() returned %i, module is not safe to play", ret);
592 jar_xm_free_context(ctx);
593 return 1;
594 }
595 #endif
596
597 return 0;
598 }
599
600 void jar_xm_free_context(jar_xm_context_t *ctx) {
601 if (ctx != NULL) { JARXM_FREE(ctx->allocated_memory); }
602 }
603
604 void jar_xm_set_max_loop_count(jar_xm_context_t *ctx, uint8_t loopcnt) {
605 ctx->max_loop_count = loopcnt;
606 }
607
608 uint8_t jar_xm_get_loop_count(jar_xm_context_t *ctx) {
609 return ctx->loop_count;
610 }
611
612 bool jar_xm_mute_channel(jar_xm_context_t *ctx, uint16_t channel, bool mute) {
613 bool old = ctx->channels[channel - 1].muted;
614 ctx->channels[channel - 1].muted = mute;
615 return old;
616 }
617
618 bool jar_xm_mute_instrument(jar_xm_context_t *ctx, uint16_t instr, bool mute) {
619 bool old = ctx->module.instruments[instr - 1].muted;
620 ctx->module.instruments[instr - 1].muted = mute;
621 return old;
622 }
623
624 const char* jar_xm_get_module_name(jar_xm_context_t *ctx) {
625 return ctx->module.name;
626 }
627
628 const char* jar_xm_get_tracker_name(jar_xm_context_t *ctx) {
629 return ctx->module.trackername;
630 }
631
632 uint16_t jar_xm_get_number_of_channels(jar_xm_context_t *ctx) {
633 return ctx->module.num_channels;
634 }
635
636 uint16_t jar_xm_get_module_length(jar_xm_context_t *ctx) {
637 return ctx->module.length;
638 }
639
640 uint16_t jar_xm_get_number_of_patterns(jar_xm_context_t *ctx) {
641 return ctx->module.num_patterns;
642 }
643
644 uint16_t jar_xm_get_number_of_rows(jar_xm_context_t *ctx, uint16_t pattern) {
645 return ctx->module.patterns[pattern].num_rows;
646 }
647
648 uint16_t jar_xm_get_number_of_instruments(jar_xm_context_t *ctx) {
649 return ctx->module.num_instruments;
650 }
651
652 uint16_t jar_xm_get_number_of_samples(jar_xm_context_t *ctx, uint16_t instrument) {
653 return ctx->module.instruments[instrument - 1].num_samples;
654 }
655
656 void jar_xm_get_playing_speed(jar_xm_context_t *ctx, uint16_t *bpm, uint16_t *tempo) {
657 if(bpm) *bpm = ctx->bpm;
658 if(tempo) *tempo = ctx->tempo;
659 }
660
661 void jar_xm_get_position(jar_xm_context_t *ctx, uint8_t *pattern_index, uint8_t *pattern, uint8_t *row, uint64_t *samples) {
662 if(pattern_index) *pattern_index = ctx->current_table_index;
663 if(pattern) *pattern = ctx->module.pattern_table[ctx->current_table_index];
664 if(row) *row = ctx->current_row;
665 if(samples) *samples = ctx->generated_samples;
666 }
667
668 uint64_t jar_xm_get_latest_trigger_of_instrument(jar_xm_context_t *ctx, uint16_t instr) {
669 return ctx->module.instruments[instr - 1].latest_trigger;
670 }
671
672 uint64_t jar_xm_get_latest_trigger_of_sample(jar_xm_context_t *ctx, uint16_t instr, uint16_t sample) {
673 return ctx->module.instruments[instr - 1].samples[sample].latest_trigger;
674 }
675
676 uint64_t jar_xm_get_latest_trigger_of_channel(jar_xm_context_t *ctx, uint16_t chn) {
677 return ctx->channels[chn - 1].latest_trigger;
678 }
679
680 //* .xm files are little-endian. (XXX: Are they really?)
681
682 //* Bound reader macros.
683 //* If we attempt to read the buffer out-of-bounds, pretend that the buffer is infinitely padded with zeroes.
684 #define READ_U8(offset) (((offset) < moddata_length) ? (*(uint8_t *)(moddata + (offset))) : 0)
685 #define READ_U16(offset) ((uint16_t)READ_U8(offset) | ((uint16_t)READ_U8((offset) + 1) << 8))
686 #define READ_U32(offset) ((uint32_t)READ_U16(offset) | ((uint32_t)READ_U16((offset) + 2) << 16))
687 #define READ_MEMCPY(ptr, offset, length) memcpy_pad(ptr, length, moddata, moddata_length, offset)
688
689 static void memcpy_pad(void *dst, size_t dst_len, const void *src, size_t src_len, size_t offset) {
690 uint8_t *dst_c = (uint8_t *)dst;
691 const uint8_t *src_c = (uint8_t *)src;
692
693 /* how many bytes can be copied without overrunning `src` */
694 size_t copy_bytes = (src_len >= offset) ? (src_len - offset) : 0;
695 copy_bytes = copy_bytes > dst_len ? dst_len : copy_bytes;
696
697 memcpy(dst_c, src_c + offset, copy_bytes);
698 /* padded bytes */
699 memset(dst_c + copy_bytes, 0, dst_len - copy_bytes);
700 }
701
702 #if JAR_XM_DEFENSIVE
703
704 int jar_xm_check_sanity_preload(const char* module, size_t module_length) {
705 if(module_length < 60) { return 4; }
706 if(memcmp("Extended Module: ", module, 17) != 0) { return 1; }
707 if(module[37] != 0x1A) { return 2; }
708 if(module[59] != 0x01 || module[58] != 0x04) { return 3; } /* Not XM 1.04 */
709 return 0;
710 }
711
712 int jar_xm_check_sanity_postload(jar_xm_context_t* ctx) {
713 /* Check the POT */
714 for(uint8_t i = 0; i < ctx->module.length; ++i) {
715 if(ctx->module.pattern_table[i] >= ctx->module.num_patterns) {
716 if(i+1 == ctx->module.length && ctx->module.length > 1) {
717 DEBUG("trimming invalid POT at pos %X", i);
718 --ctx->module.length;
719 } else {
720 DEBUG("module has invalid POT, pos %X references nonexistent pattern %X", i, ctx->module.pattern_table[i]);
721 return 1;
722 }
723 }
724 }
725
726 return 0;
727 }
728
729 #endif
730
731 size_t jar_xm_get_memory_needed_for_context(const char* moddata, size_t moddata_length) {
732 size_t memory_needed = 0;
733 size_t offset = 60; /* 60 = Skip the first header */
734 uint16_t num_channels;
735 uint16_t num_patterns;
736 uint16_t num_instruments;
737
738 /* Read the module header */
739 num_channels = READ_U16(offset + 8);
740 num_patterns = READ_U16(offset + 10);
741 memory_needed += num_patterns * sizeof(jar_xm_pattern_t);
742 memory_needed = ALIGN(memory_needed, 16);
743 num_instruments = READ_U16(offset + 12);
744 memory_needed += num_instruments * sizeof(jar_xm_instrument_t);
745 memory_needed = ALIGN(memory_needed, 16);
746 memory_needed += MAX_NUM_ROWS * READ_U16(offset + 4) * sizeof(uint8_t); /* Module length */
747
748 offset += READ_U32(offset); /* Header size */
749
750 /* Read pattern headers */
751 for(uint16_t i = 0; i < num_patterns; ++i) {
752 uint16_t num_rows;
753 num_rows = READ_U16(offset + 5);
754 memory_needed += num_rows * num_channels * sizeof(jar_xm_pattern_slot_t);
755 offset += READ_U32(offset) + READ_U16(offset + 7); /* Pattern header length + packed pattern data size */
756 }
757 memory_needed = ALIGN(memory_needed, 16);
758
759 /* Read instrument headers */
760 for(uint16_t i = 0; i < num_instruments; ++i) {
761 uint16_t num_samples;
762 uint32_t sample_header_size = 0;
763 uint32_t sample_size_aggregate = 0;
764 num_samples = READ_U16(offset + 27);
765 memory_needed += num_samples * sizeof(jar_xm_sample_t);
766 if(num_samples > 0) { sample_header_size = READ_U32(offset + 29); }
767
768 offset += READ_U32(offset); /* Instrument header size */
769 for(uint16_t j = 0; j < num_samples; ++j) {
770 uint32_t sample_size;
771 uint8_t flags;
772 sample_size = READ_U32(offset);
773 flags = READ_U8(offset + 14);
774 sample_size_aggregate += sample_size;
775
776 if(flags & (1 << 4)) { /* 16 bit sample */
777 memory_needed += sample_size * (sizeof(float) >> 1);
778 } else { /* 8 bit sample */
779 memory_needed += sample_size * sizeof(float);
780 }
781 offset += sample_header_size;
782 }
783 offset += sample_size_aggregate;
784 }
785
786 memory_needed += num_channels * sizeof(jar_xm_channel_context_t);
787 memory_needed += sizeof(jar_xm_context_t);
788 return memory_needed;
789 }
790
791 char* jar_xm_load_module(jar_xm_context_t* ctx, const char* moddata, size_t moddata_length, char* mempool) {
792 size_t offset = 0;
793 jar_xm_module_t* mod = &(ctx->module);
794
795 /* Read XM header */
796 READ_MEMCPY(mod->name, offset + 17, MODULE_NAME_LENGTH);
797 READ_MEMCPY(mod->trackername, offset + 38, TRACKER_NAME_LENGTH);
798 offset += 60;
799
800 /* Read module header */
801 uint32_t header_size = READ_U32(offset);
802 mod->length = READ_U16(offset + 4);
803 mod->restart_position = READ_U16(offset + 6);
804 mod->num_channels = READ_U16(offset + 8);
805 mod->num_patterns = READ_U16(offset + 10);
806 mod->num_instruments = READ_U16(offset + 12);
807 mod->patterns = (jar_xm_pattern_t*)mempool;
808 mod->linear_interpolation = 1; // Linear interpolation can be set after loading
809 mod->ramping = 1; // ramping can be set after loading
810 mempool += mod->num_patterns * sizeof(jar_xm_pattern_t);
811 mempool = (char *)ALIGN_PTR(mempool, 16);
812 mod->instruments = (jar_xm_instrument_t*)mempool;
813 mempool += mod->num_instruments * sizeof(jar_xm_instrument_t);
814 mempool = (char *)ALIGN_PTR(mempool, 16);
815 uint16_t flags = READ_U32(offset + 14);
816 mod->frequency_type = (flags & (1 << 0)) ? jar_xm_LINEAR_FREQUENCIES : jar_xm_AMIGA_FREQUENCIES;
817 ctx->default_tempo = READ_U16(offset + 16);
818 ctx->default_bpm = READ_U16(offset + 18);
819 ctx->tempo =ctx->default_tempo;
820 ctx->bpm = ctx->default_bpm;
821
822 READ_MEMCPY(mod->pattern_table, offset + 20, PATTERN_ORDER_TABLE_LENGTH);
823 offset += header_size;
824
825 /* Read patterns */
826 for(uint16_t i = 0; i < mod->num_patterns; ++i) {
827 uint16_t packed_patterndata_size = READ_U16(offset + 7);
828 jar_xm_pattern_t* pat = mod->patterns + i;
829 pat->num_rows = READ_U16(offset + 5);
830 pat->slots = (jar_xm_pattern_slot_t*)mempool;
831 mempool += mod->num_channels * pat->num_rows * sizeof(jar_xm_pattern_slot_t);
832 offset += READ_U32(offset); /* Pattern header length */
833
834 if(packed_patterndata_size == 0) { /* No pattern data is present */
835 memset(pat->slots, 0, sizeof(jar_xm_pattern_slot_t) * pat->num_rows * mod->num_channels);
836 } else {
837 /* This isn't your typical for loop */
838 for(uint16_t j = 0, k = 0; j < packed_patterndata_size; ++k) {
839 uint8_t note = READ_U8(offset + j);
840 jar_xm_pattern_slot_t* slot = pat->slots + k;
841 if(note & (1 << 7)) {
842 /* MSB is set, this is a compressed packet */
843 ++j;
844 if(note & (1 << 0)) { /* Note follows */
845 slot->note = READ_U8(offset + j);
846 ++j;
847 } else {
848 slot->note = 0;
849 }
850 if(note & (1 << 1)) { /* Instrument follows */
851 slot->instrument = READ_U8(offset + j);
852 ++j;
853 } else {
854 slot->instrument = 0;
855 }
856 if(note & (1 << 2)) { /* Volume column follows */
857 slot->volume_column = READ_U8(offset + j);
858 ++j;
859 } else {
860 slot->volume_column = 0;
861 }
862 if(note & (1 << 3)) { /* Effect follows */
863 slot->effect_type = READ_U8(offset + j);
864 ++j;
865 } else {
866 slot->effect_type = 0;
867 }
868 if(note & (1 << 4)) { /* Effect parameter follows */
869 slot->effect_param = READ_U8(offset + j);
870 ++j;
871 } else {
872 slot->effect_param = 0;
873 }
874 } else { /* Uncompressed packet */
875 slot->note = note;
876 slot->instrument = READ_U8(offset + j + 1);
877 slot->volume_column = READ_U8(offset + j + 2);
878 slot->effect_type = READ_U8(offset + j + 3);
879 slot->effect_param = READ_U8(offset + j + 4);
880 j += 5;
881 }
882 }
883 }
884
885 offset += packed_patterndata_size;
886 }
887 mempool = (char *)ALIGN_PTR(mempool, 16);
888
889 /* Read instruments */
890 for(uint16_t i = 0; i < ctx->module.num_instruments; ++i) {
891 uint32_t sample_header_size = 0;
892 jar_xm_instrument_t* instr = mod->instruments + i;
893
894 READ_MEMCPY(instr->name, offset + 4, INSTRUMENT_NAME_LENGTH);
895 instr->num_samples = READ_U16(offset + 27);
896
897 if(instr->num_samples > 0) {
898 /* Read extra header properties */
899 sample_header_size = READ_U32(offset + 29);
900 READ_MEMCPY(instr->sample_of_notes, offset + 33, NUM_NOTES);
901
902 instr->volume_envelope.num_points = READ_U8(offset + 225);
903 instr->panning_envelope.num_points = READ_U8(offset + 226);
904
905 for(uint8_t j = 0; j < instr->volume_envelope.num_points; ++j) {
906 instr->volume_envelope.points[j].frame = READ_U16(offset + 129 + 4 * j);
907 instr->volume_envelope.points[j].value = READ_U16(offset + 129 + 4 * j + 2);
908 }
909
910 for(uint8_t j = 0; j < instr->panning_envelope.num_points; ++j) {
911 instr->panning_envelope.points[j].frame = READ_U16(offset + 177 + 4 * j);
912 instr->panning_envelope.points[j].value = READ_U16(offset + 177 + 4 * j + 2);
913 }
914
915 instr->volume_envelope.sustain_point = READ_U8(offset + 227);
916 instr->volume_envelope.loop_start_point = READ_U8(offset + 228);
917 instr->volume_envelope.loop_end_point = READ_U8(offset + 229);
918 instr->panning_envelope.sustain_point = READ_U8(offset + 230);
919 instr->panning_envelope.loop_start_point = READ_U8(offset + 231);
920 instr->panning_envelope.loop_end_point = READ_U8(offset + 232);
921
922 uint8_t flags = READ_U8(offset + 233);
923 instr->volume_envelope.enabled = flags & (1 << 0);
924 instr->volume_envelope.sustain_enabled = flags & (1 << 1);
925 instr->volume_envelope.loop_enabled = flags & (1 << 2);
926
927 flags = READ_U8(offset + 234);
928 instr->panning_envelope.enabled = flags & (1 << 0);
929 instr->panning_envelope.sustain_enabled = flags & (1 << 1);
930 instr->panning_envelope.loop_enabled = flags & (1 << 2);
931 instr->vibrato_type = (jar_xm_waveform_type_t)READ_U8(offset + 235);
932 if(instr->vibrato_type == 2) {
933 instr->vibrato_type = (jar_xm_waveform_type_t)1;
934 } else if(instr->vibrato_type == 1) {
935 instr->vibrato_type = (jar_xm_waveform_type_t)2;
936 }
937 instr->vibrato_sweep = READ_U8(offset + 236);
938 instr->vibrato_depth = READ_U8(offset + 237);
939 instr->vibrato_rate = READ_U8(offset + 238);
940 instr->volume_fadeout = READ_U16(offset + 239);
941 instr->samples = (jar_xm_sample_t*)mempool;
942 mempool += instr->num_samples * sizeof(jar_xm_sample_t);
943 } else {
944 instr->samples = NULL;
945 }
946
947 /* Instrument header size */
948 offset += READ_U32(offset);
949
950 for(int j = 0; j < instr->num_samples; ++j) {
951 /* Read sample header */
952 jar_xm_sample_t* sample = instr->samples + j;
953
954 sample->length = READ_U32(offset);
955 sample->loop_start = READ_U32(offset + 4);
956 sample->loop_length = READ_U32(offset + 8);
957 sample->loop_end = sample->loop_start + sample->loop_length;
958 sample->volume = (float)(READ_U8(offset + 12) << 2) / 256.f;
959 if (sample->volume > 1.0f) {sample->volume = 1.f;};
960 sample->finetune = (int8_t)READ_U8(offset + 13);
961
962 uint8_t flags = READ_U8(offset + 14);
963 switch (flags & 3) {
964 case 2:
965 case 3:
966 sample->loop_type = jar_xm_PING_PONG_LOOP;
967 case 1:
968 sample->loop_type = jar_xm_FORWARD_LOOP;
969 break;
970 default:
971 sample->loop_type = jar_xm_NO_LOOP;
972 break;
973 };
974 sample->bits = (flags & 0x10) ? 16 : 8;
975 sample->stereo = (flags & 0x20) ? 1 : 0;
976 sample->panning = (float)READ_U8(offset + 15) / 255.f;
977 sample->relative_note = (int8_t)READ_U8(offset + 16);
978 READ_MEMCPY(sample->name, 18, SAMPLE_NAME_LENGTH);
979 sample->data = (float *)mempool;
980 if(sample->bits == 16) {
981 /* 16 bit sample */
982 mempool += sample->length * (sizeof(float) >> 1);
983 sample->loop_start >>= 1;
984 sample->loop_length >>= 1;
985 sample->loop_end >>= 1;
986 sample->length >>= 1;
987 } else {
988 /* 8 bit sample */
989 mempool += sample->length * sizeof(float);
990 }
991 // Adjust loop points to reflect half of the reported length (stereo)
992 if (sample->stereo && sample->loop_type != jar_xm_NO_LOOP) {
993 div_t lstart = div(READ_U32(offset + 4), 2);
994 sample->loop_start = lstart.quot;
995 div_t llength = div(READ_U32(offset + 8), 2);
996 sample->loop_length = llength.quot;
997 sample->loop_end = sample->loop_start + sample->loop_length;
998 };
999
1000 offset += sample_header_size;
1001 }
1002
1003 // Read all samples and convert them to float values
1004 for(int j = 0; j < instr->num_samples; ++j) {
1005 /* Read sample data */
1006 jar_xm_sample_t* sample = instr->samples + j;
1007 int length = sample->length;
1008 if (sample->stereo) {
1009 // Since it is stereo, we cut the sample in half (treated as single channel)
1010 div_t result = div(sample->length, 2);
1011 if(sample->bits == 16) {
1012 int16_t v = 0;
1013 for(int k = 0; k < length; ++k) {
1014 if (k == result.quot) { v = 0;};
1015 v = v + (int16_t)READ_U16(offset + (k << 1));
1016 sample->data[k] = (float) v / 32768.f ;//* sign;
1017 if(sample->data[k] < -1.0) {sample->data[k] = -1.0;} else if(sample->data[k] > 1.0) {sample->data[k] = 1.0;};
1018 }
1019 offset += sample->length << 1;
1020 } else {
1021 int8_t v = 0;
1022 for(int k = 0; k < length; ++k) {
1023 if (k == result.quot) { v = 0;};
1024 v = v + (int8_t)READ_U8(offset + k);
1025 sample->data[k] = (float)v / 128.f ;//* sign;
1026 if(sample->data[k] < -1.0) {sample->data[k] = -1.0;} else if(sample->data[k] > 1.0) {sample->data[k] = 1.0;};
1027 }
1028 offset += sample->length;
1029 };
1030 sample->length = result.quot;
1031 } else {
1032 if(sample->bits == 16) {
1033 int16_t v = 0;
1034 for(int k = 0; k < length; ++k) {
1035 v = v + (int16_t)READ_U16(offset + (k << 1));
1036 sample->data[k] = (float) v / 32768.f ;//* sign;
1037 if(sample->data[k] < -1.0) {sample->data[k] = -1.0;} else if(sample->data[k] > 1.0) {sample->data[k] = 1.0;};
1038 }
1039 offset += sample->length << 1;
1040 } else {
1041 int8_t v = 0;
1042 for(int k = 0; k < length; ++k) {
1043 v = v + (int8_t)READ_U8(offset + k);
1044 sample->data[k] = (float)v / 128.f ;//* sign;
1045 if(sample->data[k] < -1.0) {sample->data[k] = -1.0;} else if(sample->data[k] > 1.0) {sample->data[k] = 1.0;};
1046 }
1047 offset += sample->length;
1048 }
1049 }
1050 };
1051 };
1052 return mempool;
1053 };
1054
1055 //-------------------------------------------------------------------------------
1056 //THE FOLLOWING IS FOR PLAYING
1057 static float jar_xm_waveform(jar_xm_waveform_type_t, uint8_t);
1058 static void jar_xm_autovibrato(jar_xm_context_t*, jar_xm_channel_context_t*);
1059 static void jar_xm_vibrato(jar_xm_context_t*, jar_xm_channel_context_t*, uint8_t, uint16_t);
1060 static void jar_xm_tremolo(jar_xm_context_t*, jar_xm_channel_context_t*, uint8_t, uint16_t);
1061 static void jar_xm_arpeggio(jar_xm_context_t*, jar_xm_channel_context_t*, uint8_t, uint16_t);
1062 static void jar_xm_tone_portamento(jar_xm_context_t*, jar_xm_channel_context_t*);
1063 static void jar_xm_pitch_slide(jar_xm_context_t*, jar_xm_channel_context_t*, float);
1064 static void jar_xm_panning_slide(jar_xm_channel_context_t*, uint8_t);
1065 static void jar_xm_volume_slide(jar_xm_channel_context_t*, uint8_t);
1066
1067 static float jar_xm_envelope_lerp(jar_xm_envelope_point_t*, jar_xm_envelope_point_t*, uint16_t);
1068 static void jar_xm_envelope_tick(jar_xm_channel_context_t*, jar_xm_envelope_t*, uint16_t*, float*);
1069 static void jar_xm_envelopes(jar_xm_channel_context_t*);
1070
1071 static float jar_xm_linear_period(float);
1072 static float jar_xm_linear_frequency(float);
1073 static float jar_xm_amiga_period(float);
1074 static float jar_xm_amiga_frequency(float);
1075 static float jar_xm_period(jar_xm_context_t*, float);
1076 static float jar_xm_frequency(jar_xm_context_t*, float, float);
1077 static void jar_xm_update_frequency(jar_xm_context_t*, jar_xm_channel_context_t*);
1078
1079 static void jar_xm_handle_note_and_instrument(jar_xm_context_t*, jar_xm_channel_context_t*, jar_xm_pattern_slot_t*);
1080 static void jar_xm_trigger_note(jar_xm_context_t*, jar_xm_channel_context_t*, unsigned int flags);
1081 static void jar_xm_cut_note(jar_xm_channel_context_t*);
1082 static void jar_xm_key_off(jar_xm_channel_context_t*);
1083
1084 static void jar_xm_post_pattern_change(jar_xm_context_t*);
1085 static void jar_xm_row(jar_xm_context_t*);
1086 static void jar_xm_tick(jar_xm_context_t*);
1087
1088 static void jar_xm_next_of_sample(jar_xm_context_t*, jar_xm_channel_context_t*, int);
1089 static void jar_xm_mixdown(jar_xm_context_t*, float*, float*);
1090
1091 #define jar_xm_TRIGGER_KEEP_VOLUME (1 << 0)
1092 #define jar_xm_TRIGGER_KEEP_PERIOD (1 << 1)
1093 #define jar_xm_TRIGGER_KEEP_SAMPLE_POSITION (1 << 2)
1094
1095 // C-2, C#2, D-2, D#2, E-2, F-2, F#2, G-2, G#2, A-2, A#2, B-2, C-3
1096 static const uint16_t amiga_frequencies[] = { 1712, 1616, 1525, 1440, 1357, 1281, 1209, 1141, 1077, 1017, 961, 907, 856 };
1097
1098 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f
1099 static const float multi_retrig_add[] = { 0.f, -1.f, -2.f, -4.f, -8.f, -16.f, 0.f, 0.f, 0.f, 1.f, 2.f, 4.f, 8.f, 16.f, 0.f, 0.f };
1100
1101 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f
1102 static const float multi_retrig_multiply[] = { 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, .6666667f, .5f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.5f, 2.f };
1103
1104 #define jar_xm_CLAMP_UP1F(vol, limit) do { \
1105 if((vol) > (limit)) (vol) = (limit); \
1106 } while(0)
1107 #define jar_xm_CLAMP_UP(vol) jar_xm_CLAMP_UP1F((vol), 1.f)
1108
1109 #define jar_xm_CLAMP_DOWN1F(vol, limit) do { \
1110 if((vol) < (limit)) (vol) = (limit); \
1111 } while(0)
1112 #define jar_xm_CLAMP_DOWN(vol) jar_xm_CLAMP_DOWN1F((vol), .0f)
1113
1114 #define jar_xm_CLAMP2F(vol, up, down) do { \
1115 if((vol) > (up)) (vol) = (up); \
1116 else if((vol) < (down)) (vol) = (down); \
1117 } while(0)
1118 #define jar_xm_CLAMP(vol) jar_xm_CLAMP2F((vol), 1.f, .0f)
1119
1120 #define jar_xm_SLIDE_TOWARDS(val, goal, incr) do { \
1121 if((val) > (goal)) { \
1122 (val) -= (incr); \
1123 jar_xm_CLAMP_DOWN1F((val), (goal)); \
1124 } else if((val) < (goal)) { \
1125 (val) += (incr); \
1126 jar_xm_CLAMP_UP1F((val), (goal)); \
1127 } \
1128 } while(0)
1129
1130 #define jar_xm_LERP(u, v, t) ((u) + (t) * ((v) - (u)))
1131 #define jar_xm_INVERSE_LERP(u, v, lerp) (((lerp) - (u)) / ((v) - (u)))
1132
1133 #define HAS_TONE_PORTAMENTO(s) ((s)->effect_type == 3 \
1134 || (s)->effect_type == 5 \
1135 || ((s)->volume_column >> 4) == 0xF)
1136 #define HAS_ARPEGGIO(s) ((s)->effect_type == 0 \
1137 && (s)->effect_param != 0)
1138 #define HAS_VIBRATO(s) ((s)->effect_type == 4 \
1139 || (s)->effect_param == 6 \
1140 || ((s)->volume_column >> 4) == 0xB)
1141 #define NOTE_IS_VALID(n) ((n) > 0 && (n) < 97)
1142 #define NOTE_OFF 97
1143
1144 static float jar_xm_waveform(jar_xm_waveform_type_t waveform, uint8_t step) {
1145 static unsigned int next_rand = 24492;
1146 step %= 0x40;
1147 switch(waveform) {
1148 case jar_xm_SINE_WAVEFORM: /* No SIN() table used, direct calculation. */
1149 return -sinf(2.f * 3.141592f * (float)step / (float)0x40);
1150 case jar_xm_RAMP_DOWN_WAVEFORM: /* Ramp down: 1.0f when step = 0; -1.0f when step = 0x40 */
1151 return (float)(0x20 - step) / 0x20;
1152 case jar_xm_SQUARE_WAVEFORM: /* Square with a 50% duty */
1153 return (step >= 0x20) ? 1.f : -1.f;
1154 case jar_xm_RANDOM_WAVEFORM: /* Use the POSIX.1-2001 example, just to be deterministic across different machines */
1155 next_rand = next_rand * 1103515245 + 12345;
1156 return (float)((next_rand >> 16) & 0x7FFF) / (float)0x4000 - 1.f;
1157 case jar_xm_RAMP_UP_WAVEFORM: /* Ramp up: -1.f when step = 0; 1.f when step = 0x40 */
1158 return (float)(step - 0x20) / 0x20;
1159 default:
1160 break;
1161 }
1162 return .0f;
1163 }
1164
1165 static void jar_xm_autovibrato(jar_xm_context_t* ctx, jar_xm_channel_context_t* ch) {
1166 if(ch->instrument == NULL || ch->instrument->vibrato_depth == 0) return;
1167 jar_xm_instrument_t* instr = ch->instrument;
1168 float sweep = 1.f;
1169 if(ch->autovibrato_ticks < instr->vibrato_sweep) { sweep = jar_xm_LERP(0.f, 1.f, (float)ch->autovibrato_ticks / (float)instr->vibrato_sweep); }
1170 unsigned int step = ((ch->autovibrato_ticks++) * instr->vibrato_rate) >> 2;
1171 ch->autovibrato_note_offset = .25f * jar_xm_waveform(instr->vibrato_type, step) * (float)instr->vibrato_depth / (float)0xF * sweep;
1172 jar_xm_update_frequency(ctx, ch);
1173 }
1174
1175 static void jar_xm_vibrato(jar_xm_context_t* ctx, jar_xm_channel_context_t* ch, uint8_t param, uint16_t pos) {
1176 unsigned int step = pos * (param >> 4);
1177 ch->vibrato_note_offset = 2.f * jar_xm_waveform(ch->vibrato_waveform, step) * (float)(param & 0x0F) / (float)0xF;
1178 jar_xm_update_frequency(ctx, ch);
1179 }
1180
1181 static void jar_xm_tremolo(jar_xm_context_t* ctx, jar_xm_channel_context_t* ch, uint8_t param, uint16_t pos) {
1182 unsigned int step = pos * (param >> 4);
1183 ch->tremolo_volume = -1.f * jar_xm_waveform(ch->tremolo_waveform, step) * (float)(param & 0x0F) / (float)0xF;
1184 }
1185
1186 static void jar_xm_arpeggio(jar_xm_context_t* ctx, jar_xm_channel_context_t* ch, uint8_t param, uint16_t tick) {
1187 switch(tick % 3) {
1188 case 0:
1189 ch->arp_in_progress = false;
1190 ch->arp_note_offset = 0;
1191 break;
1192 case 2:
1193 ch->arp_in_progress = true;
1194 ch->arp_note_offset = param >> 4;
1195 break;
1196 case 1:
1197 ch->arp_in_progress = true;
1198 ch->arp_note_offset = param & 0x0F;
1199 break;
1200 }
1201 jar_xm_update_frequency(ctx, ch);
1202 }
1203
1204 static void jar_xm_tone_portamento(jar_xm_context_t* ctx, jar_xm_channel_context_t* ch) {
1205 /* 3xx called without a note, wait until we get an actual target note. */
1206 if(ch->tone_portamento_target_period == 0.f) return; /* no value, exit */
1207 if(ch->period != ch->tone_portamento_target_period) {
1208 jar_xm_SLIDE_TOWARDS(ch->period, ch->tone_portamento_target_period, (ctx->module.frequency_type == jar_xm_LINEAR_FREQUENCIES ? 4.f : 1.f) * ch->tone_portamento_param);
1209 jar_xm_update_frequency(ctx, ch);
1210 }
1211 }
1212
1213 static void jar_xm_pitch_slide(jar_xm_context_t* ctx, jar_xm_channel_context_t* ch, float period_offset) {
1214 /* Don't ask about the 4.f coefficient. I found mention of it nowhere. Found by ear. */
1215 if(ctx->module.frequency_type == jar_xm_LINEAR_FREQUENCIES) {period_offset *= 4.f; }
1216 ch->period += period_offset;
1217 jar_xm_CLAMP_DOWN(ch->period);
1218 /* XXX: upper bound of period ? */
1219 jar_xm_update_frequency(ctx, ch);
1220 }
1221
1222 static void jar_xm_panning_slide(jar_xm_channel_context_t* ch, uint8_t rawval) {
1223 if (rawval & 0xF0) {ch->panning += (float)((rawval & 0xF0 )>> 4) / (float)0xFF;};
1224 if (rawval & 0x0F) {ch->panning -= (float)(rawval & 0x0F) / (float)0xFF;};
1225 };
1226
1227 static void jar_xm_volume_slide(jar_xm_channel_context_t* ch, uint8_t rawval) {
1228 if (rawval & 0xF0) {ch->volume += (float)((rawval & 0xF0) >> 4) / (float)0x40;};
1229 if (rawval & 0x0F) {ch->volume -= (float)(rawval & 0x0F) / (float)0x40;};
1230 };
1231
1232 static float jar_xm_envelope_lerp(jar_xm_envelope_point_t* a, jar_xm_envelope_point_t* b, uint16_t pos) {
1233 /* Linear interpolation between two envelope points */
1234 if(pos <= a->frame) return a->value;
1235 else if(pos >= b->frame) return b->value;
1236 else {
1237 float p = (float)(pos - a->frame) / (float)(b->frame - a->frame);
1238 return a->value * (1 - p) + b->value * p;
1239 }
1240 }
1241
1242 static void jar_xm_post_pattern_change(jar_xm_context_t* ctx) {
1243 /* Loop if necessary */
1244 if(ctx->current_table_index >= ctx->module.length) {
1245 ctx->current_table_index = ctx->module.restart_position;
1246 ctx->tempo =ctx->default_tempo; // reset to file default value
1247 ctx->bpm = ctx->default_bpm; // reset to file default value
1248 ctx->global_volume = ctx->default_global_volume; // reset to file default value
1249 }
1250 }
1251
1252 static float jar_xm_linear_period(float note) {
1253 return 7680.f - note * 64.f;
1254 }
1255
1256 static float jar_xm_linear_frequency(float period) {
1257 return 8363.f * powf(2.f, (4608.f - period) / 768.f);
1258 }
1259
1260 static float jar_xm_amiga_period(float note) {
1261 unsigned int intnote = note;
1262 uint8_t a = intnote % 12;
1263 int8_t octave = note / 12.f - 2;
1264 uint16_t p1 = amiga_frequencies[a], p2 = amiga_frequencies[a + 1];
1265 if(octave > 0) {
1266 p1 >>= octave;
1267 p2 >>= octave;
1268 } else if(octave < 0) {
1269 p1 <<= -octave;
1270 p2 <<= -octave;
1271 }
1272 return jar_xm_LERP(p1, p2, note - intnote);
1273 }
1274
1275 static float jar_xm_amiga_frequency(float period) {
1276 if(period == .0f) return .0f;
1277 return 7093789.2f / (period * 2.f); /* This is the PAL value. (we could use the NTSC value also) */
1278 }
1279
1280 static float jar_xm_period(jar_xm_context_t* ctx, float note) {
1281 switch(ctx->module.frequency_type) {
1282 case jar_xm_LINEAR_FREQUENCIES:
1283 return jar_xm_linear_period(note);
1284 case jar_xm_AMIGA_FREQUENCIES:
1285 return jar_xm_amiga_period(note);
1286 }
1287 return .0f;
1288 }
1289
1290 static float jar_xm_frequency(jar_xm_context_t* ctx, float period, float note_offset) {
1291 switch(ctx->module.frequency_type) {
1292 case jar_xm_LINEAR_FREQUENCIES:
1293 return jar_xm_linear_frequency(period - 64.f * note_offset);
1294 case jar_xm_AMIGA_FREQUENCIES:
1295 if(note_offset == 0) { return jar_xm_amiga_frequency(period); };
1296 int8_t octave;
1297 float note;
1298 uint16_t p1, p2;
1299 uint8_t a = octave = 0;
1300
1301 /* Find the octave of the current period */
1302 if(period > amiga_frequencies[0]) {
1303 --octave;
1304 while(period > (amiga_frequencies[0] << -octave)) --octave;
1305 } else if(period < amiga_frequencies[12]) {
1306 ++octave;
1307 while(period < (amiga_frequencies[12] >> octave)) ++octave;
1308 }
1309
1310 /* Find the smallest note closest to the current period */
1311 for(uint8_t i = 0; i < 12; ++i) {
1312 p1 = amiga_frequencies[i], p2 = amiga_frequencies[i + 1];
1313 if(octave > 0) {
1314 p1 >>= octave;
1315 p2 >>= octave;
1316 } else if(octave < 0) {
1317 p1 <<= (-octave);
1318 p2 <<= (-octave);
1319 }
1320 if(p2 <= period && period <= p1) {
1321 a = i;
1322 break;
1323 }
1324 }
1325 if(JAR_XM_DEBUG && (p1 < period || p2 > period)) { DEBUG("%i <= %f <= %i should hold but doesn't, this is a bug", p2, period, p1); }
1326 note = 12.f * (octave + 2) + a + jar_xm_INVERSE_LERP(p1, p2, period);
1327 return jar_xm_amiga_frequency(jar_xm_amiga_period(note + note_offset));
1328 }
1329
1330 return .0f;
1331 }
1332
1333 static void jar_xm_update_frequency(jar_xm_context_t* ctx, jar_xm_channel_context_t* ch) {
1334 ch->frequency = jar_xm_frequency( ctx, ch->period, (ch->arp_note_offset > 0 ? ch->arp_note_offset : ( ch->vibrato_note_offset + ch->autovibrato_note_offset )) );
1335 ch->step = ch->frequency / ctx->rate;
1336 }
1337
1338 static void jar_xm_handle_note_and_instrument(jar_xm_context_t* ctx, jar_xm_channel_context_t* ch, jar_xm_pattern_slot_t* s) {
1339 jar_xm_module_t* mod = &(ctx->module);
1340 if(s->instrument > 0) {
1341 if(HAS_TONE_PORTAMENTO(ch->current) && ch->instrument != NULL && ch->sample != NULL) { /* Tone portamento in effect */
1342 jar_xm_trigger_note(ctx, ch, jar_xm_TRIGGER_KEEP_PERIOD | jar_xm_TRIGGER_KEEP_SAMPLE_POSITION);
1343 } else if(s->instrument > ctx->module.num_instruments) { /* Invalid instrument, Cut current note */
1344 jar_xm_cut_note(ch);
1345 ch->instrument = NULL;
1346 ch->sample = NULL;
1347 } else {
1348 ch->instrument = ctx->module.instruments + (s->instrument - 1);
1349 if(s->note == 0 && ch->sample != NULL) { /* Ghost instrument, trigger note */
1350 /* Sample position is kept, but envelopes are reset */
1351 jar_xm_trigger_note(ctx, ch, jar_xm_TRIGGER_KEEP_SAMPLE_POSITION);
1352 }
1353 }
1354 }
1355
1356 if(NOTE_IS_VALID(s->note)) {
1357 // note value is s->note -1
1358 jar_xm_instrument_t* instr = ch->instrument;
1359 if(HAS_TONE_PORTAMENTO(ch->current) && instr != NULL && ch->sample != NULL) {
1360 /* Tone portamento in effect */
1361 ch->note = s->note + ch->sample->relative_note + ch->sample->finetune / 128.f - 1.f;
1362 ch->tone_portamento_target_period = jar_xm_period(ctx, ch->note);
1363 } else if(instr == NULL || ch->instrument->num_samples == 0) { /* Issue on instrument */
1364 jar_xm_cut_note(ch);
1365 } else {
1366 if(instr->sample_of_notes[s->note - 1] < instr->num_samples) {
1367 if (mod->ramping) {
1368 for(int i = 0; i < jar_xm_SAMPLE_RAMPING_POINTS; ++i) {
1369 jar_xm_next_of_sample(ctx, ch, i);
1370 }
1371 ch->frame_count = 0;
1372 };
1373 ch->sample = instr->samples + instr->sample_of_notes[s->note - 1];
1374 ch->orig_note = ch->note = s->note + ch->sample->relative_note + ch->sample->finetune / 128.f - 1.f;
1375 if(s->instrument > 0) {
1376 jar_xm_trigger_note(ctx, ch, 0);
1377 } else { /* Ghost note: keep old volume */
1378 jar_xm_trigger_note(ctx, ch, jar_xm_TRIGGER_KEEP_VOLUME);
1379 }
1380 } else {
1381 jar_xm_cut_note(ch);
1382 }
1383 }
1384 } else if(s->note == NOTE_OFF) {
1385 jar_xm_key_off(ch);
1386 }
1387
1388 // Interpret Effect column
1389 switch(s->effect_type) {
1390 case 1: /* 1xx: Portamento up */
1391 if(s->effect_param > 0) { ch->portamento_up_param = s->effect_param; }
1392 break;
1393 case 2: /* 2xx: Portamento down */
1394 if(s->effect_param > 0) { ch->portamento_down_param = s->effect_param; }
1395 break;
1396 case 3: /* 3xx: Tone portamento */
1397 if(s->effect_param > 0) { ch->tone_portamento_param = s->effect_param; }
1398 break;
1399 case 4: /* 4xy: Vibrato */
1400 if(s->effect_param & 0x0F) { ch->vibrato_param = (ch->vibrato_param & 0xF0) | (s->effect_param & 0x0F); } /* Set vibrato depth */
1401 if(s->effect_param >> 4) { ch->vibrato_param = (s->effect_param & 0xF0) | (ch->vibrato_param & 0x0F); } /* Set vibrato speed */
1402 break;
1403 case 5: /* 5xy: Tone portamento + Volume slide */
1404 if(s->effect_param > 0) { ch->volume_slide_param = s->effect_param; }
1405 break;
1406 case 6: /* 6xy: Vibrato + Volume slide */
1407 if(s->effect_param > 0) { ch->volume_slide_param = s->effect_param; }
1408 break;
1409 case 7: /* 7xy: Tremolo */
1410 if(s->effect_param & 0x0F) { ch->tremolo_param = (ch->tremolo_param & 0xF0) | (s->effect_param & 0x0F); } /* Set tremolo depth */
1411 if(s->effect_param >> 4) { ch->tremolo_param = (s->effect_param & 0xF0) | (ch->tremolo_param & 0x0F); } /* Set tremolo speed */
1412 break;
1413 case 8: /* 8xx: Set panning */
1414 ch->panning = (float)s->effect_param / 255.f;
1415 break;
1416 case 9: /* 9xx: Sample offset */
1417 if(ch->sample != 0) { //&& NOTE_IS_VALID(s->note)) {
1418 uint32_t final_offset = s->effect_param << (ch->sample->bits == 16 ? 7 : 8);
1419 switch (ch->sample->loop_type) {
1420 case jar_xm_NO_LOOP:
1421 if(final_offset >= ch->sample->length) { /* Pretend the sample dosen't loop and is done playing */
1422 ch->sample_position = -1;
1423 } else {
1424 ch->sample_position = final_offset;
1425 }
1426 break;
1427 case jar_xm_FORWARD_LOOP:
1428 if (final_offset >= ch->sample->loop_end) {
1429 ch->sample_position -= ch->sample->loop_length;
1430 } else if(final_offset >= ch->sample->length) {
1431 ch->sample_position = ch->sample->loop_start;
1432 } else {
1433 ch->sample_position = final_offset;
1434 }
1435 break;
1436 case jar_xm_PING_PONG_LOOP:
1437 if(final_offset >= ch->sample->loop_end) {
1438 ch->ping = false;
1439 ch->sample_position = (ch->sample->loop_end << 1) - ch->sample_position;
1440 } else if(final_offset >= ch->sample->length) {
1441 ch->ping = false;
1442 ch->sample_position -= ch->sample->length - 1;
1443 } else {
1444 ch->sample_position = final_offset;
1445 };
1446 break;
1447 }
1448 }
1449 break;
1450 case 0xA: /* Axy: Volume slide */
1451 if(s->effect_param > 0) { ch->volume_slide_param = s->effect_param; }
1452 break;
1453 case 0xB: /* Bxx: Position jump */
1454 if(s->effect_param < ctx->module.length) {
1455 ctx->position_jump = true;
1456 ctx->jump_dest = s->effect_param;
1457 }
1458 break;
1459 case 0xC: /* Cxx: Set volume */
1460 ch->volume = (float)((s->effect_param > 0x40) ? 0x40 : s->effect_param) / (float)0x40;
1461 break;
1462 case 0xD: /* Dxx: Pattern break */
1463 /* Jump after playing this line */
1464 ctx->pattern_break = true;
1465 ctx->jump_row = (s->effect_param >> 4) * 10 + (s->effect_param & 0x0F);
1466 break;
1467 case 0xE: /* EXy: Extended command */
1468 switch(s->effect_param >> 4) {
1469 case 1: /* E1y: Fine portamento up */
1470 if(s->effect_param & 0x0F) { ch->fine_portamento_up_param = s->effect_param & 0x0F; }
1471 jar_xm_pitch_slide(ctx, ch, -ch->fine_portamento_up_param);
1472 break;
1473 case 2: /* E2y: Fine portamento down */
1474 if(s->effect_param & 0x0F) { ch->fine_portamento_down_param = s->effect_param & 0x0F; }
1475 jar_xm_pitch_slide(ctx, ch, ch->fine_portamento_down_param);
1476 break;
1477 case 4: /* E4y: Set vibrato control */
1478 ch->vibrato_waveform = (jar_xm_waveform_type_t)(s->effect_param & 3);
1479 ch->vibrato_waveform_retrigger = !((s->effect_param >> 2) & 1);
1480 break;
1481 case 5: /* E5y: Set finetune */
1482 if(NOTE_IS_VALID(ch->current->note) && ch->sample != NULL) {
1483 ch->note = ch->current->note + ch->sample->relative_note + (float)(((s->effect_param & 0x0F) - 8) << 4) / 128.f - 1.f;
1484 ch->period = jar_xm_period(ctx, ch->note);
1485 jar_xm_update_frequency(ctx, ch);
1486 }
1487 break;
1488 case 6: /* E6y: Pattern loop */
1489 if(s->effect_param & 0x0F) {
1490 if((s->effect_param & 0x0F) == ch->pattern_loop_count) { /* Loop is over */
1491 ch->pattern_loop_count = 0;
1492 ctx->position_jump = false;
1493 } else { /* Jump to the beginning of the loop */
1494 ch->pattern_loop_count++;
1495 ctx->position_jump = true;
1496 ctx->jump_row = ch->pattern_loop_origin;
1497 ctx->jump_dest = ctx->current_table_index;
1498 }
1499 } else {
1500 ch->pattern_loop_origin = ctx->current_row; /* Set loop start point */
1501 ctx->jump_row = ch->pattern_loop_origin; /* Replicate FT2 E60 bug */
1502 }
1503 break;
1504 case 7: /* E7y: Set tremolo control */
1505 ch->tremolo_waveform = (jar_xm_waveform_type_t)(s->effect_param & 3);
1506 ch->tremolo_waveform_retrigger = !((s->effect_param >> 2) & 1);
1507 break;
1508 case 0xA: /* EAy: Fine volume slide up */
1509 if(s->effect_param & 0x0F) { ch->fine_volume_slide_param = s->effect_param & 0x0F; }
1510 jar_xm_volume_slide(ch, ch->fine_volume_slide_param << 4);
1511 break;
1512 case 0xB: /* EBy: Fine volume slide down */
1513 if(s->effect_param & 0x0F) { ch->fine_volume_slide_param = s->effect_param & 0x0F; }
1514 jar_xm_volume_slide(ch, ch->fine_volume_slide_param);
1515 break;
1516 case 0xD: /* EDy: Note delay */
1517 /* XXX: figure this out better. EDx triggers the note even when there no note and no instrument. But ED0 acts like like a ghost note, EDx (x != 0) does not. */
1518 if(s->note == 0 && s->instrument == 0) {
1519 unsigned int flags = jar_xm_TRIGGER_KEEP_VOLUME;
1520 if(ch->current->effect_param & 0x0F) {
1521 ch->note = ch->orig_note;
1522 jar_xm_trigger_note(ctx, ch, flags);
1523 } else {
1524 jar_xm_trigger_note(ctx, ch, flags | jar_xm_TRIGGER_KEEP_PERIOD | jar_xm_TRIGGER_KEEP_SAMPLE_POSITION );
1525 }
1526 }
1527 break;
1528
1529 case 0xE: /* EEy: Pattern delay */
1530 ctx->extra_ticks = (ch->current->effect_param & 0x0F) * ctx->tempo;
1531 break;
1532 default:
1533 break;
1534 }
1535 break;
1536
1537 case 0xF: /* Fxx: Set tempo/BPM */
1538 if(s->effect_param > 0) {
1539 if(s->effect_param <= 0x1F) { // First 32 possible values adjust the ticks (goes into tempo)
1540 ctx->tempo = s->effect_param;
1541 } else { //32 and greater values adjust the BPM
1542 ctx->bpm = s->effect_param;
1543 }
1544 }
1545 break;
1546
1547 case 16: /* Gxx: Set global volume */
1548 ctx->global_volume = (float)((s->effect_param > 0x40) ? 0x40 : s->effect_param) / (float)0x40;
1549 break;
1550 case 17: /* Hxy: Global volume slide */
1551 if(s->effect_param > 0) { ch->global_volume_slide_param = s->effect_param; }
1552 break;
1553 case 21: /* Lxx: Set envelope position */
1554 ch->volume_envelope_frame_count = s->effect_param;
1555 ch->panning_envelope_frame_count = s->effect_param;
1556 break;
1557 case 25: /* Pxy: Panning slide */
1558 if(s->effect_param > 0) { ch->panning_slide_param = s->effect_param; }
1559 break;
1560 case 27: /* Rxy: Multi retrig note */
1561 if(s->effect_param > 0) {
1562 if((s->effect_param >> 4) == 0) { /* Keep previous x value */
1563 ch->multi_retrig_param = (ch->multi_retrig_param & 0xF0) | (s->effect_param & 0x0F);
1564 } else {
1565 ch->multi_retrig_param = s->effect_param;
1566 }
1567 }
1568 break;
1569 case 29: /* Txy: Tremor */
1570 if(s->effect_param > 0) { ch->tremor_param = s->effect_param; } /* Tremor x and y params are not separately kept in memory, unlike Rxy */
1571 break;
1572 case 33: /* Xxy: Extra stuff */
1573 switch(s->effect_param >> 4) {
1574 case 1: /* X1y: Extra fine portamento up */
1575 if(s->effect_param & 0x0F) { ch->extra_fine_portamento_up_param = s->effect_param & 0x0F; }
1576 jar_xm_pitch_slide(ctx, ch, -1.0f * ch->extra_fine_portamento_up_param);
1577 break;
1578 case 2: /* X2y: Extra fine portamento down */
1579 if(s->effect_param & 0x0F) { ch->extra_fine_portamento_down_param = s->effect_param & 0x0F; }
1580 jar_xm_pitch_slide(ctx, ch, ch->extra_fine_portamento_down_param);
1581 break;
1582 default:
1583 break;
1584 }
1585 break;
1586 default:
1587 break;
1588 }
1589 }
1590
1591 static void jar_xm_trigger_note(jar_xm_context_t* ctx, jar_xm_channel_context_t* ch, unsigned int flags) {
1592 if (!(flags & jar_xm_TRIGGER_KEEP_SAMPLE_POSITION)) {
1593 ch->sample_position = 0.f;
1594 ch->ping = true;
1595 };
1596
1597 if (!(flags & jar_xm_TRIGGER_KEEP_VOLUME)) {
1598 if(ch->sample != NULL) {
1599 ch->volume = ch->sample->volume;
1600 };
1601 };
1602 ch->panning = ch->sample->panning;
1603 ch->sustained = true;
1604 ch->fadeout_volume = ch->volume_envelope_volume = 1.0f;
1605 ch->panning_envelope_panning = .5f;
1606 ch->volume_envelope_frame_count = ch->panning_envelope_frame_count = 0;
1607 ch->vibrato_note_offset = 0.f;
1608 ch->tremolo_volume = 0.f;
1609 ch->tremor_on = false;
1610 ch->autovibrato_ticks = 0;
1611
1612 if(ch->vibrato_waveform_retrigger) { ch->vibrato_ticks = 0; } /* XXX: should the waveform itself also be reset to sine? */
1613 if(ch->tremolo_waveform_retrigger) { ch->tremolo_ticks = 0; }
1614 if(!(flags & jar_xm_TRIGGER_KEEP_PERIOD)) {
1615 ch->period = jar_xm_period(ctx, ch->note);
1616 jar_xm_update_frequency(ctx, ch);
1617 }
1618 ch->latest_trigger = ctx->generated_samples;
1619 if(ch->instrument != NULL) { ch->instrument->latest_trigger = ctx->generated_samples; }
1620 if(ch->sample != NULL) { ch->sample->latest_trigger = ctx->generated_samples; }
1621 }
1622
1623 static void jar_xm_cut_note(jar_xm_channel_context_t* ch) {
1624 ch->volume = .0f; /* NB: this is not the same as Key Off */
1625 // ch->curr_left = .0f;
1626 // ch->curr_right = .0f;
1627 }
1628
1629 static void jar_xm_key_off(jar_xm_channel_context_t* ch) {
1630 ch->sustained = false; /* Key Off */
1631 if(ch->instrument == NULL || !ch->instrument->volume_envelope.enabled) { jar_xm_cut_note(ch); } /* If no volume envelope is used, also cut the note */
1632 }
1633
1634 static void jar_xm_row(jar_xm_context_t* ctx) {
1635 if(ctx->position_jump) {
1636 ctx->current_table_index = ctx->jump_dest;
1637 ctx->current_row = ctx->jump_row;
1638 ctx->position_jump = false;
1639 ctx->pattern_break = false;
1640 ctx->jump_row = 0;
1641 jar_xm_post_pattern_change(ctx);
1642 } else if(ctx->pattern_break) {
1643 ctx->current_table_index++;
1644 ctx->current_row = ctx->jump_row;
1645 ctx->pattern_break = false;
1646 ctx->jump_row = 0;
1647 jar_xm_post_pattern_change(ctx);
1648 }
1649 jar_xm_pattern_t* cur = ctx->module.patterns + ctx->module.pattern_table[ctx->current_table_index];
1650 bool in_a_loop = false;
1651
1652 /* Read notes information for all channels into temporary pattern slot */
1653 for(uint8_t i = 0; i < ctx->module.num_channels; ++i) {
1654 jar_xm_pattern_slot_t* s = cur->slots + ctx->current_row * ctx->module.num_channels + i;
1655 jar_xm_channel_context_t* ch = ctx->channels + i;
1656 ch->current = s;
1657 // If there is no note delay effect (0xED) then...
1658 if(s->effect_type != 0xE || s->effect_param >> 4 != 0xD) {
1659 //********** Process the channel slot information **********
1660 jar_xm_handle_note_and_instrument(ctx, ch, s);
1661 } else {
1662 // read the note delay information
1663 ch->note_delay_param = s->effect_param & 0x0F;
1664 }
1665 if(!in_a_loop && ch->pattern_loop_count > 0) {
1666 // clarify if in a loop or not
1667 in_a_loop = true;
1668 }
1669 }
1670
1671 if(!in_a_loop) {
1672 /* No E6y loop is in effect (or we are in the first pass) */
1673 ctx->loop_count = (ctx->row_loop_count[MAX_NUM_ROWS * ctx->current_table_index + ctx->current_row]++);
1674 }
1675
1676 /// Move to next row
1677 ctx->current_row++; /* uint8 warning: can increment from 255 to 0, in which case it is still necessary to go the next pattern. */
1678 if (!ctx->position_jump && !ctx->pattern_break && (ctx->current_row >= cur->num_rows || ctx->current_row == 0)) {
1679 ctx->current_table_index++;
1680 ctx->current_row = ctx->jump_row; /* This will be 0 most of the time, except when E60 is used */
1681 ctx->jump_row = 0;
1682 jar_xm_post_pattern_change(ctx);
1683 }
1684 }
1685
1686 static void jar_xm_envelope_tick(jar_xm_channel_context_t *ch, jar_xm_envelope_t *env, uint16_t *counter, float *outval) {
1687 if(env->num_points < 2) {
1688 if(env->num_points == 1) {
1689 *outval = (float)env->points[0].value / (float)0x40;
1690 if(*outval > 1) { *outval = 1; };
1691 } else {;
1692 return;
1693 };
1694 } else {
1695 if(env->loop_enabled) {
1696 uint16_t loop_start = env->points[env->loop_start_point].frame;
1697 uint16_t loop_end = env->points[env->loop_end_point].frame;
1698 uint16_t loop_length = loop_end - loop_start;
1699 if(*counter >= loop_end) { *counter -= loop_length; };
1700 };
1701 for(uint8_t j = 0; j < (env->num_points - 1); ++j) {
1702 if(env->points[j].frame <= *counter && env->points[j+1].frame >= *counter) {
1703 *outval = jar_xm_envelope_lerp(env->points + j, env->points + j + 1, *counter) / (float)0x40;
1704 break;
1705 };
1706 };
1707 /* Make sure it is safe to increment frame count */
1708 if(!ch->sustained || !env->sustain_enabled || *counter != env->points[env->sustain_point].frame) { (*counter)++; };
1709 };
1710 };
1711
1712 static void jar_xm_envelopes(jar_xm_channel_context_t *ch) {
1713 if(ch->instrument != NULL) {
1714 if(ch->instrument->volume_envelope.enabled) {
1715 if(!ch->sustained) {
1716 ch->fadeout_volume -= (float)ch->instrument->volume_fadeout / 65536.f;
1717 jar_xm_CLAMP_DOWN(ch->fadeout_volume);
1718 };
1719 jar_xm_envelope_tick(ch, &(ch->instrument->volume_envelope), &(ch->volume_envelope_frame_count), &(ch->volume_envelope_volume));
1720 };
1721 if(ch->instrument->panning_envelope.enabled) {
1722 jar_xm_envelope_tick(ch, &(ch->instrument->panning_envelope), &(ch->panning_envelope_frame_count), &(ch->panning_envelope_panning));
1723 };
1724 };
1725 };
1726
1727 static void jar_xm_tick(jar_xm_context_t* ctx) {
1728 if(ctx->current_tick == 0) {
1729 jar_xm_row(ctx); // We have processed all ticks and we run the row
1730 }
1731
1732 jar_xm_module_t* mod = &(ctx->module);
1733 for(uint8_t i = 0; i < ctx->module.num_channels; ++i) {
1734 jar_xm_channel_context_t* ch = ctx->channels + i;
1735 jar_xm_envelopes(ch);
1736 jar_xm_autovibrato(ctx, ch);
1737 if(ch->arp_in_progress && !HAS_ARPEGGIO(ch->current)) {
1738 ch->arp_in_progress = false;
1739 ch->arp_note_offset = 0;
1740 jar_xm_update_frequency(ctx, ch);
1741 }
1742 if(ch->vibrato_in_progress && !HAS_VIBRATO(ch->current)) {
1743 ch->vibrato_in_progress = false;
1744 ch->vibrato_note_offset = 0.f;
1745 jar_xm_update_frequency(ctx, ch);
1746 }
1747
1748 // Effects in volumne column mostly handled on a per tick basis
1749 switch(ch->current->volume_column & 0xF0) {
1750 case 0x50: // Checks for volume = 64
1751 if(ch->current->volume_column != 0x50) break;
1752 case 0x10: // Set volume 0-15
1753 case 0x20: // Set volume 16-32
1754 case 0x30: // Set volume 32-48
1755 case 0x40: // Set volume 48-64
1756 ch->volume = (float)(ch->current->volume_column - 16) / 64.0f;
1757 break;
1758 case 0x60: // Volume slide down
1759 jar_xm_volume_slide(ch, ch->current->volume_column & 0x0F);
1760 break;
1761 case 0x70: // Volume slide up
1762 jar_xm_volume_slide(ch, ch->current->volume_column << 4);
1763 break;
1764 case 0x80: // Fine volume slide down
1765 jar_xm_volume_slide(ch, ch->current->volume_column & 0x0F);
1766 break;
1767 case 0x90: // Fine volume slide up
1768 jar_xm_volume_slide(ch, ch->current->volume_column << 4);
1769 break;
1770 case 0xA0: // Set vibrato speed
1771 ch->vibrato_param = (ch->vibrato_param & 0x0F) | ((ch->current->volume_column & 0x0F) << 4);
1772 break;
1773 case 0xB0: // Vibrato
1774 ch->vibrato_in_progress = false;
1775 jar_xm_vibrato(ctx, ch, ch->vibrato_param, ch->vibrato_ticks++);
1776 break;
1777 case 0xC0: // Set panning
1778 if(!ctx->current_tick ) {
1779 ch->panning = (float)(ch->current->volume_column & 0x0F) / 15.0f;
1780 }
1781 break;
1782 case 0xD0: // Panning slide left
1783 jar_xm_panning_slide(ch, ch->current->volume_column & 0x0F);
1784 break;
1785 case 0xE0: // Panning slide right
1786 jar_xm_panning_slide(ch, ch->current->volume_column << 4);
1787 break;
1788 case 0xF0: // Tone portamento
1789 if(!ctx->current_tick ) {
1790 if(ch->current->volume_column & 0x0F) { ch->tone_portamento_param = ((ch->current->volume_column & 0x0F) << 4) | (ch->current->volume_column & 0x0F); }
1791 };
1792 jar_xm_tone_portamento(ctx, ch);
1793 break;
1794 default:
1795 break;
1796 }
1797
1798 // Only some standard effects handled on a per tick basis
1799 // see jar_xm_handle_note_and_instrument for all effects handling on a per row basis
1800 switch(ch->current->effect_type) {
1801 case 0: /* 0xy: Arpeggio */
1802 if(ch->current->effect_param > 0) {
1803 char arp_offset = ctx->tempo % 3;
1804 switch(arp_offset) {
1805 case 2: /* 0 -> x -> 0 -> y -> x -> ... */
1806 if(ctx->current_tick == 1) {
1807 ch->arp_in_progress = true;
1808 ch->arp_note_offset = ch->current->effect_param >> 4;
1809 jar_xm_update_frequency(ctx, ch);
1810 break;
1811 }
1812 /* No break here, this is intended */
1813 case 1: /* 0 -> 0 -> y -> x -> ... */
1814 if(ctx->current_tick == 0) {
1815 ch->arp_in_progress = false;
1816 ch->arp_note_offset = 0;
1817 jar_xm_update_frequency(ctx, ch);
1818 break;
1819 }
1820 /* No break here, this is intended */
1821 case 0: /* 0 -> y -> x -> ... */
1822 jar_xm_arpeggio(ctx, ch, ch->current->effect_param, ctx->current_tick - arp_offset);
1823 default:
1824 break;
1825 }
1826 }
1827 break;
1828
1829 case 1: /* 1xx: Portamento up */
1830 if(ctx->current_tick == 0) break;
1831 jar_xm_pitch_slide(ctx, ch, -ch->portamento_up_param);
1832 break;
1833 case 2: /* 2xx: Portamento down */
1834 if(ctx->current_tick == 0) break;
1835 jar_xm_pitch_slide(ctx, ch, ch->portamento_down_param);
1836 break;
1837 case 3: /* 3xx: Tone portamento */
1838 if(ctx->current_tick == 0) break;
1839 jar_xm_tone_portamento(ctx, ch);
1840 break;
1841 case 4: /* 4xy: Vibrato */
1842 if(ctx->current_tick == 0) break;
1843 ch->vibrato_in_progress = true;
1844 jar_xm_vibrato(ctx, ch, ch->vibrato_param, ch->vibrato_ticks++);
1845 break;
1846 case 5: /* 5xy: Tone portamento + Volume slide */
1847 if(ctx->current_tick == 0) break;
1848 jar_xm_tone_portamento(ctx, ch);
1849 jar_xm_volume_slide(ch, ch->volume_slide_param);
1850 break;
1851 case 6: /* 6xy: Vibrato + Volume slide */
1852 if(ctx->current_tick == 0) break;
1853 ch->vibrato_in_progress = true;
1854 jar_xm_vibrato(ctx, ch, ch->vibrato_param, ch->vibrato_ticks++);
1855 jar_xm_volume_slide(ch, ch->volume_slide_param);
1856 break;
1857 case 7: /* 7xy: Tremolo */
1858 if(ctx->current_tick == 0) break;
1859 jar_xm_tremolo(ctx, ch, ch->tremolo_param, ch->tremolo_ticks++);
1860 break;
1861 case 8: /* 8xy: Set panning */
1862 break;
1863 case 9: /* 9xy: Sample offset */
1864 break;
1865 case 0xA: /* Axy: Volume slide */
1866 if(ctx->current_tick == 0) break;
1867 jar_xm_volume_slide(ch, ch->volume_slide_param);
1868 break;
1869 case 0xE: /* EXy: Extended command */
1870 switch(ch->current->effect_param >> 4) {
1871 case 0x9: /* E9y: Retrigger note */
1872 if(ctx->current_tick != 0 && ch->current->effect_param & 0x0F) {
1873 if(!(ctx->current_tick % (ch->current->effect_param & 0x0F))) {
1874 jar_xm_trigger_note(ctx, ch, 0);
1875 jar_xm_envelopes(ch);
1876 }
1877 }
1878 break;
1879 case 0xC: /* ECy: Note cut */
1880 if((ch->current->effect_param & 0x0F) == ctx->current_tick) {
1881 jar_xm_cut_note(ch);
1882 }
1883 break;
1884 case 0xD: /* EDy: Note delay */
1885 if(ch->note_delay_param == ctx->current_tick) {
1886 jar_xm_handle_note_and_instrument(ctx, ch, ch->current);
1887 jar_xm_envelopes(ch);
1888 }
1889 break;
1890 default:
1891 break;
1892 }
1893 break;
1894 case 16: /* Fxy: Set tempo/BPM */
1895 break;
1896 case 17: /* Hxy: Global volume slide */
1897 if(ctx->current_tick == 0) break;
1898 if((ch->global_volume_slide_param & 0xF0) && (ch->global_volume_slide_param & 0x0F)) { break; }; /* Invalid state */
1899 if(ch->global_volume_slide_param & 0xF0) { /* Global slide up */
1900 float f = (float)(ch->global_volume_slide_param >> 4) / (float)0x40;
1901 ctx->global_volume += f;
1902 jar_xm_CLAMP_UP(ctx->global_volume);
1903 } else { /* Global slide down */
1904 float f = (float)(ch->global_volume_slide_param & 0x0F) / (float)0x40;
1905 ctx->global_volume -= f;
1906 jar_xm_CLAMP_DOWN(ctx->global_volume);
1907 };
1908 break;
1909
1910 case 20: /* Kxx: Key off */
1911 if(ctx->current_tick == ch->current->effect_param) { jar_xm_key_off(ch); };
1912 break;
1913 case 21: /* Lxx: Set envelope position */
1914 break;
1915 case 25: /* Pxy: Panning slide */
1916 if(ctx->current_tick == 0) break;
1917 jar_xm_panning_slide(ch, ch->panning_slide_param);
1918 break;
1919 case 27: /* Rxy: Multi retrig note */
1920 if(ctx->current_tick == 0) break;
1921 if(((ch->multi_retrig_param) & 0x0F) == 0) break;
1922 if((ctx->current_tick % (ch->multi_retrig_param & 0x0F)) == 0) {
1923 float v = ch->volume * multi_retrig_multiply[ch->multi_retrig_param >> 4]
1924 + multi_retrig_add[ch->multi_retrig_param >> 4];
1925 jar_xm_CLAMP(v);
1926 jar_xm_trigger_note(ctx, ch, 0);
1927 ch->volume = v;
1928 };
1929 break;
1930
1931 case 29: /* Txy: Tremor */
1932 if(ctx->current_tick == 0) break;
1933 ch->tremor_on = ( (ctx->current_tick - 1) % ((ch->tremor_param >> 4) + (ch->tremor_param & 0x0F) + 2) > (ch->tremor_param >> 4) );
1934 break;
1935 default:
1936 break;
1937 };
1938
1939 float panning, volume;
1940 panning = ch->panning + (ch->panning_envelope_panning - .5f) * (.5f - fabs(ch->panning - .5f)) * 2.0f;
1941 if(ch->tremor_on) {
1942 volume = .0f;
1943 } else {
1944 volume = ch->volume + ch->tremolo_volume;
1945 jar_xm_CLAMP(volume);
1946 volume *= ch->fadeout_volume * ch->volume_envelope_volume;
1947 };
1948
1949 if (mod->ramping) {
1950 ch->target_panning = panning;
1951 ch->target_volume = volume;
1952 } else {
1953 ch->actual_panning = panning;
1954 ch->actual_volume = volume;
1955 };
1956 };
1957
1958 ctx->current_tick++; // ok so we understand that ticks increment within the row
1959 if(ctx->current_tick >= ctx->tempo + ctx->extra_ticks) {
1960 // This means it reached the end of the row and we reset
1961 ctx->current_tick = 0;
1962 ctx->extra_ticks = 0;
1963 };
1964
1965 // Number of ticks / second = BPM * 0.4
1966 ctx->remaining_samples_in_tick += (float)ctx->rate / ((float)ctx->bpm * 0.4f);
1967 };
1968
1969 static void jar_xm_next_of_sample(jar_xm_context_t* ctx, jar_xm_channel_context_t* ch, int previous) {
1970 jar_xm_module_t* mod = &(ctx->module);
1971
1972 // ch->curr_left = 0.f;
1973 // ch->curr_right = 0.f;
1974 if(ch->instrument == NULL || ch->sample == NULL || ch->sample_position < 0) {
1975 ch->curr_left = 0.f;
1976 ch->curr_right = 0.f;
1977 if (mod->ramping) {
1978 if (ch->frame_count < jar_xm_SAMPLE_RAMPING_POINTS) {
1979 if (previous > -1) {
1980 ch->end_of_previous_sample_left[previous] = jar_xm_LERP(ch->end_of_previous_sample_left[ch->frame_count], ch->curr_left, (float)ch->frame_count / (float)jar_xm_SAMPLE_RAMPING_POINTS);
1981 ch->end_of_previous_sample_right[previous] = jar_xm_LERP(ch->end_of_previous_sample_right[ch->frame_count], ch->curr_right, (float)ch->frame_count / (float)jar_xm_SAMPLE_RAMPING_POINTS);
1982 } else {
1983 ch->curr_left = jar_xm_LERP(ch->end_of_previous_sample_left[ch->frame_count], ch->curr_left, (float)ch->frame_count / (float)jar_xm_SAMPLE_RAMPING_POINTS);
1984 ch->curr_right = jar_xm_LERP(ch->end_of_previous_sample_right[ch->frame_count], ch->curr_right, (float)ch->frame_count / (float)jar_xm_SAMPLE_RAMPING_POINTS);
1985 };
1986 };
1987 };
1988 return;
1989 };
1990 if(ch->sample->length == 0) {
1991 return;
1992 };
1993
1994 float t = 0.f;
1995 uint32_t b = 0;
1996 if(mod->linear_interpolation) {
1997 b = ch->sample_position + 1;
1998 t = ch->sample_position - (uint32_t)ch->sample_position; /* Cheaper than fmodf(., 1.f) */
1999 };
2000
2001 float u_left, u_right;
2002 u_left = ch->sample->data[(uint32_t)ch->sample_position];
2003 if (ch->sample->stereo) {
2004 u_right = ch->sample->data[(uint32_t)ch->sample_position + ch->sample->length];
2005 } else {
2006 u_right = u_left;
2007 };
2008 float v_left = 0.f, v_right = 0.f;
2009 switch(ch->sample->loop_type) {
2010 case jar_xm_NO_LOOP:
2011 if(mod->linear_interpolation) {
2012 v_left = (b < ch->sample->length) ? ch->sample->data[b] : .0f;
2013 if (ch->sample->stereo) {
2014 v_right = (b < ch->sample->length) ? ch->sample->data[b + ch->sample->length] : .0f;
2015 } else {
2016 v_right = v_left;
2017 };
2018 };
2019 ch->sample_position += ch->step;
2020 if(ch->sample_position >= ch->sample->length) { ch->sample_position = -1; } // stop playing this sample
2021 break;
2022 case jar_xm_FORWARD_LOOP:
2023 if(mod->linear_interpolation) {
2024 v_left = ch->sample->data[ (b == ch->sample->loop_end) ? ch->sample->loop_start : b ];
2025 if (ch->sample->stereo) {
2026 v_right = ch->sample->data[ (b == ch->sample->loop_end) ? ch->sample->loop_start + ch->sample->length : b + ch->sample->length];
2027 } else {
2028 v_right = v_left;
2029 };
2030 };
2031 ch->sample_position += ch->step;
2032 if (ch->sample_position >= ch->sample->loop_end) {
2033 ch->sample_position -= ch->sample->loop_length;
2034 };
2035 if(ch->sample_position >= ch->sample->length) {
2036 ch->sample_position = ch->sample->loop_start;
2037 };
2038 break;
2039 case jar_xm_PING_PONG_LOOP:
2040 if(ch->ping) {
2041 if(mod->linear_interpolation) {
2042 v_left = (b >= ch->sample->loop_end) ? ch->sample->data[(uint32_t)ch->sample_position] : ch->sample->data[b];
2043 if (ch->sample->stereo) {
2044 v_right = (b >= ch->sample->loop_end) ? ch->sample->data[(uint32_t)ch->sample_position + ch->sample->length] : ch->sample->data[b + ch->sample->length];
2045 } else {
2046 v_right = v_left;
2047 };
2048 };
2049 ch->sample_position += ch->step;
2050 if(ch->sample_position >= ch->sample->loop_end) {
2051 ch->ping = false;
2052 ch->sample_position = (ch->sample->loop_end << 1) - ch->sample_position;
2053 };
2054 if(ch->sample_position >= ch->sample->length) {
2055 ch->ping = false;
2056 ch->sample_position -= ch->sample->length - 1;
2057 };
2058 } else {
2059 if(mod->linear_interpolation) {
2060 v_left = u_left;
2061 v_right = u_right;
2062 u_left = (b == 1 || b - 2 <= ch->sample->loop_start) ? ch->sample->data[(uint32_t)ch->sample_position] : ch->sample->data[b - 2];
2063 if (ch->sample->stereo) {
2064 u_right = (b == 1 || b - 2 <= ch->sample->loop_start) ? ch->sample->data[(uint32_t)ch->sample_position + ch->sample->length] : ch->sample->data[b + ch->sample->length - 2];
2065 } else {
2066 u_right = u_left;
2067 };
2068 };
2069 ch->sample_position -= ch->step;
2070 if(ch->sample_position <= ch->sample->loop_start) {
2071 ch->ping = true;
2072 ch->sample_position = (ch->sample->loop_start << 1) - ch->sample_position;
2073 };
2074 if (ch->sample_position <= .0f) {
2075 ch->ping = true;
2076 ch->sample_position = .0f;
2077 };
2078 };
2079 break;
2080
2081 default:
2082 v_left = .0f;
2083 v_right = .0f;
2084 break;
2085 };
2086
2087 float endval_left = mod->linear_interpolation ? jar_xm_LERP(u_left, v_left, t) : u_left;
2088 float endval_right = mod->linear_interpolation ? jar_xm_LERP(u_right, v_right, t) : u_right;
2089
2090 if (mod->ramping) {
2091 if(ch->frame_count < jar_xm_SAMPLE_RAMPING_POINTS) {
2092 /* Smoothly transition between old and new sample. */
2093 if (previous > -1) {
2094 ch->end_of_previous_sample_left[previous] = jar_xm_LERP(ch->end_of_previous_sample_left[ch->frame_count], endval_left, (float)ch->frame_count / (float)jar_xm_SAMPLE_RAMPING_POINTS);
2095 ch->end_of_previous_sample_right[previous] = jar_xm_LERP(ch->end_of_previous_sample_right[ch->frame_count], endval_right, (float)ch->frame_count / (float)jar_xm_SAMPLE_RAMPING_POINTS);
2096 } else {
2097 ch->curr_left = jar_xm_LERP(ch->end_of_previous_sample_left[ch->frame_count], endval_left, (float)ch->frame_count / (float)jar_xm_SAMPLE_RAMPING_POINTS);
2098 ch->curr_right = jar_xm_LERP(ch->end_of_previous_sample_right[ch->frame_count], endval_right, (float)ch->frame_count / (float)jar_xm_SAMPLE_RAMPING_POINTS);
2099 };
2100 };
2101 };
2102
2103 if (previous > -1) {
2104 ch->end_of_previous_sample_left[previous] = endval_left;
2105 ch->end_of_previous_sample_right[previous] = endval_right;
2106 } else {
2107 ch->curr_left = endval_left;
2108 ch->curr_right = endval_right;
2109 };
2110 };
2111
2112 // gather all channel audio into stereo float
2113 static void jar_xm_mixdown(jar_xm_context_t* ctx, float* left, float* right) {
2114 jar_xm_module_t* mod = &(ctx->module);
2115
2116 if(ctx->remaining_samples_in_tick <= 0) {
2117 jar_xm_tick(ctx);
2118 };
2119 ctx->remaining_samples_in_tick--;
2120 *left = 0.f;
2121 *right = 0.f;
2122 if(ctx->max_loop_count > 0 && ctx->loop_count > ctx->max_loop_count) { return; }
2123
2124 for(uint8_t i = 0; i < ctx->module.num_channels; ++i) {
2125 jar_xm_channel_context_t* ch = ctx->channels + i;
2126 if(ch->instrument != NULL && ch->sample != NULL && ch->sample_position >= 0) {
2127 jar_xm_next_of_sample(ctx, ch, -1);
2128 if(!ch->muted && !ch->instrument->muted) {
2129 *left += ch->curr_left * ch->actual_volume * (1.f - ch->actual_panning);
2130 *right += ch->curr_right * ch->actual_volume * ch->actual_panning;
2131 };
2132
2133 if (mod->ramping) {
2134 ch->frame_count++;
2135 jar_xm_SLIDE_TOWARDS(ch->actual_volume, ch->target_volume, ctx->volume_ramp);
2136 jar_xm_SLIDE_TOWARDS(ch->actual_panning, ch->target_panning, ctx->panning_ramp);
2137 };
2138 };
2139 };
2140 if (ctx->global_volume != 1.0f) {
2141 *left *= ctx->global_volume;
2142 *right *= ctx->global_volume;
2143 };
2144
2145 // experimental
2146 // float counter = (float)ctx->generated_samples * 0.0001f
2147 // *left = tan(&left + sin(counter));
2148 // *right = tan(&right + cos(counter));
2149
2150 // apply brick wall limiter when audio goes beyond bounderies
2151 if(*left < -1.0) {*left = -1.0;} else if(*left > 1.0) {*left = 1.0;};
2152 if(*right < -1.0) {*right = -1.0;} else if(*right > 1.0) {*right = 1.0;};
2153 };
2154
2155 void jar_xm_generate_samples(jar_xm_context_t* ctx, float* output, size_t numsamples) {
2156 if(ctx && output) {
2157 ctx->generated_samples += numsamples;
2158 for(size_t i = 0; i < numsamples; i++) {
2159 jar_xm_mixdown(ctx, output + (2 * i), output + (2 * i + 1));
2160 };
2161 };
2162 };
2163
2164 uint64_t jar_xm_get_remaining_samples(jar_xm_context_t* ctx) {
2165 uint64_t total = 0;
2166 uint8_t currentLoopCount = jar_xm_get_loop_count(ctx);
2167 jar_xm_set_max_loop_count(ctx, 0);
2168 while(jar_xm_get_loop_count(ctx) == currentLoopCount) {
2169 total += ctx->remaining_samples_in_tick;
2170 ctx->remaining_samples_in_tick = 0;
2171 jar_xm_tick(ctx);
2172 }
2173 ctx->loop_count = currentLoopCount;
2174 return total;
2175 }
2176
2177 //--------------------------------------------
2178 //FILE LOADER - TODO - NEEDS TO BE CLEANED UP
2179 //--------------------------------------------
2180 #undef DEBUG
2181 #define DEBUG(...) do { \
2182 fprintf(stderr, __VA_ARGS__); \
2183 fflush(stderr); \
2184 } while(0)
2185
2186 #define DEBUG_ERR(...) do { \
2187 fprintf(stderr, __VA_ARGS__); \
2188 fflush(stderr); \
2189 } while(0)
2190
2191 #define FATAL(...) do { \
2192 fprintf(stderr, __VA_ARGS__); \
2193 fflush(stderr); \
2194 exit(1); \
2195 } while(0)
2196
2197 #define FATAL_ERR(...) do { \
2198 fprintf(stderr, __VA_ARGS__); \
2199 fflush(stderr); \
2200 exit(1); \
2201 } while(0)
2202
2203
2204 int jar_xm_create_context_from_file(jar_xm_context_t** ctx, uint32_t rate, const char* filename) {
2205 FILE* xmf;
2206 int size;
2207 int ret;
2208
2209 xmf = fopen(filename, "rb");
2210 if(xmf == NULL) {
2211 DEBUG_ERR("Could not open input file");
2212 *ctx = NULL;
2213 return 3;
2214 }
2215
2216 fseek(xmf, 0, SEEK_END);
2217 size = ftell(xmf);
2218 rewind(xmf);
2219 if(size == -1) {
2220 fclose(xmf);
2221 DEBUG_ERR("fseek() failed");
2222 *ctx = NULL;
2223 return 4;
2224 }
2225
2226 char* data = (char *)JARXM_MALLOC(size + 1);
2227 if(!data || fread(data, 1, size, xmf) < size) {
2228 fclose(xmf);
2229 DEBUG_ERR(data ? "fread() failed" : "JARXM_MALLOC() failed");
2230 JARXM_FREE(data);
2231 *ctx = NULL;
2232 return 5;
2233 }
2234
2235 fclose(xmf);
2236
2237 ret = jar_xm_create_context_safe(ctx, data, size, rate);
2238 JARXM_FREE(data);
2239
2240 switch(ret) {
2241 case 0:
2242 break;
2243 case 1: DEBUG("could not create context: module is not sane\n");
2244 *ctx = NULL;
2245 return 1;
2246 break;
2247 case 2: FATAL("could not create context: malloc failed\n");
2248 return 2;
2249 break;
2250 default: FATAL("could not create context: unknown error\n");
2251 return 6;
2252 break;
2253 }
2254
2255 return 0;
2256 }
2257
2258 // not part of the original library
2259 void jar_xm_reset(jar_xm_context_t* ctx) {
2260 for (uint16_t i = 0; i < jar_xm_get_number_of_channels(ctx); i++) {
2261 jar_xm_cut_note(&ctx->channels[i]);
2262 }
2263 ctx->generated_samples = 0;
2264 ctx->current_row = 0;
2265 ctx->current_table_index = 0;
2266 ctx->current_tick = 0;
2267 ctx->tempo =ctx->default_tempo; // reset to file default value
2268 ctx->bpm = ctx->default_bpm; // reset to file default value
2269 ctx->global_volume = ctx->default_global_volume; // reset to file default value
2270 }
2271
2272
2273 void jar_xm_flip_linear_interpolation(jar_xm_context_t* ctx) {
2274 if (ctx->module.linear_interpolation) {
2275 ctx->module.linear_interpolation = 0;
2276 } else {
2277 ctx->module.linear_interpolation = 1;
2278 }
2279 }
2280
2281 void jar_xm_table_jump(jar_xm_context_t* ctx, int table_ptr) {
2282 for (uint16_t i = 0; i < jar_xm_get_number_of_channels(ctx); i++) {
2283 jar_xm_cut_note(&ctx->channels[i]);
2284 }
2285 ctx->current_row = 0;
2286 ctx->current_tick = 0;
2287 if(table_ptr > 0 && table_ptr < ctx->module.length) {
2288 ctx->current_table_index = table_ptr;
2289 ctx->module.restart_position = table_ptr; // The reason to jump is to start a new loop or track
2290 } else {
2291 ctx->current_table_index = 0;
2292 ctx->module.restart_position = 0; // The reason to jump is to start a new loop or track
2293 ctx->tempo =ctx->default_tempo; // reset to file default value
2294 ctx->bpm = ctx->default_bpm; // reset to file default value
2295 ctx->global_volume = ctx->default_global_volume; // reset to file default value
2296 };
2297 }
2298
2299
2300 // TRANSLATE NOTE NUMBER INTO USER VALUE (ie. 1 = C-1, 2 = C#1, 3 = D-1 ... )
2301 const char* xm_note_chr(int number) {
2302 if (number == NOTE_OFF) {
2303 return "==";
2304 };
2305 number = number % 12;
2306 switch(number) {
2307 case 1: return "C-";
2308 case 2: return "C#";
2309 case 3: return "D-";
2310 case 4: return "D#";
2311 case 5: return "E-";
2312 case 6: return "F-";
2313 case 7: return "F#";
2314 case 8: return "G-";
2315 case 9: return "G#";
2316 case 10: return "A-";
2317 case 11: return "A#";
2318 case 12: return "B-";
2319 };
2320 return "??";
2321 };
2322
2323 const char* xm_octave_chr(int number) {
2324 if (number == NOTE_OFF) {
2325 return "=";
2326 };
2327
2328 int number2 = number - number % 12;
2329 int result = floor(number2 / 12) + 1;
2330 switch(result) {
2331 case 1: return "1";
2332 case 2: return "2";
2333 case 3: return "3";
2334 case 4: return "4";
2335 case 5: return "5";
2336 case 6: return "6";
2337 case 7: return "7";
2338 case 8: return "8";
2339 default: return "?"; /* UNKNOWN */
2340 };
2341
2342 };
2343
2344 // TRANSLATE NOTE EFFECT CODE INTO USER VALUE
2345 const char* xm_effect_chr(int fx) {
2346 switch(fx) {
2347 case 0: return "0"; /* ZERO = NO EFFECT */
2348 case 1: return "1"; /* 1xx: Portamento up */
2349 case 2: return "2"; /* 2xx: Portamento down */
2350 case 3: return "3"; /* 3xx: Tone portamento */
2351 case 4: return "4"; /* 4xy: Vibrato */
2352 case 5: return "5"; /* 5xy: Tone portamento + Volume slide */
2353 case 6: return "6"; /* 6xy: Vibrato + Volume slide */
2354 case 7: return "7"; /* 7xy: Tremolo */
2355 case 8: return "8"; /* 8xx: Set panning */
2356 case 9: return "9"; /* 9xx: Sample offset */
2357 case 0xA: return "A";/* Axy: Volume slide */
2358 case 0xB: return "B";/* Bxx: Position jump */
2359 case 0xC: return "C";/* Cxx: Set volume */
2360 case 0xD: return "D";/* Dxx: Pattern break */
2361 case 0xE: return "E";/* EXy: Extended command */
2362 case 0xF: return "F";/* Fxx: Set tempo/BPM */
2363 case 16: return "G"; /* Gxx: Set global volume */
2364 case 17: return "H"; /* Hxy: Global volume slide */
2365 case 21: return "L"; /* Lxx: Set envelope position */
2366 case 25: return "P"; /* Pxy: Panning slide */
2367 case 27: return "R"; /* Rxy: Multi retrig note */
2368 case 29: return "T"; /* Txy: Tremor */
2369 case 33: return "X"; /* Xxy: Extra stuff */
2370 default: return "?"; /* UNKNOWN */
2371 };
2372 }
2373
2374 #ifdef JAR_XM_RAYLIB
2375
2376 #include "raylib.h" // Need RayLib API calls for the DEBUG display
2377
2378 void jar_xm_debug(jar_xm_context_t *ctx) {
2379 int size=40;
2380 int x = 0, y = 0;
2381
2382 // DEBUG VARIABLES
2383 y += size; DrawText(TextFormat("CUR TBL = %i", ctx->current_table_index), x, y, size, WHITE);
2384 y += size; DrawText(TextFormat("CUR PAT = %i", ctx->module.pattern_table[ctx->current_table_index]), x, y, size, WHITE);
2385 y += size; DrawText(TextFormat("POS JMP = %d", ctx->position_jump), x, y, size, WHITE);
2386 y += size; DrawText(TextFormat("JMP DST = %i", ctx->jump_dest), x, y, size, WHITE);
2387 y += size; DrawText(TextFormat("PTN BRK = %d", ctx->pattern_break), x, y, size, WHITE);
2388 y += size; DrawText(TextFormat("CUR ROW = %i", ctx->current_row), x, y, size, WHITE);
2389 y += size; DrawText(TextFormat("JMP ROW = %i", ctx->jump_row), x, y, size, WHITE);
2390 y += size; DrawText(TextFormat("ROW LCT = %i", ctx->row_loop_count), x, y, size, WHITE);
2391 y += size; DrawText(TextFormat("LCT = %i", ctx->loop_count), x, y, size, WHITE);
2392 y += size; DrawText(TextFormat("MAX LCT = %i", ctx->max_loop_count), x, y, size, WHITE);
2393 x = size * 12; y = 0;
2394
2395 y += size; DrawText(TextFormat("CUR TCK = %i", ctx->current_tick), x, y, size, WHITE);
2396 y += size; DrawText(TextFormat("XTR TCK = %i", ctx->extra_ticks), x, y, size, WHITE);
2397 y += size; DrawText(TextFormat("TCK/ROW = %i", ctx->tempo), x, y, size, ORANGE);
2398 y += size; DrawText(TextFormat("SPL TCK = %f", ctx->remaining_samples_in_tick), x, y, size, WHITE);
2399 y += size; DrawText(TextFormat("GEN SPL = %i", ctx->generated_samples), x, y, size, WHITE);
2400 y += size * 7;
2401
2402 x = 0;
2403 size=16;
2404 // TIMELINE OF MODULE
2405 for (int i=0; i < ctx->module.length; i++) {
2406 if (i == ctx->jump_dest) {
2407 if (ctx->position_jump) {
2408 DrawRectangle(i * size * 2, y - size, size * 2, size, GOLD);
2409 } else {
2410 DrawRectangle(i * size * 2, y - size, size * 2, size, BROWN);
2411 };
2412 };
2413 if (i == ctx->current_table_index) {
2414 // DrawText(TextFormat("%02X", ctx->current_tick), i * size * 2, y - size, size, WHITE);
2415 DrawRectangle(i * size * 2, y, size * 2, size, RED);
2416 DrawText(TextFormat("%02X", ctx->current_row), i * size * 2, y - size, size, YELLOW);
2417 } else {
2418 DrawRectangle(i * size * 2, y, size * 2, size, ORANGE);
2419 };
2420 DrawText(TextFormat("%02X", ctx->module.pattern_table[i]), i * size * 2, y, size, WHITE);
2421 };
2422 y += size;
2423
2424 jar_xm_pattern_t* cur = ctx->module.patterns + ctx->module.pattern_table[ctx->current_table_index];
2425
2426 /* DISPLAY CURRENTLY PLAYING PATTERN */
2427
2428 x += 2 * size;
2429 for(uint8_t i = 0; i < ctx->module.num_channels; i++) {
2430 DrawRectangle(x, y, 8 * size, size, PURPLE);
2431 DrawText("N", x, y, size, YELLOW);
2432 DrawText("I", x + size * 2, y, size, YELLOW);
2433 DrawText("V", x + size * 4, y, size, YELLOW);
2434 DrawText("FX", x + size * 6, y, size, YELLOW);
2435 x += 9 * size;
2436 };
2437 x += size;
2438 for (int j=(ctx->current_row - 14); j<(ctx->current_row + 15); j++) {
2439 y += size;
2440 x = 0;
2441 if (j >=0 && j < (cur->num_rows)) {
2442 DrawRectangle(x, y, size * 2, size, BROWN);
2443 DrawText(TextFormat("%02X",j), x, y, size, WHITE);
2444 x += 2 * size;
2445 for(uint8_t i = 0; i < ctx->module.num_channels; i++) {
2446 if (j==(ctx->current_row)) {
2447 DrawRectangle(x, y, 8 * size, size, DARKGREEN);
2448 } else {
2449 DrawRectangle(x, y, 8 * size, size, DARKGRAY);
2450 };
2451 jar_xm_pattern_slot_t *s = cur->slots + j * ctx->module.num_channels + i;
2452 // jar_xm_channel_context_t *ch = ctx->channels + i;
2453 if (s->note > 0) {DrawText(TextFormat("%s%s", xm_note_chr(s->note), xm_octave_chr(s->note) ), x, y, size, WHITE);} else {DrawText("...", x, y, size, GRAY);};
2454 if (s->instrument > 0) {
2455 DrawText(TextFormat("%02X", s->instrument), x + size * 2, y, size, WHITE);
2456 if (s->volume_column == 0) {
2457 DrawText(TextFormat("%02X", 64), x + size * 4, y, size, YELLOW);
2458 };
2459 } else {
2460 DrawText("..", x + size * 2, y, size, GRAY);
2461 if (s->volume_column == 0) {
2462 DrawText("..", x + size * 4, y, size, GRAY);
2463 };
2464 };
2465 if (s->volume_column > 0) {DrawText(TextFormat("%02X", (s->volume_column - 16)), x + size * 4, y, size, WHITE);};
2466 if (s->effect_type > 0 || s->effect_param > 0) {DrawText(TextFormat("%s%02X", xm_effect_chr(s->effect_type), s->effect_param), x + size * 6, y, size, WHITE);};
2467 x += 9 * size;
2468 };
2469 };
2470 };
2471
2472 }
2473 #endif // RayLib extension
2474
2475 #endif//end of JAR_XM_IMPLEMENTATION
2476 //-------------------------------------------------------------------------------
2477
2478 #endif//end of INCLUDE_JAR_XM_H