Logo

index : raylib-jai

---

  • summary
  • about
  • tree
  • log
  • branches
<< path: root/public/raylib-jai.git/html/Raylib/raylib/src/external/jar_xm.h blob: 849fe62f4ae6e46bf4088a2327bcbe792f6c9c5d [raw] [clear marker]

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