# April 18, 2021

## Playing my First MOD With my First MOD Player

### Programming, MOD Player

Today instead of tending to yard work I decided to dive into the next phase if a new project: an Amiga module player. The first milestone has been reached and I’m impressed by how much I’ve already accomplished.

The journey started on Friday when I used some base reference material to read in a standard 4 channel MOD file. Initially I thought I’d detail all those steps are part of this article but I have decided instead to make a multi-part series on the process of creating my own MOD player. In this article I will focus on what happened during the day that allowed me take a skeleton of a library that was able to load a MOD file, and a very simple WAV file writer to render the first MOD I composed.

I spent a fair amount of time on Saturday trying to work out how the Amiga computer played back notes. The reference document was fairly vague and their numbers slightly inaccurate but we’ll save the details for another article. In the end, I learned that the sample period defines the rate at which new words are sent to the analog to digital converter. This determines the samples’ pitch. That part was easy. What I wasn’t sure about was how to convert these values to the sample frequency I was using. I finished Saturday with some understanding of how the rates worked.

Today it was time to make sound. It made sense to me to render the first MOD I ever wrote: Que’s First. While technically Crazzy was the first MOD I wrote, it was not composed so much as randomly thrown together. Que’s First’s melody was composed on a keyboard before it was put into MOD form. So it is really the first MOD I composed.

I started by ignoring periods all together. Somewhere I had read the the samples that make MOD instruments were sampled at 8000 Hz. So I made a program to extract MOD samples and turn them into WAV files setup with a 8000 Hz playback frequency. This is quick but required one conversion. Amiga samples are two’s complement 8-bit signed integers, and was a WAV sample is an 8-bit unsigned integer. So all the samples need to have 0x80 added to them.

//=============================================================================
// Uses: Export a MOD file's samples to WAV files.
// Date: 2021-04-17
// Author: Andrew Que <https://www.DrQue.net/>
//=============================================================================
#include <stdio.h>
#include "waveExport.h"

int main( int argumentCount, char * * arguments )
{
bool isError = ( argumentCount <= 1 );

if ( isError )
fprintf( stderr, "Syntax: %s <MOD file>\n", arguments[ 0 ] );

char const * fileName = arguments[ 1 ];

ModFile modFile;
if ( ! isError )
{
isError |= loadMod( fileName, &modFile );
if ( isError )
fprintf( stderr, "Unable to load file.\n" );
}

if ( ! isError )
{
for ( unsigned sampleIndex = 0; sampleIndex < MOD_NUMBER_OF_SAMPLES; sampleIndex += 1 )
{
if ( modFile.samples[ sampleIndex ].sampleWords > 0 )
{
char fileName[ 14 ];
snprintf( fileName, sizeof( fileName )"%d.WAV", sampleIndex );

unsigned sampleSize = modFile.samples[ sampleIndex ].sampleWords * 2;

for ( unsigned index = 0; index < sampleSize; index += 1 )
modFile.sampleData[ sampleIndex ][ index ] += 0x80;

waveExport
(
fileName,
MOD_SAMPLE_RATE,
(uint8_t*)modFile.sampleData[ sampleIndex ],
sampleSize
);
}
}
}

int returnResult = 0;
if ( isError )
returnResult = -1;

return returnResult;
}

The produced all the samples from my MOD as I expected, and their pitch sounded reasonable. My first pass at playback would simply render the first channel of the pattern. This would work well because for that song, the first channel is the drum beat—a simple kick drum and snare combination. Pitch doesn’t matter too much. This would allow me to get the speed of playback correct.

//=============================================================================
// Uses: Mix the first pattern, channel 0, no pitch, volume, effects, etc.
// Date: 2021-04-18
// Author: Andrew Que <https://www.DrQue.net/>
//=============================================================================
#include <stdio.h>
#include <stdlib.h>
#include "modStrings.h"
#include "amigaConstants.h"
#include "waveExport.h"

enum { FREQUENCY          = 8000 };
enum { TICKS_PER_DIVISION = 6 };
enum { BEAT_PER_MINUTE    = 125 };

#define DIVISIONS_PER_MINUTE      (24.0 * BEAT_PER_MINUTE / TICKS_PER_DIVISION)
#define SAMPLES_PER_DIVISION      (60.0 * FREQUENCY / DIVISIONS_PER_MINUTE)
#define SAMPLES_PER_PATTERN       (SAMPLES_PER_DIVISION * MOD_PATTERN_DIVISIONS)

static ModFile modFile;
static uint8_t * samples;

static unsigned sampleIndex = 0;
static unsigned instrumentIndex = 0;

typedef struct
{
//Sample const * sample;
int instrument;
unsigned period;
unsigned volume;
unsigned index;

} SoundChannel;

static SoundChannel soundChannels[ MOD_CHANNELS ];

void mixDivision( void )
{
for ( unsigned count = 0; count < SAMPLES_PER_DIVISION; count += 1 )
{
SoundChannel * channel = &soundChannels[ 0 ];

samples[ sampleIndex ] = 0x80;
if ( 0xFF != channel->instrument )
{
Sample const * sample = &modFile.samples[ channel->instrument ];
if ( channel->index < ( 2 * sample->sampleWords ) )
{
samples[ sampleIndex ] = modFile.sampleData[ channel->instrument ][ channel->index ];

channel->index += 1;
}
}

instrumentIndex += 1;
sampleIndex += 1;
}
}

void play( void )
{
uint8_t actualPattern = modFile.patternTable[ 0 ];
Pattern * pattern = &modFile.patterns[ actualPattern ];

for ( unsigned channelIndex = 0; channelIndex < MOD_CHANNELS; channelIndex += 1 )
soundChannels[ channelIndex ].instrument = 0xFF;

for ( uint8_t divisionIndex = 0; divisionIndex < MOD_PATTERN_DIVISIONS; divisionIndex += 1 )
{
printf( "Division: %2d - ", divisionIndex );

Channel * channel = &pattern->channels[ divisionIndex ][ 0 ];
if ( pattern->channels[ divisionIndex ][ 0 ].sample )
{
soundChannels[ 0 ].instrument = channel->sample - 2;
soundChannels[ 0 ].period = channel->period;
soundChannels[ 0 ].index = 0;
printf( " %2d %5d %s", channel->sample, channel->period, modFile.samples[ channel->sample - 2 ].name );
}
else
printf( " -- " );

printf( "\n" );

mixDivision();
}

}

int main( int argumentCount, char * * arguments )
{
bool isError = ( argumentCount <= 2 );

if ( isError )
fprintf( stderr, "Syntax: %s <MOD file> <Out wave file>\n", arguments[ 0 ] );

char const * modFileName = arguments[ 1 ];
char const * wavFileName = arguments[ 2 ];

if ( ! isError )
{
isError |= loadMod( modFileName, &modFile );
if ( isError )
fprintf( stderr, "Unable to load file.\n" );
}

if ( ! isError )
{
samples = (uint8_t*)malloc( SAMPLES_PER_PATTERN );
isError = ( NULL == samples );
}

if ( ! isError )
{
play();
isError = waveExport( wavFileName, FREQUENCY, samples, SAMPLES_PER_PATTERN );
}

int returnResult = 0;
if ( isError )
returnResult = -1;

return returnResult;
}

This produced a WAV file that had my bass/snare beat. A good start. The next step was to render all 4 channels. The song begins with a measure of just the beat. There is the kick/snare on the first track, and the second channel which has a rattle shake (like a Maraca). The volume of the shake alternates between full and half which loosely mimics the beads in the rattle sounding at different volumes depending on the side they hit.

//=============================================================================
// Uses: Mixdown of first pattern all 4 channels, no effects, no pitch.
// Date: 2021-04-18
// Author: Andrew Que <https://www.DrQue.net/>
//=============================================================================
#include <stdio.h>
#include <stdlib.h>
#include "modStrings.h"
#include "amigaConstants.h"
#include "waveExport.h"

enum { FREQUENCY          = 8000 };
enum { TICKS_PER_DIVISION = 6 };
enum { BEAT_PER_MINUTE    = 125 };

#define DIVISIONS_PER_MINUTE      (24.0 * BEAT_PER_MINUTE / TICKS_PER_DIVISION)
#define SAMPLES_PER_DIVISION      (60.0 * FREQUENCY / DIVISIONS_PER_MINUTE)
#define SAMPLES_PER_PATTERN       (SAMPLES_PER_DIVISION * MOD_PATTERN_DIVISIONS)

static ModFile modFile;
static uint8_t * samples;

static unsigned sampleIndex = 0;

typedef struct
{
uint8_t instrument;
unsigned period;
unsigned volume;
unsigned index;

} SoundChannel;

static SoundChannel soundChannels[ MOD_CHANNELS ];

void mixDivision( void )
{
for ( unsigned count = 0; count < SAMPLES_PER_DIVISION; count += 1 )
{
uint16_t mix = 0;
for ( unsigned channelIndex = 0; channelIndex < MOD_CHANNELS; channelIndex += 1 )
{
SoundChannel * soundChannel = &soundChannels[ channelIndex ];

int16_t subMix = 0;
if ( 0xFF != soundChannel->instrument )
{
Sample const * sample = &modFile.samples[ soundChannel->instrument ];
if ( soundChannel->index < ( 2 * sample->sampleWords ) )
{
subMix  = modFile.sampleData[ soundChannel->instrument ][ soundChannel->index ];
subMix *= soundChannel->volume;
subMix /= 64;

soundChannel->index += 1;
}
}

mix += subMix;
}

samples[ sampleIndex ] = ( mix / 4 ) + 0x80;

sampleIndex += 1;
}
}

void play( void )
{
uint8_t actualPattern = modFile.patternTable[ 0 ];
Pattern * pattern = &modFile.patterns[ actualPattern ];

for ( unsigned channelIndex = 0; channelIndex < MOD_CHANNELS; channelIndex += 1 )
soundChannels[ channelIndex ].instrument = 0xFF;

for ( uint8_t divisionIndex = 0; divisionIndex < MOD_PATTERN_DIVISIONS; divisionIndex += 1 )
{
printf( "Division: %2d - ", divisionIndex );

for ( unsigned channelIndex = 0; channelIndex < MOD_CHANNELS; channelIndex += 1 )
{
Channel * channel = &pattern->channels[ divisionIndex ][ channelIndex ];
if ( channel->sample )
{
soundChannels[ channelIndex ].instrument = channel->sample - 1;
soundChannels[ channelIndex ].period = channel->period;
soundChannels[ channelIndex ].index = 0;

if ( MOD_EFFECT_TYPE__SET_VOLUME == channel->effectType )
soundChannels[ channelIndex ].volume = channel->effectParameter;
else
soundChannels[ channelIndex ].volume = 64;

printf( " %2d %5d %2d ", channel->sample, channel->period, channel->effectType );
}
else
printf( " -- ----- -- " );
}

printf( "\n" );

mixDivision();
}

}

int main( int argumentCount, char * * arguments )
{
bool isError = ( argumentCount <= 2 );

if ( isError )
fprintf( stderr, "Syntax: %s <MOD file> <Out wave file>\n", arguments[ 0 ] );

char const * modFileName = arguments[ 1 ];
char const * wavFileName = arguments[ 2 ];

if ( ! isError )
{
isError |= loadMod( modFileName, &modFile );
if ( isError )
fprintf( stderr, "Unable to load file.\n" );
}

if ( ! isError )
{
samples = (uint8_t*)malloc( SAMPLES_PER_PATTERN );
isError = ( NULL == samples );
}

if ( ! isError )
{
play();
isError = waveExport( wavFileName, FREQUENCY, samples, SAMPLES_PER_PATTERN );
}

int returnResult = 0;
if ( isError )
returnResult = -1;

return returnResult;
}

This code produced the entire beat which is looped throughout the song. Now it was time for pitch. My work yesterday gave me an equation to convert the note’s period value to the number of samples per second sent to the Digital-to-Analog Converter (DAC). I had a fixed number of samples per second sent to the DAC, so what I needed to calculate was which sample would be getting sent to the DAC at a moment in time. I plan to write in much more detail about how MOD timing works, but for now just understand that songs are broken up in to patterns which consist of 64 divisions in which a note can be played. The speed at which divisions are played is based on the tempo which defaults to 125 beats/minute. There are 4 divisions in a beat. A division is further divided into ticks but other than knowing that the speed calculations assume 6 ticks/division, ticks are not yet used elsewhere.

So I added a function to mix a single division worth of samples. This function has a fixed-point index used to figure out where in the channel’s instrument sample the next output sample comes from. The is some fractional number based on the note’s period. We only use the whole number for the index, but keep the fractional part so it can properly accumulate as playback continues.

I needed to add the calculation to compute the note’s playback increment rate. This is how many counts (including fractional) the instrument sample index changes for each output sample of the mix. Just simple scaling math here. To make it easy on myself I used floating-point for doing the calculation. There are no speed concerns and I was just trying to move quickly so I didn’t feel bad about this.

//=============================================================================
// Uses: Mixdown first pattern with correct pitch.
// Date: 2021-04-18
// Author: Andrew Que <https://www.DrQue.net/>
//=============================================================================
#include <stdio.h>
#include <stdlib.h>
#include "modStrings.h"
#include "amigaConstants.h"
#include "waveExport.h"

enum { FREQUENCY          = 44100 };
enum { TICKS_PER_DIVISION = 6 };
enum { BEAT_PER_MINUTE    = 125 };

#define DIVISIONS_PER_MINUTE      (24.0 * BEAT_PER_MINUTE / TICKS_PER_DIVISION)
#define SAMPLES_PER_DIVISION      (60.0 * FREQUENCY / DIVISIONS_PER_MINUTE)
#define SAMPLES_PER_PATTERN       (SAMPLES_PER_DIVISION * MOD_PATTERN_DIVISIONS)

static ModFile modFile;
static uint8_t * samples;

static unsigned sampleIndex = 0;

enum { INDEX_FIXED_SHIFT = 16 };

typedef struct
{
uint8_t  instrument;
uint16_t period;
uint8_t  volume;
uint32_t index;
uint32_t indexIncrement;

} SoundChannel;

static SoundChannel soundChannels[ MOD_CHANNELS ];

void mixDivision( void )
{
for ( unsigned count = 0; count < SAMPLES_PER_DIVISION; count += 1 )
{
uint16_t mix = 0;
for ( unsigned channelIndex = 0; channelIndex < MOD_CHANNELS; channelIndex += 1 )
{
SoundChannel * soundChannel = &soundChannels[ channelIndex ];

int16_t subMix = 0;
if ( 0xFF != soundChannel->instrument )
{
Sample const * sample = &modFile.samples[ soundChannel->instrument ];
int8_t const * sampleData = modFile.sampleData[ soundChannel->instrument ];
uint16_t index = soundChannel->index >> INDEX_FIXED_SHIFT;
if ( index < ( 2 * sample->sampleWords ) )
{
subMix  = sampleData[ index ];
subMix *= soundChannel->volume;
subMix /= 64;

soundChannel->index += soundChannel->indexIncrement;
}
}

mix += subMix;
}

samples[ sampleIndex ] = ( mix / 4 ) + 0x80;

sampleIndex += 1;
}
}

void play( void )
{
uint8_t actualPattern = modFile.patternTable[ 0 ];
Pattern * pattern = &modFile.patterns[ actualPattern ];

for ( unsigned channelIndex = 0; channelIndex < MOD_CHANNELS; channelIndex += 1 )
soundChannels[ channelIndex ].instrument = 0xFF;

for ( uint8_t divisionIndex = 0; divisionIndex < MOD_PATTERN_DIVISIONS; divisionIndex += 1 )
{
printf( "Division: %2d - ", divisionIndex );

for ( unsigned channelIndex = 0; channelIndex < MOD_CHANNELS; channelIndex += 1 )
{
Channel * channel = &pattern->channels[ divisionIndex ][ channelIndex ];
if ( channel->sample )
{
soundChannels[ channelIndex ].instrument = channel->sample - 1;

soundChannels[ channelIndex ].index = 0;

// Number of samples/second.
double sendRate =
(double)AMIGA_NTSC_CRYSTAL / ( channel->period * AMIGA_PAULA_PERIOD_DIVIDE );

double sampleRate = sendRate / FREQUENCY;

soundChannels[ channelIndex ].indexIncrement = sampleRate * ( 1 << INDEX_FIXED_SHIFT );
//soundChannels[ channelIndex ].indexIncrement = 1 << INDEX_FIXED_SHIFT;

if ( MOD_EFFECT_TYPE__SET_VOLUME == channel->effectType )
soundChannels[ channelIndex ].volume = channel->effectParameter;
else
soundChannels[ channelIndex ].volume = 64;

printf( " %2d %5d %2d %7.3f ", channel->sample, channel->period, channel->effectType, sendRate );
}
else
printf( " -- ----- -- ------- " );
}

printf( "\n" );

mixDivision();
}

}

int main( int argumentCount, char * * arguments )
{
bool isError = ( argumentCount <= 2 );

if ( isError )
fprintf( stderr, "Syntax: %s <MOD file> <Out wave file>\n", arguments[ 0 ] );

char const * modFileName = arguments[ 1 ];
char const * wavFileName = arguments[ 2 ];

if ( ! isError )
{
isError |= loadMod( modFileName, &modFile );
if ( isError )
fprintf( stderr, "Unable to load file.\n" );
}

if ( ! isError )
{
samples = (uint8_t*)malloc( SAMPLES_PER_PATTERN );
isError = ( NULL == samples );
}

if ( ! isError )
{
play();
isError = waveExport( wavFileName, FREQUENCY, samples, SAMPLES_PER_PATTERN );
}

int returnResult = 0;
if ( isError )
returnResult = -1;

return returnResult;
}

The results: I had a full playback of my first module that was mostly accurate. For my next iteration I addressed two issues: the pattern break effect and volume slides. In order to do this I needed to address ticks. As briefly stated, each division is further broken into a number of ticks. Effects are applied on the tick level. For volume slide, the amount the volume changes is applied each tick.

Although I didn’t need it for this song, I also added instrument loops. While rendering my own song, I was also rendering a classic: Bjorn Lynne’s 12th Warrior. I wasn’t worried about getting everything correct—just pieces—and did get instrument loops working.

//=============================================================================
// Uses: Mixdown first pattern with correct pitch.
// Date: 2021-04-18
// Author: Andrew Que <https://www.DrQue.net/>
//=============================================================================
#include <stdio.h>
#include <stdlib.h>
#include "modStrings.h"
#include "amigaConstants.h"
#include "waveExport.h"

enum { FREQUENCY          = 8000 };
enum { TICKS_PER_DIVISION = 6 };
enum { BEAT_PER_MINUTE    = 125 };

#define DIVISIONS_PER_MINUTE      (24 * BEAT_PER_MINUTE / TICKS_PER_DIVISION)
#define SAMPLES_PER_DIVISION      (60 * FREQUENCY / DIVISIONS_PER_MINUTE)
#define SAMPLES_PER_TICK          (SAMPLES_PER_DIVISION / TICKS_PER_DIVISION)
#define SAMPLES_PER_PATTERN       (SAMPLES_PER_DIVISION * MOD_PATTERN_DIVISIONS)

static uint8_t * samples;

static unsigned sampleIndex = 0;

enum { INDEX_FIXED_SHIFT = 16 };

typedef struct
{
uint8_t  instrument;
uint16_t period;
uint8_t  volume;
int8_t volumeSlide;
uint32_t index;
uint32_t indexIncrement;
uint32_t sampleLength;

} SoundChannel;

static SoundChannel soundChannels[ MOD_CHANNELS ];

void mixTick( ModFile const * modFile )
{
for ( unsigned count = 0; count < SAMPLES_PER_TICK; count += 1 )
{
uint16_t mix = 0;
for ( unsigned channelIndex = 0; channelIndex < MOD_CHANNELS; channelIndex += 1 )
{
SoundChannel * soundChannel = &soundChannels[ channelIndex ];

int16_t subMix = 0;
if ( 0xFF != soundChannel->instrument )
{
Sample const * sample = &modFile->samples[ soundChannel->instrument ];
int8_t const * sampleData = modFile->sampleData[ soundChannel->instrument ];

uint16_t sampleLength = 2 * sample->sampleWords;
uint16_t index = soundChannel->index >> INDEX_FIXED_SHIFT;

if ( ( index > sampleLength )
&& ( sample->repeatLength > 0 ) )
{
uint16_t offset = 2 * sample->repeatOffset;
uint16_t length = 2 * sample->repeatLength;
index = ( index - sampleLength ) + offset;// - offset - length;
soundChannel->index = index / 2;
}

if ( index < sampleLength )
{
subMix  = sampleData[ index ];
subMix *= soundChannel->volume;
subMix /= 64;

soundChannel->index += soundChannel->indexIncrement;
}

}

mix += subMix;
}

samples[ sampleIndex ] = ( mix / 4 ) + 0x80;

sampleIndex += 1;
}
}

void play( ModFile const * modFile )
{
for ( unsigned channelIndex = 0; channelIndex < MOD_CHANNELS; channelIndex += 1 )
soundChannels[ channelIndex ].instrument = 0xFF;

for ( uint8_t patternIndex = 0; patternIndex < modFile->numberOfPatterns; patternIndex += 1 )
{
uint8_t actualPattern = modFile->patternTable[ patternIndex ];
Pattern const * pattern = &modFile->patterns[ actualPattern ];

uint8_t divisionIndex = 0;
uint8_t nextDivisionIndex = 1;
while ( divisionIndex < MOD_PATTERN_DIVISIONS )
{
printf( "%3d/%2d: ", patternIndex, divisionIndex );

// Loop through each channel.
for ( unsigned channelIndex = 0; channelIndex < MOD_CHANNELS; channelIndex += 1 )
{
// The active channel.
Channel const * channel = &pattern->channels[ divisionIndex ][ channelIndex ];

// If there is an instrument selected...
if ( channel->sample )
{
soundChannels[ channelIndex ].instrument = channel->sample - 1;
soundChannels[ channelIndex ].index = 0;

// Number of samples/second.
double sendRate =
(double)AMIGA_NTSC_CRYSTAL / ( channel->period * AMIGA_PAULA_PERIOD_DIVIDE );

double sampleRate = sendRate / FREQUENCY;

soundChannels[ channelIndex ].indexIncrement = sampleRate * ( 1 << INDEX_FIXED_SHIFT );

// Default volume.
soundChannels[ channelIndex ].volume = 64;
}

soundChannels[ channelIndex ].volumeSlide = 0;
if ( MOD_EFFECT_TYPE__VOLUME_SLIDE == channel->effectType )
{
int8_t up   = ( channel->effectParameter & 0xF0 ) >> 4;
int8_t down = ( channel->effectParameter & 0x0F ) >> 0;
if ( ( 0 != up ) && ( 0 == down ) )
soundChannels[ channelIndex ].volumeSlide = up;
else
if ( ( 0 == up ) && ( 0 != down ) )
soundChannels[ channelIndex ].volumeSlide = -down;
}

if ( MOD_EFFECT_TYPE__SET_VOLUME == channel->effectType )
soundChannels[ channelIndex ].volume = channel->effectParameter;

if ( ( MOD_EFFECT_TYPE__PATTERN_BREAK == channel->effectType )
|| ( MOD_EFFECT_TYPE__POSITION_JUMP == channel->effectType ) )
{
nextDivisionIndex = MOD_PATTERN_DIVISIONS;
}

//------------
// Print out
//------------

char const * effectName = "";
char effectParameter[ 4 ] = "   ";
if ( MOD_EFFECT_TYPE__NONE != channel->effectType )
{
effectName = MOD_EFFECT_NAMES[ channel->effectType ];
snprintf( effectParameter, sizeof( effectParameter )"%03X", channel->effectParameter & 0xFFF );
}

char const * note = "";
char sample[ 4 ] = "   ";
if ( 0 != channel->sample )
{
note = getNoteName( channel->period );
snprintf( sample, sizeof( sample )"%3d", channel->sample );
}

printf
(
"| %s %3s %2d %-10s %s %3i ",
sample,
note,
channel->effectType,
effectName,
effectParameter,
soundChannels[ channelIndex ].volumeSlide
);

//------------

}

for ( uint8_t tickCount = 0; tickCount < TICKS_PER_DIVISION; tickCount += 1 )
{
mixTick( modFile );

for ( unsigned channelIndex = 0; channelIndex < MOD_CHANNELS; channelIndex += 1 )
{
SoundChannel * soundChannel = &soundChannels[ channelIndex ];
if ( 0 != soundChannels[ channelIndex ].volumeSlide )
{
int8_t newVolume = soundChannel->volume;
newVolume += soundChannels[ channelIndex ].volumeSlide;

if ( newVolume < 0 )
newVolume = 0;

if ( newVolume > MOD_MAX_VOLUME )
newVolume = MOD_MAX_VOLUME;

//printf( "\t%d %i %i %i\n", channelIndex, soundChannels[ channelIndex ].volumeSlide, soundChannel->volume, newVolume );

soundChannel->volume = newVolume;
}
}
}

divisionIndex = nextDivisionIndex;
nextDivisionIndex = divisionIndex + 1;

printf( "\n" );

}
}
}

int main( int argumentCount, char * * arguments )
{
bool isError = ( argumentCount <= 2 );

if ( isError )
fprintf( stderr, "Syntax: %s <MOD file> <Out wave file>\n", arguments[ 0 ] );

char const * modFileName = arguments[ 1 ];
char const * wavFileName = arguments[ 2 ];

ModFile modFile;
if ( ! isError )
{
isError |= loadMod( modFileName, &modFile );
if ( isError )
fprintf( stderr, "Unable to load file.\n" );
}

printf
(
"DIVISIONS_PER_MINUTE..: %d\n"
"SAMPLES_PER_DIVISION..: %d\n"
"SAMPLES_PER_TICK......: %d\n"
"SAMPLES_PER_PATTERN...: %d\n",
DIVISIONS_PER_MINUTE,
SAMPLES_PER_DIVISION,
SAMPLES_PER_TICK,
SAMPLES_PER_PATTERN
);

if ( ! isError )
{
samples = (uint8_t*)malloc( SAMPLES_PER_PATTERN * modFile.numberOfPatterns );
isError = ( NULL == samples );
}

if ( ! isError )
{
play( &modFile );
isError = waveExport( wavFileName, FREQUENCY, samples, sampleIndex );
}

int returnResult = 0;
if ( isError )
returnResult = -1;

return returnResult;
}

That was it. With the volume slide functional I was able to fully render my very first Amiga module. For the first time I am releasing this MOD and my first rendering of it. Be aware, I was 13 or 14 years old when I composed this song and was no (and am still not a) musical prodigy.

The song itself was composed around 1991 or 1992 on a Yamaha Protasound PSS-140 keyboard acquired from a garage sale, and I tracked this MOD sometime in between mid and late 1993. 28 years latter, I am able to render it into a playable waveform using only my own software.

All the code posted here was written in a full day of work, based on code written over bits of the prior 4 days. I typically don’t release uncleaned code, but this is kind of a unique project in its ability to show developing code.

# April 19, 2021

## Adding Arpeggio and Portamento to MOD Player

### Programming, MOD Player

//=============================================================================
// Uses:
// Date: 2021-04-19
// Author: Andrew Que <https://www.DrQue.net/>
//=============================================================================
#include <stdio.h>
#include <stdlib.h>
#include "modStrings.h"
#include "amigaConstants.h"
#include "waveExport.h"

enum { FREQUENCY          = 21276 };
enum { TICKS_PER_DIVISION = 6 };
enum { BEAT_PER_MINUTE    = 125 };

static bool const printNotes = true;

// Number of samples in the longest possible division.
#define LONGEST_DIVISION_SAMPLES  ( ( 60L * FREQUENCY * MOD_PATTERN_DIVISIONS * MOD_SPEED_CHANGEOVER ) \
/ ( 24 * ( MOD_SPEED_CHANGEOVER + 1 ) ) )

enum { INDEX_FIXED_SHIFT = 8 };

typedef struct
{
// Which instrument is sounding. 0xFF for none.
uint8_t instrument;

// Period (i.e. note).
uint16_t period;
MOD_Note note;

uint16_t arpeggioA;
uint16_t arpeggioB;
uint8_t arpeggioIndex;

// Volume of channel.
uint8_t volume;

// Volume slide (+/- slide per tick).
int8_t volumeSlide;

// Pitch slide (+/- periods per tick).
int16_t pitchSlide;

// For sliding to a new note, this is the target note.
uint16_t slideTarget;

// Current index into sample.
uint32_t index;

// Fixed-point increment each output sample added.
uint32_t indexIncrement;

// End of sample (used for looping).
uint32_t sampleEnd;

} SoundChannel;

typedef struct
{
SoundChannel soundChannels[ MOD_CHANNELS ];

uint8_t * samples;
unsigned sampleIndex;
unsigned numberOfSamples;

unsigned samplesPerTick;
unsigned bpm;
unsigned ticksPerDivision;

} SongPlaypack;

//-----------------------------------------------------------------------------
// Uses:
//   Process a single division tick.
// Input:
//   songPlayback - Song song playback.
//   modFile - Loaded MOD file.
// Output:
//   *songPlayback is modified.
//   songPlayback->samples - New samples are added here.
//   songPlayback->sampleIndex - Index into `samples`.
//-----------------------------------------------------------------------------
static void mixTick( SongPlaypack * songPlayback, ModFile const * modFile )
{
for ( unsigned count = 0; count < songPlayback->samplesPerTick; count += 1 )
{
uint16_t mix = 0;
for ( unsigned channelIndex = 0; channelIndex < MOD_CHANNELS; channelIndex += 1 )
{
SoundChannel * soundChannel = &songPlayback->soundChannels[ channelIndex ];

int16_t subMix = 0;
if ( 0xFF != soundChannel->instrument )
{
Sample const * sample = &modFile->samples[ soundChannel->instrument ];
int8_t const * sampleData = modFile->sampleData[ soundChannel->instrument ];

uint32_t sampleEnd = 2 * soundChannel->sampleEnd;
uint32_t index = soundChannel->index >> INDEX_FIXED_SHIFT;

// If this is a repeating sample and we've passed the repeat point...
if ( ( index >= sampleEnd )
&& ( sample->repeatLength > 1 ) )
{
index = 2 * sample->repeatOffset;

// Save new index.
soundChannel->index = index << INDEX_FIXED_SHIFT;

// Change end point.
soundChannel->sampleEnd = sample->repeatLength + sample->repeatOffset;
if ( soundChannel->sampleEnd > sample->sampleWords )
// Invalid configuration--the repeat end is greater than the
// actual end.  So use the actual end.
soundChannel->sampleEnd = sample->sampleWords;
}

if ( index < sampleEnd )
{
subMix  = sampleData[ index ];
subMix *= soundChannel->volume;
subMix /= 64;

soundChannel->index += soundChannel->indexIncrement;
}

}

mix += subMix;
}

if ( songPlayback->sampleIndex < songPlayback->numberOfSamples )
songPlayback->samples[ songPlayback->sampleIndex ] = ( mix / 4 ) + 0x80;

songPlayback->sampleIndex += 1;
}
}

//-----------------------------------------------------------------------------
// Uses:
//   Compute new speed settings.
// Input:
//   songPlayback - Instance of `SongPlaypack` to modify.
//   ticksPerDivision - New ticks/division.
//   bpm - New beats/minute.
// Output:
//   Results are stored in:
//     songPlayback->ticksPerDivision
//     songPlayback->bpm
//     songPlayback->samplesPerTick
//-----------------------------------------------------------------------------
static inline void calculationNewSpeed
(
SongPlaypack * songPlayback,
unsigned ticksPerDivision,
unsigned bpm
)
{
songPlayback->ticksPerDivision = ticksPerDivision;
songPlayback->bpm              = bpm;
songPlayback->samplesPerTick   = 60 * FREQUENCY / ( 24 * bpm );
}

//-----------------------------------------------------------------------------
// Uses:
//   Mix down song.
//-----------------------------------------------------------------------------
bool modToWave( char const * const fileName, ModFile const * modFile )
{
bool isError = false;

unsigned numberOfSamples = LONGEST_DIVISION_SAMPLES;
uint8_t * samples = malloc( LONGEST_DIVISION_SAMPLES );

isError = ( NULL == samples );

SongPlaypack songPlayback;
songPlayback.samples = samples;
songPlayback.numberOfSamples  = numberOfSamples;
calculationNewSpeed( &songPlayback, TICKS_PER_DIVISION, BEAT_PER_MINUTE );

for ( unsigned channelIndex = 0; channelIndex < MOD_CHANNELS; channelIndex += 1 )
{
SoundChannel * soundChannel = &songPlayback.soundChannels[ channelIndex ];
soundChannel->instrument = 0xFF;
soundChannel->pitchSlide = 0;
soundChannel->volumeSlide = 0;
soundChannel->arpeggioA = 0;
soundChannel->arpeggioB = 0;
}

for ( uint8_t patternIndex = 0; patternIndex < modFile->numberOfPatterns; patternIndex += 1 )
//uint8_t patternIndex = 4;
{
songPlayback.sampleIndex = 0;

uint8_t actualPattern = modFile->patternTable[ patternIndex ];
Pattern const * pattern = &modFile->patterns[ actualPattern ];

uint8_t divisionIndex = 0;
uint8_t nextDivisionIndex = 1;
while ( divisionIndex < MOD_PATTERN_DIVISIONS )
{
if ( printNotes )
printf( "%2d/%02X: ", patternIndex, divisionIndex );

// Loop through each channel.
for ( unsigned channelIndex = 0; channelIndex < MOD_CHANNELS; channelIndex += 1 )
//unsigned channelIndex = 3;
{
// The active channel.
Channel const * channel = &pattern->channels[ divisionIndex ][ channelIndex ];
SoundChannel * soundChannel = &songPlayback.soundChannels[ channelIndex ];

// If there is an instrument selected...
if ( channel->period )
{
// Set the instrument.  If it is not specified, just use the last one.
if ( 0 != channel->sample )
soundChannel->instrument = channel->sample - 1;

soundChannel->index = 0;

Sample const * sample = &modFile->samples[ soundChannel->instrument ];
soundChannel->sampleEnd = sample->sampleWords;
soundChannel->note = channel->note;

if ( MOD_EFFECT_TYPE__SLIDE_TO_NOTE == channel->effectType )
{
soundChannel->slideTarget = channel->period;

// Sliding up or down?
if ( channel->period < soundChannel->period )
soundChannel->pitchSlide = (int16_t)channel->effectParameter;
else
soundChannel->pitchSlide = -(int16_t)channel->effectParameter;
}
else
soundChannel->period = channel->period;

// Default volume.
soundChannel->volume = sample->volume;
}

soundChannel->arpeggioA = 0;
soundChannel->arpeggioB = 0;
soundChannel->arpeggioIndex = 0;
if ( MOD_EFFECT_TYPE__ARPEGGIO == channel->effectType )
{
MOD_Note noteA   = soundChannel->note + ( ( channel->effectParameter >> 4 ) & 0x0F );
uint16_t periodA = getPeriodByNote( noteA );
soundChannel->arpeggioA = periodA - soundChannel->period;

MOD_Note noteB   = soundChannel->note + ( ( channel->effectParameter >> 0 ) & 0x0F );
uint16_t periodB = getPeriodByNote( noteB );
soundChannel->arpeggioB = periodB - soundChannel->period;
}

if ( MOD_EFFECT_TYPE__SET_SPEED == channel->effectType )
{
if ( channel->effectParameter <= MOD_SPEED_CHANGEOVER )
songPlayback.ticksPerDivision = channel->effectParameter;
else
songPlayback.bpm = channel->effectParameter;

calculationNewSpeed( &songPlayback, songPlayback.ticksPerDivision, songPlayback.bpm );
}

// Volume slide.
soundChannel->volumeSlide = 0;
if ( MOD_EFFECT_TYPE__VOLUME_SLIDE == channel->effectType )
{
int8_t up   = ( channel->effectParameter & 0xF0 ) >> 4;
int8_t down = ( channel->effectParameter & 0x0F ) >> 0;
if ( ( 0 != up ) && ( 0 == down ) )
soundChannel->volumeSlide = up;
else
if ( ( 0 == up ) && ( 0 != down ) )
soundChannel->volumeSlide = -down;
}

// Pitch slide.
if ( MOD_EFFECT_TYPE__SLIDE_UP == channel->effectType )
{
soundChannel->pitchSlide = -(int16_t)channel->effectParameter;
soundChannel->slideTarget = getPeriodByNote( MOD_NOTE__B_3 );
}
else
if ( MOD_EFFECT_TYPE__SLIDE_DOWN == channel->effectType )
{
soundChannel->pitchSlide = (int16_t)channel->effectParameter;
soundChannel->slideTarget = getPeriodByNote( MOD_NOTE__C_1 );
}
else
if ( MOD_EFFECT_TYPE__SLIDE_TO_NOTE != channel->effectType )
soundChannel->pitchSlide = 0;

// Volume set.
if ( MOD_EFFECT_TYPE__SET_VOLUME == channel->effectType )
soundChannel->volume = channel->effectParameter;

// Pattern break and position jump.
if ( ( MOD_EFFECT_TYPE__PATTERN_BREAK == channel->effectType )
|| ( MOD_EFFECT_TYPE__POSITION_JUMP == channel->effectType ) )
{
nextDivisionIndex = MOD_PATTERN_DIVISIONS;
}

// Print out
if ( printNotes )
{
char const * effectName = "";
char effectParameter[ 4 ] = "   ";
if ( MOD_EFFECT_TYPE__NONE != channel->effectType )
{
effectName = MOD_EFFECT_NAMES[ channel->effectType ];
snprintf( effectParameter, sizeof( effectParameter )"%03X", channel->effectParameter & 0xFFF );
}

char const * note = "";
char sample[ 4 ] = "   ";
if ( 0 != channel->period )
{
note = getNoteName( channel->period );
snprintf( sample, sizeof( sample )"%3d", channel->sample );
}

printf
(
"| %s %3s %-10s %s ",
sample,
note,
effectName,
effectParameter
);
}

}

if ( printNotes )
printf( "|\n" );

// For each tick of this division, generate samples.
for ( uint8_t tickCount = 0; tickCount < songPlayback.ticksPerDivision; tickCount += 1 )
{
// Print out
if ( printNotes )
printf( "\tt%d ", tickCount );
for ( unsigned channelIndex = 0; channelIndex < MOD_CHANNELS; channelIndex += 1 )
{
SoundChannel * soundChannel = &songPlayback.soundChannels[ channelIndex ];

uint16_t period = soundChannel->period;

if ( 1 == soundChannel->arpeggioIndex )
period += soundChannel->arpeggioA;
else
if ( 2 == soundChannel->arpeggioIndex )
period += soundChannel->arpeggioB;

soundChannel->arpeggioIndex += 1;
if ( soundChannel->arpeggioIndex >= 3 )
soundChannel->arpeggioIndex = 0;

// Number of samples/second.
double sendRate =
(double)AMIGA_NTSC_CRYSTAL / ( period * AMIGA_PAULA_PERIOD_DIVIDE );

double sampleRate = sendRate / FREQUENCY;

soundChannel->indexIncrement = sampleRate * ( 1 << INDEX_FIXED_SHIFT );

// Print out
if ( printNotes )
printf
(
"| p%4d v%2d s%-2i %-5u",
period,
soundChannel->volume,
soundChannel->pitchSlide,
soundChannel->index >> INDEX_FIXED_SHIFT
);
}

if ( printNotes )
printf( " |\n" );

mixTick( &songPlayback, modFile );

for ( unsigned channelIndex = 0; channelIndex < MOD_CHANNELS; channelIndex += 1 )
{
SoundChannel * soundChannel = &songPlayback.soundChannels[ channelIndex ];

// If sliding and this isn't the last tick of the division.
// (If the period of the note being played is z, then the final
// period will be z - (x*16 + y)*(ticks - 1))
if ( ( 0 != soundChannel->pitchSlide )
&& ( songPlayback.ticksPerDivision > 1 )
&& ( tickCount < ( songPlayback.ticksPerDivision - 1 ) ) )
{
soundChannel->period += soundChannel->pitchSlide;

if ( ( soundChannel->pitchSlide < 0 )
&& ( soundChannel->period < soundChannel->slideTarget ) )
{
soundChannel->period = soundChannel->slideTarget;
}

if ( ( soundChannel->pitchSlide > 0 )
&& ( soundChannel->period > soundChannel->slideTarget ) )
{
soundChannel->period = soundChannel->slideTarget;
}
}

if ( 0 != soundChannel->volumeSlide )
{
int8_t newVolume = soundChannel->volume;
newVolume += soundChannel->volumeSlide;

if ( newVolume < 0 )
newVolume = 0;

if ( newVolume > MOD_MAX_VOLUME )
newVolume = MOD_MAX_VOLUME;

soundChannel->volume = newVolume;
}
}
}

divisionIndex = nextDivisionIndex;
nextDivisionIndex = divisionIndex + 1;
}

if ( 0 == patternIndex )
// Create new file and write first pattern.
isError |=
waveExport( fileName, FREQUENCY, songPlayback.samples, songPlayback.sampleIndex );
else
// Append this pattern to file.
isError |=
waveExportAppend( fileName, FREQUENCY, songPlayback.samples, songPlayback.sampleIndex );
}

return isError;
}

int main( int argumentCount, char * * arguments )
{
bool isError = ( argumentCount <= 2 );

if ( isError )
fprintf( stderr, "Syntax: %s <MOD file> <Out wave file>\n", arguments[ 0 ] );

char const * modFileName = arguments[ 1 ];
char const * wavFileName = arguments[ 2 ];

ModFile modFile;
if ( ! isError )
{
isError |= loadMod( modFileName, &modFile );
if ( isError )
fprintf( stderr, "Unable to load file.\n" );
}

if ( ! isError )
isError = modToWave( wavFileName, &modFile );

int returnResult = 0;
if ( isError )
returnResult = -1;

return returnResult;
}

Added two more effects today: arpeggio and portamento (slides). I have arpeggio (effect 0) slide up (effect 1) and slide down (effect 2) tested but not slide to note (effect 3). Arpeggio turned out to be more of a pain than I had anticipated. The parameters are not pitch, but simitones. That meant I had to add a reference to the note being played as well as the note’s period. This allows me to select and lookup the other notes in the simitone.

Slides are fairly simple except for the ticks-1 ending. Not sure why but this means the note doesn’t slide on the last tick of the division. For testing I use a fairly notorious song: CYBER.MOD. There is more than one rendition of this song and it is an adaptation of Jeroen Tel’s theme to the 1987 game Cybernoid: The Fighting Machine. Who composed this MOD is unknown.

There are several problems with this MOD. First, the slides are not slide to note, but just slides with values set so they get close to their desired note. As a result, many (most) of the slides end up out-of-tune. Another problem is that the sample looping is incorrect. Some instruments have loop lengths that extend beyond the last sample.

This song is a version of a C64 track, and a common practice for the SID 6581/8580 sound generated music was to use arpeggio to mimic chords. This technique quickly plays several notes, usually 2 or 3, one after another (an arpeggio), to make a simulated chord. The sound is emblematic to chiptunes. MODs have the effect but it isn’t used very often, mainly because if one wants chord they can simply sample the chord and include it. Nonetheless this song makes heavy use of arpeggio to simulate the C64 sound.

The arpeggio and slides make it a good song for testing because it is easy to hear differences if the playback isn’t working correctly. I have successfully reproduced the song and that should prove slides and arpeggio are functional.

I meant to try another MOD that uses slide, but I cannot load 15 instrument MOD files. So that will have to wait for another day.

Note: Yes, the slides are out-of-tune—that is how the song is written and that is how it is being reproduced.

# April 20, 2021

## MOD Panning and Surround Sound

### MOD Player

I did not have a lot of time after work to play with the MOD player but in what little time I had I was able to modify the WAV library to handle creating WAV files incrementally. My previous method involved either creating a WAV file, or opening an existing WAV file, appending samples and updating the header. In my new method the files stays open after creation. The start function just writes a placeholder heading. Then an add samples function is called until all the samples are written. When complete, a close function will fill in the header with the finial values.

The update is an improvement but mainly done so I could add support for stereo sound. I suspected that stereo sound was simply two samples back-to-back, with the first on one channel and the second on the other. This turned out to be correct.

With a stereo WAV file library I added fixed-panning to the MOD player. The original Amiga hardware had fixed panning. Channels 1 and 4 were to the left, and channels 2 and 3 were to the right. I never liked how hard this panning was so used 50% left, 50% right instead. This is still stereo but not as extreme. As one last trick I decided to see if I couldn’t implement Dual Module Player’s surround sound effect. I had values for left and right panning which were just integer numbers used to scale the volume for that channel. It was my understanding the surround sound was simply to use a negative value on the opposite channel. So with 64 being the maximum volume for a channel, values of 64 for left and -64 for right should result in surround sound. I believe it is this simple as the effect sounds correct.

# April 21, 2021

## Self-Panning MOD

### MOD Player

I’ve written in the past about the module player I used the most when I first started listening to MOD music: Otto Chros’ Dual Module Player (DMP). The original Amiga MOD format did not have any support for panning sound from left to right because the sound channels had panning fixed by the hardware. Effect number 8 was an otherwise unused effect that, somewhere along the line, was repurposed for panning. DMP supported this and I had figured that out.

DMP had another stereo effect called “surround” that could be applied to channels. What this did was play the normal waveform on one channel and the negative waveform on the other. The effect is so functional my 5.1 surround sound speakers interpolate this and place the sound on the rear speakers, but even with just two speaker the effect did make it seem as though the sound was coming from behind.

Many of the MOD files I wrote had mixing instructions for how to setup panning with DMP. At some point I figured out the panning effect, but didn’t think surround was a possible option. Then in an experiment I made a MOD that simply set the panning to each of the 256 possible panning values. I knew the first 128 were valid, but wasn’t sure what would happen after that. To my delight I found that DMP interpreted a value of 164 as surround. I wrote exactly one module find to take advantage of this. In mid June of 1996 I composed Level 3 - Dorrn. It was designed for a game I never made completed and I made fairly extensive use for the panning effect.

Yesterday I completed the work needed to have stereo sound, and today I implemented the actual pan effect. To finish the implementation I needed to add one other effect: sample offset. This was a fairly quick addition. While I was at it, I decided to change my floating point math to fixed-point. That was a bit of a pain because of reciprocals, but I had an idea afterward that might solve that problem easier. For now, I have fixed-point math and no floating-point which should allow me to port this code to an embedded device when I am ready.

The results of my work: a fully functional render of Level 3 – Dorrn.