
ASSEMBLER COURSE - LESSON 14

		- FUNDAMENTALS OF ACOUSTICS AND DIGITAL AUDIO -

(Directory Sourcec8) - therefore write "V Assembler3:sources8"

			         ___
			       _(   )_
			    __( . .  .)__
			  _(   _ .. ._ . )_
			 ( . _/(_____)\_   )
			(_  // __ | __ \\ __)
			(__( \/ o\ /o \/ )__)
			 ( .\_\__/ \__/_/. )
			  \_/ (_.   ._) \_/
			   /___(     )___\
			  ( |  |\___/|  | )
			   ||__|  |  |__||
			   ||::|__|__|::||
			   ||:::::::::sc||
			  .||:::__|__:;:||
			  /|. __     __ .|\.
			./(__..| .  .|.__) \.
			(______|. .. |______)
			   /|  |_____|
			         /|\


Author: Alvise Spanò

As you all certainly know, sound is nothing more than a WAVE, or, according to 
the physical definition, the "propagation of a perturbation in a medium"; in 
the case of the sounds we are used to hearing, the perturbation (wave) is 
initially emitted by the vibration of matter (molecules and / or atoms), and 
the medium is air (a wave is an oscillation, a continuous exchange of energy 
kinetics and potential, therefore mechanical, between molecules and / or atoms 
(physically it is the pressure variation between particles of matter), and 
therefore NEEDS matter to exist and spread: in a vacuum, for example, no sound 
wave or any other type of vibration propagates between two distinct and 
separate bodies (only electromagnetic radiation - at least so far, the only 
ones we are aware of - are able to move even in vacuum thanks to their dual 
physical nature both as a corpuscle with mass - albeit very small - (photon) 
and a wave)).

The physical model adopted to describe this continuous yielding of energy from 
one point to another in the medium presents the graph of the trigonometric 
function SINUS (= sin), that is of a SINUSOID.

>>> WAVE FUNCTION: y = f(x ± v*t) <<<

x example: HARMONIC WAVE EQUATION: y = asink(x±vt) = a * sin(k * (x ± v * t))

		    - y = DEPENDENT VARIABLE: in a two-dimensional Cartesian 
			  graph (x, y), the ordinate y represents the 
			  "dimensions" of each point x of the oscillation.

		    - a = WAVE AMPLIFICATION COEFFICIENT: as you well know, -1 
			  <= sin (x) <= 1 (sine of x (x = any real number) 
			  between -1 and 1, extremes included), so to obtain 
			  an oscillation that varies from -a to a (-a <= sin 
			  (x) <= a) it is necessary to multiply sin (x) by a 
			  real number a.

		    - k = FREQUENCY OF THE WAVE: by varying this parameter the 
			  frequency is varied, and, in an inversely 
			  proportional way, the PERIOD of the wave, that is 
			  the minimum interval, along the axis of the 
			  independent variable (in this case x) for which the 
			  sinusoid is cyclable, that is the minimum interval 
			  after which the wave assumes the same characteristics.
			  At this point we introduce the concept of WAVE 
			  LENGTH (= space traveled in the period = distance 
			  between two crests of adjacent cycles), and we 
			  deepen that of frequency: number of times in which 
			  the same characteristics are assumed by the wave in 
			  a given unit of time, or how many times per second 
			  the period is read (= cycles per second); usually 
			  the minute second [s] is considered as a unit of 
			  time and the Hertz [Hz = s ^ -1 = 1 / s] as a unit 
			  of measurement of frequency.

		    - x = INDEPENDENT VARIABLE: in a two-dimensional Cartesian 
			  graph (x, y), the abscissa x represents a point 
			  along a predetermined rectilinear spatial dimension 
			  at a given instant; x belongs to real numbers and, 
			  theoretically, has no limitations, i.e. it embraces 
			  the whole line causing in the considered plane (x, 
			  y) a sinusoid that continues to infinity both to the 
			  left and to the right of the origin of the O axes 
			  (0,0 ): this makes it easy to understand how the 
			  sine function enjoys a periodicity.
			  For example, if k = 1, the wave period is 360 
			  degrees (= 2 * ¶ radians) and the frequency is 1 Hz; 
			  if k = 2, the period is 180 ° (= ¶ rad) and the 
			  frequency is equal to 2 Hz; and so on.

		    - v = SPEED OF PROPAGATION: it indicates the speed in the 
			  kinematic sense with which a point of the wave moves 
			  in space.
			  Note that v = WAVE LENGTH * FREQ.

		    - t = INSTANT OF TIME: keep in mind that v * t = s = 
			  space, and s is the distance between two 
			  corresponding points of the same perturbation taken 
			  in different t, therefore, adding/subtracting 
			  to/from x we obtain over time a propagation, a 
			  movement in the space of wave.
			  it should be noted that with (x + s) the wave will 
			  move to the left, and with (x - s) to the right 
			  along the abscissa axis.

			  P.S.: I apologize for the hasty explanations and the 
			  absence of demonstrations, but this does not seem to 
			  me the right opportunity to dwell excessively on 
			  topics that do not directly concern assembler and 
			  coding in general; so please take the aforementioned 
			  explanations as they are and do not worry too much 
			  if you do not understand the physics of the waves in 
			  depth: you won't need it to put music into a game or 
			  demo in the end.

		    N.B.: Keep in mind that x and y represent any two 
			  characteristics of the propagation phenomenon.
			  In the case of sound waves, we will consider x and y 
			  as two spatial dimensions that describe the wave on 
			  a plane by examining a section.

	                         ·      ·
	                         :      :
	                 ________¦      ¦________
	                 \       |  __  |       /
	__________________\_____ | _\/_ | _____/__________________
	\____________________  / | \/\/ | \  ____________________/
	         \____________ \_|._  _.|_/ ____________/
	                \  ____ _)| \/ |(_ ____  /
	                 \/   / \__¯`'¯__/ \   \/
	                     / /  /    \  \ \
	                     \/ \ `····' / \/
	                         \      /
	                          \    /
	                           \  /sYz
	                            \/

Now we are able to transfer what we have learned from the hints of general 
physics of propagation phenomena in real acoustics, defining the concept of 
HARMONIC: a sound - by the way, non-existent in nature and reproducible only 
with electronic instruments, such as the computer - which presents the 
waveform (= graph (x, y) of the perturbation along its entire duration) of a 
sinusoid.
We can say that the harmonic wave is the model of the BASIC SOUND, which 
joining together with many others creates all NON pure sounds.
Physics always distinguishes 3 qualities in a sound so that it can be described:

	   1- PITCH:	   Which is distinguished by PURE sounds (made up of a 
			   single harmonic - nonexistent in nature) and 
			   NATURAL (made up of several overlapping harmonics 
			   in the same time interval - some of those that 
			   exist in nature have thousands of harmonics of 
			   different periods), and it qualifies the frequency, 
			   by altering which the various notes are produced.

	   2- INTENSITY:   Which can be seen as a sort of "volume" of the 
			   sound, and, in the case of harmonics, is directly 
			   proportional to the amplification a (absolute value 
			   of the Y shares of the crests) of the sinusoid.

	   3- TIMBRE:      Which qualifies the waveform of the sound 
			   irrespective of the previous two parameters, then 
			   substantially describes the musical instrument or, 
			   more generally, what we distinguish one sound from 
			   another regardless of its pitch and intensity.

Let's forget the various formulas for calculating the sound intensity and the 
pressure and intensity levels [deciBell = dB], which in any case do not 
directly affect electronic music but only acoustics as a branch of physics 
that deals with the diffusion of sounds in environment and the design of 
devices capable of reproducing (speakers, etc.) or picking up (microphones, 
etc.) sounds, and let us dwell on the pitch and timbre.

*** First of all, to begin with, the timbre itself is a non-existent parameter:
the computer does not distinguish sounds, and converts the digital data it has 
in its memory into analog signals (which transfer electrical intensities and 
not bits) according to a reading frequency and a given under-amplification 
value, ignoring the difference between sound and noise - two concepts that 
only we humans have introduced with different meanings and attributable to the 
aesthetic sense ***.

Therefore, we cannot really talk about timbre as a parameter - at least at an 
electronic level - even if there are sophisticated algorithms for identifying 
and comparing the timbre of different waveforms that could be useful for those 
who intend to program speech recognition routines. , eg; in any case, this is 
certainly not the right place to discuss such complex applications in the 
world of sound synthesis and processing.

So let's move on to the most important parameter, as far as we are concerned:
the pitch of the sounds is directly linked, in the case of NATURAL sounds, to 
the frequency of the fundamental harmonic (FUNDAMENTAL FREQUENCY) that 
distinguishes them, and, in the case of PURE sounds, to the frequency of the 
ONLY harmonic that constitutes them.

Let's take an example: we have a pure (harmonic) sound of period (= duration) X;
it can be emitted at any frequency, it depends only on the "READING SPEED" of 
the sound by the broadcaster: for example, if this "reads" the harmonic for 
its entire period 2 times per second, the frequency will be equal to 2 Hz; at 
a later stage, the problem of the acoustic diffusion of the given sound in the 
air also arises, which, however, is soon solved: the speed of sound 
propagation in the air is 380 m / s, and therefore, knowing that SPEED = WAVE 
LENGTH * FREQ., it is extremely simple to obtain the wavelength, which 
coincides, in terms of spatial dimensions, with period (which is expressed in 
seconds).

At this point a new parameter comes into play, to deal with the tone 
generation tools: the reading speed, or SPEED / SAMPLING FREQUENCY.

But now, to continue, it is necessary to explain how electronic instruments 
treat sound and how they process it before passing it to the amplifier.

Through the use of a sampler (audio digitizer) and suitable software, it is 
possible to convert the sounds coming from a sound source (microphone, CD, 
etc.) into numerical data (digital samples) each of which describes the 
"share" of an interval (of a "tiny slice" - to speak in scientific terms -) 
along the abscissa of the graph (x, y) of the waveform. The more samples we 
"capture", the more defined and closer to physical reality the digital sound 
will be.

For example, if we have a natural sound (therefore, not harmonic) lasting 2 
seconds (which we assume as a period, since it is not possible to identify a 
lower minimum interval for which the wave cycles), and we are able to obtain 
the fundamental frequency, it is sufficient to sample in memory with a DOUBLE 
sampling frequency (Nyquist theorem, explained later), to obtain a faithful 
and acoustically defined reproduction of the sound; if, for example, the 
fundamental frequency is 2 kHz (= 2000 Hz), we should record 2000 samples per 
second, for a total of 4000 samples (2000 samples / s * 2 s = 4000 samples).

** Each sample in memory occupies 8 bits (= 1 byte), in the Amiga, which 
adopts an 8-bit sound definition.
With the 8-bit number it is possible to describe Y quotas between -128 (= - (2 
^ 8) / 2 = -2 ^ (8-1) = -2 ^ 7) and 127 (= (2 ^ 8) / 2-1 = 2 ^ (8-1) -1 = 2 ^ 
7-1 (zero has a positive sign, in binary: in fact the positive numbers (from 0 
to 127) are 128 like the negative ones), extremes included, of each single 
sample, for a total of 256 (= 2 ^ 8) expressible values **.

N.B.:	it is important to note that the waveform oscillates between the I (+) 
	and the II (-) quadrant, divided by the abscissa of height 0; DO NOT 
	consider -128 as 0 and +127 as 255: it is NOT possible to translate 
	the wave on the 1st quadrant and make everything positive, * the 
	numbers would not go back to the sound chip, nor to any sound 
	processing for special effects via software *.

*** CONSIDER EACH SAMPLE AS AN 8 BIT SIGNED BYTE (= MSB = bit 7) ***

it is important to underline that digital synthesis with a number of bits 
greater than 8 would offer a higher sound quality, with the same sampling 
frequency.

For example, CD players read 16-bit samples (= 2 bytes = 1 word), which means 
that the Y range varies from -32768 (= - (2 ^ 16) / 2 = -2 ^ (16-1 ) = = -2 ^ 
15) and 32767 (= (2 ^ 16) / 2-1 = 2 ^ (16-1) -1 = 2 ^ 15-1), for a total of 
65536 (= 2 ^ 16) expressible values: *** this does not mean, however, that the 
value 32767 (positive peak) of the CD corresponds to a greater share of that 
sample than the value 127 of the same sample rendered to 8 bits: the sound 
output will be the same, except that with the same physical range the 16-bit 
synstesis offers much more definition (in essence, with 8 bits I have 256 
numbers to express a sound, between two physically constant positive and 
negative peaks, which however at 16 bit it is synthesized with a much higher 
range of values (65536) and therefore WITH MORE PRECISION, WITH LESS 
APPROXIMATION OF THE DIMENSIONS).

In a certain sense we can say that the 8 bits of the first example correspond 
to the high 8 bits (15: 8) of the 16 bits of the second, and the low 8 bits 
correspond to a sort of approximation after a fictitious comma placed between 
the high byte and the low one of the sample word ***.

Now let's go back to talking about the sampling frequency, citing a famous and 
important - as complicated as it is as far as the proof is concerned - which 
states that "THE FREQUENCY RESPONSE IS EQUAL TO HALF OF THE SAMPLING 
FREQUENCY" (Nyquist theorem): basically, it means that if we sample at 10 kHz, 
only the sounds with a frequency lower than or equal to 10/2 = 5 kHz will be 
faithfully reproduced (this explains the mysterious "DOUBLE" written just 
above about the sampling frequency necessary to sample the data sound, knowing 
its fundamental frequency).

It is essential to sample the sounds at an adequate frequency in order not to 
hear the ALIASING, which cuts frequencies above half the sampling frequency 
giving them an unpleasant "disturbed" effect.

** Although the Paula (for the record, the proper name of the Amiga sound 
chip) adopts digital precision at just 8 bits, it is possible to reproduce 
equally good quality sounds by sampling at the right frequencies and avoiding 
aliasing. ***, even if, however, the quality of a CD cannot be reached, which 
samples 16 bits at 44.1 kHz (44100 Hz) to obtain a frequency response ranging 
from 20 Hz to about 22 kHz, which corresponds approximately to the range of 
audible frequencies for the human ear (subjective: someone could go up to 20 
kHz approx.)

* I take this opportunity to say that sounds with a frequency (fundamental, 
implied) less than 20 Hz are called INFRASOUND, and those with a frequency 
greater than 20-22 kHz ULTRASOUND: both are NOT audible to humans *.

However, most natural sounds do not have a fundamental frequency above 15-16 
kHz; So is it enough to sample at maximum 32 kHz to faithfully reproduce 
almost all existing sounds?

Well, no! For a very simple reason: We have just explained that natural sounds 
are made up of many harmonics, among which a fundamental one can be 
identified: it could also happen that the fundamental frequency (which we 
usually use to calculate the sampling frequency) is actually the frequency of 
the harmonic of shorter period (therefore, of higher frequency); in this case 
all the harmonics of higher frequency than the one we assume as fundamental 
would be cut and reproduced with aliasing, significantly lowering the overall 
sound quality.

*** THEREFORE, IT WOULD BE APPROPRIATE TO SAMPLE AT DOUBLE FREQUENCY WITH 
RESPECT TO THE HIGHEST HARMONIC FREQUENCY THAT MAKES THE NATURAL SOUND DATA ***.
			      _______
			 _  _/ /_____\
			   _ __\  Oo /
			_ ______\_-_/______
			  (_/__/  :  __\_) '
			    __/   :   \__
			_  (_/____:____\_>
			   _ O/    _ _O/

Therefore, the intensity distinguishes the "volume" of the sound, and it is 
*** NOT constant with respect to the frequency: at very high or very low 
frequencies it is necessary to amplify it in order to be perceived with the 
same intensity compared to medium frequency sounds by the ear, which 
biological evolution (consequence of habit) has evidently led us to hear 
better those most common in nature ***; what distinguishes the pitch of a 
sound instead? In purely musical terms, it is easy to say: the NOTE.

As you no doubt know, musical notes form scales of 7 notes per OCTAVE, each of 
which begins with the note DO (C, for the Anglo-Saxon notation) and ends with 
the SI (B, for the Anglo-Saxon notation - the LA is the A); at each octave the 
frequency is doubled, therefore each DO/C is of double frequency with respect 
to the previous DO/C (note therefore that the increase in frequencies is not 
linear, but EXPONENTIAL in base 2).

Within the octave the ratios between the notes of the scale are as follows:


        DO      RE      MI      FA     SOL      LA      SI      |  (DO)
	C	D	E	F	G	A	B	|  (C)
--------+-------+-------+-------+-------+-------+-------+-------|---+---------
        1      9/8     5/4     4/3     3/2     5/3     15/8     |   2


In case you need to sample sounds that will then be used as instruments in 
music editing programs (such as SoundTracker, NoiseTracker or ProTracker), it 
would be sufficient to sample at a frequency double the fundamental frequency 
of the sound, which, if you sample from a musical instrument , corresponds to 
the frequency of the note played, at least for convenience:
if, for example, we need a piano for the composition of a module, we can 
sample A3 (A of the third octave) at 880 Hz (A3 = 440 Hz) and tell the tracker 
that the sampling frequency corresponds to A3, it will make sure to calculate 
the correct frequencies relative to the sampling frequency based on the notes 
we place on the score with that instrument.

Now, surely, you will ask yourself a question: but it is enough to sample at 
880 Hz, in order not to obtain an aliasing?

The answer is no. As we said before, it would be necessary to sample at double 
the frequency of the highest harmonic to faithfully reproduce the tone of the 
piano, but it is very complicated to derive this frequency (if not impossible).

What to do then? ** Well, try and try again to sample at various frequencies 
(honestly, much higher than 880 Hz) until you get optimal instrument 
reproduction at that note and tell the tracker the sample reading frequency 
for that note. **.
As you can see, then, the matter is more complicated in practice than in theory!

After these inevitable (and - I hope - interesting) hints of digital audio, I 
move on to the more specific explanation of the sound hardware of the Amiga's 
Original and AA chips (the Paula is the only custom chip that has never 
undergone improvements since its release in the first Amiga (1985, for the 
record)).

The hardware features 4 DMA channels dedicated to the 4 voices of the sound 
chip; these 4 voices are totally independent and are grouped 2 by 2 per 
speaker, obtaining voices 1 + 4 for the left and 2 + 3 for the right in stereo.

Furthermore, all 4 voices have their own hardware registers:

	AUDxLCH $dff0y0 =       Location of the data to be read (high word)
	AUDxLCL $dff0y2 =       Location of the data to be read (low word)
	AUDxLEN $dff0y4 =       Length of DMA (in word)
	AUDxPER $dff0y6 =       Sample period
	AUDxVOL $dff0y8 =       Volume
	AUDxDAT $dff0ya =       Channel data (2 byte = 2 sample at a time)

	N.B.: For each 'x' substitute a number from 0 to 3, corresponding to 
	      the desired voice; for each 'y' substitute a hexadecimal number 
	      from $a to $d for voices 0 to 3.

AUDxLCH-AUDxLCL:They constitute the latch value, not the pointer to the data 
		for the DMA, therefore, once set, it does not increment as it 
		does for the planes, for the sprites or for the blitter 
		channels, but is similar to the copper location registers, the 
		value which is automatically reinserted into the internal 
		pointer registers when needed.
		* Since these two 16-bit registers are adjacent, it's 
		convenient to set them up with a single 68000 MOVE.L like:
		MOVE.L  #miosample,AUDxLCH *.
		N.B.: from now on, with AUDxLC I will refer to the pair of the 
		two registers, to a sort of 32-bit single location register.

AUDxLEN:	Expresses the length in word of the sample to be played.
		If, for example, we have a sample of 500 bytes in memory, we 
		need to set this register (of one of the 4 desired channels) 
		with a value of 250.
	  N.B.: As for the blitter, writing 0 to this register reads 128 kB of 
		samples.

AUDxPER:	This register is used to specify the frequency of reading of 
		the DMA in a somewhat bizarre way - apparently -, but which 
		returns convenient and fast to the hardware: it must be set 
		with the SAMPLING PERIOD of each single sample of the sound, a 
		value that expresses the time (in system DMA CLOCK cycles = 
		3546895 Hz (PAL), 3579545 Hz (NTSC)) that the DMA must wait 
		(it works as a decrementer: -1 per clock cycle) before 
		transferring another sample.
		Here is a formula to calculate the value to enter in this 
		register, given the sampling rate (which is much more 
		practical to manage):  PER = CLOCK / freq. [Hz]
		For example, if we have to sample a harmonic LA3 - assuming we 
		find a natural source of it ... - with a frequency of 440 Hz, 
		with a period of 1 second, we must adopt a sampling frequency 
		of 880 Hz, so here is the sampling period to enter in the 
		AUDxPER register to read the sample in memory at the right 
		frequency in 1 second:
		PER = 3546895 / 880 = 4030 (PAL)
	  N.B.: The audio data is fetched by the DMA in 4 slots of the color 
		clock (16bit = 2 samples per channel) per horizontal scan line.
		PAL have 312.5 (312 = SHF, 313 = LOF) scan lines per raster, 
		and there are 50 rasters per second; therefore, the maximum 
		reading frequency (reading to all available assigned cycles) 
		would be = 2 BytePerLine * 312.5 * 50 = approximately 31300 
		Hz: ** BUT THIS SPEED IS ONLY THEORETICAL **, as it is 
		impossible to set a right sampling period that coincides 
		perfectly with the cycles assigned to the audio DMA for each 
		line of raster: an end of a period count from the DMA may 
		occur in the middle of a scan line (or, total bad luck, the 
		cycle after the slot assigned to the given voice), and the 
		hardware is forced to wait for the line after to get the data 
		to be played, while, if the sampling period is short, the 
		subsequent end of counting could take place in the line 
		itself, in the absence of new data.
		In essence, the minimum period must allow the hardware to 
		travel at least an entire line of raster: the sound does not 
		come out when it is read by the DMA, but when the internal 
		count ends from the value of the period in AUDxPER: the audio 
		DMA reads the data only during the assigned cycles (moreover 
		at very high priority - such as those of the DMA of disk 
		drives - to avoid distortions and slowdowns due to 
		"overcrowding" of channels - see: "bit planes that always 
		break") and keeps them in AUDxDAT until the end of the 
		sampling period,
		* which can happen at any time *, and sound is generated;
		* for this reason the minimum sampling period CANNOT be 
		lowered beyond 123 (=28836 Hz): to allow the DMA in any case 
		to read at least another data before playing, on the line 
		after *.
		At this point the question is in order: « Why is 123 set as 
		the minimum period, when the clock cycles per line (ie the 
		number of decrements) are 226.5 (226 = LOF, 227 = SHF)? ».
		Here is the answer: before it was mentioned that the DMA 
		transfers 16 bits (= 2 bytes) "on the spot" per voice, so it 
		has 2 playable samples on each line, and, once the first is 
		played, it can also play the next one during the same raster 
		line, due to the fact that he has not already read it; with 
		123, in fact, at most 2 end-counts can occur during the same 
		line, and the problem does not arise.
		The theoretical minimum period, therefore, should be 227 (to 
		keep us wide) / 2 = 114 (always approximating upwards), which 
		coincides more or less (the correspondence between period and 
		sampling frequency is NOT biunique:there is always a certain 
		approximation) with the theoretical maximum frequency of 
		approximately 31300 Hz. But, as mentioned above, it is not 
		accurately reachable from the hardware.
		*** 123 is the minimum period that can be set = 28836 Hz ***

AUDxVOL:	In this register the volume of the sound emission in the 
		relative channel must be specified with values between 0 and 
		64 (by inserting '64' there is no reduction of dB = maximum 
		volume).
		*** ADVICE !!! When sampling try to exploit the whole range of 
		values from -128 to 127 even for low intensity sounds in order 
		to always have maximum precision, and instead lower the volume 
		in this register ***.

AUDxDAT:	it is the momentary buffer that the DMA uses before data is 
		sent to the D/A converters (Digital/Analog) and signals are 
		output from the Amiga.
		It contains 2 bytes of audio data (the DMA transfers 16 bits 
		at a time from the RAM - this explains why the AUDxLEN must be 
		expressed in words!) Which are sent 1 to 1 to the DAC 
		(Digital-Analog Converter).
		*** NOT RECOMMENDED !!! it is also possible to set these 
		registers with the CPU when the DMA is off and make the 
		computer sound anyway  :( ***.
			         _____   
			     .__/_____\
			        \ O o /
			  /\ ____\_\_/___
			  \\\/___  :  _  \
			  O\ \  /  :  /  /
			    \\\_   :   \/
			_ __O\_/___:____\


		- EXAMPLE of setting the registers to play a 23 kB sample at a 
		  frequency of 21056 Hz stored in the memory at location 
		  $60000 (chip RAM) at maximum volume in stereo, with voice 2 
		  and 3 (third and fourth channel):

PlaySample:
	lea	$dff000,a0	; base of custom chips in a0
	move.l	#$60000,$c0(a0)	; points AUD2LC at $60000
	move.l	#$60000,$d0(a0)	; it also points AUD3LC at $60000
	move.w	#11776,$c4(a0)	; AUD2LEN = 23 kB = 23*1024 = 23552 B [...]
	move.w	#11776,$d4(a0)	; also AUD3LEN = [...] = 23552/2 = 11776 word
	move.w	#168,$c6(a0)	; AUD2PER = 3546895/21056 = 168
	move.w	#168,$d6(a0)	; sets AUD3PER as AUD2PER
	move.w	#64,$c8(a0)	; maximum volume for AUD2VOL
	move.w	#64,$d8(a0)	; maximum volume also for AUD3VOL
	move.w	#$800c,$96(a0)	; turns on the DMA of channels 2 and 3 in DMACON

Let's now explain what happens when the channels' DMAs are turned on (in 
addition to the fact that - clearly - the sample is heard ...):

		1 - The value contained in AUDLC is inserted in the internal 
		    pointing registers and the DMA begins to transfer data 
		    from the registers 2 bytes at a time.
		    * From now on the AUDLC register CAN also be changed:
		    the hardware, as soon as it has finished transferring the 
		    entire sample, will start all over again (ENDLESS LOOP).

		2 - As soon as the AUDLC value is entered in the internal 
		    registers, a LEVEL 4 interrupt is fired, which in the 
		    INTENA and INTREQ registers is divided into 4 
		    sub-interrupts, one assigned to each of the 4 audio 
		    channels:

		      +--------------+---------------------+---------+
		      |  IRQ LEVEL   |  BIT INTENA/INTREQ  | CHANNEL |
		      +--------------+---------------------+---------+
		      |      4       |	 	10  	   |    3    |
		      |      4       |	  	9	   |    2    |
		      |      4       |	  	8	   |    1    |
		      |      4       |	  	7	   |    0    |
		      +--------------+---------------------+---------+

		    Thanks to these interrupts it is possible, for example, to 
		    set a new sample to be played as soon as the current one 
		    is finished by simply pointing the location registers to 
		    another sample, and obtaining a perfect connection between 
		    the two (provided that the two waveforms respectively end 
		    and begin similarly).

		3 - at the end of the transfer, everything starts again from 
		    point (1).
		    ** The registers are never altered **.

			   .||||||.
			   \ oO  ||
			   _\_-_/||_
			  / {_{_ __ \
			  \ |____|/_/
			   /______\_)
			 ___|_|  |
			/_/______|ck!^desejn

Of course, all this is interesting - you will say -, but how to make the 
computer play a 10-minute song without sampling tens of megabytes of data?

Precisely for this purpose, Trackers were invented: programs designed to write 
music that require only the basic instruments to be sampled by obtaining the 
various notes by varying the reading frequency of the same. They are also 
equipped with an editor where you can compose the score divided into 4 tracks 
(one for each voice), each of which can play any instrument at any time, but 
still one at a time (in total you can get a maximum of 4 contemporary 
instruments).

It would be very complicated to explain here all the various possibilities of 
a tracker, so I invite you to get one (like the ProTracker: currently the best 
4-track tracker - yes, there are also multiple tracks, which mix the notes of 
several tracks in a single voice; unfortunately, however, this procedure is 
extremely slow and could not be adopted to play the music of a demo or a video 
game, since the machine, in such cases, can't afford to lose all that time 
playing music...).

The "philosophy" of the trackers, however, does not change: they all provide - 
so-called - music routines, which are asm sources that often exploiting level 
6 interrupts (connected to the CIAB) or waiting loops synchronized with the 
electronic brush, and play in real time modules (song + samples = score + 
instruments) created with the relative tracker (or compatible, that is, which 
save the module structure in the same way).

Adapting these routines to your sources is very simple: in principle - each 
has its conventions: read the .doc of your tracker - just launch an 
initialization subroutine that sets the interrupts and DMA channels - some 
even the CIAB timers ; the CIAA remains intact as it is used by the Exec to 
time processes / tasks - and to launch the play subroutine on each raster (you 
should do this at the beginning of the vertical blank interrupt code - if you 
are under the operating system, add a server of interrupt 5 (VBLANK, level 3) 
at high priority, to do everything during the vertical blank interval, before 
the planes start to fetch data and slow everything down); before quitting your 
demo / game - or any program - REMEMBER to run the interrupt, DMA and timer 
restore subroutine for the OS.

Another important paragraph on the audio hardware of the Amiga concerns the 
modulation of the sound coming from the DMA of the 4 voices.

What is MODULATION? You will certainly have heard in many songs the effect of 
AUDIO FADE (the progressive and slow decrease of the volume): well, this 
simple effect is a particular type of modulation.

*** MODULATION consists in altering one or more parameters of a sound during 
and beyond its period ***; the parameters in question are, obviously, 
INTENSITY (amplitude) and PITCH (frequency).

To what effects do amplitude modulation and frequency modulation correspond - 
in terms of sound perception?

The first, as we have already mentioned, finds a common application in 
dissolves usually at the beginning and at the end of a piece of music; a 
familiar example of frequency modulation is the slide on the strings of a 
guitar (or a string instrument): in essence, a nuanced fusion of adjacent 
notes starting from a given frequency and arriving at another, gradually 
passing through all the intermediate ones with a certain speed (or even a 
certain acceleration).

it is also possible to modulate both amplitude and frequency at the same time, 
obtaining a strange effect attributable to a phenomenon of daily experience: 
* the Doppler effect *.

Briefly, it consists in the change (in fact, modulation) of the intensity and 
pitch of the sounds coming from a source in relative motion with respect to 
the listener: when you are walking down the street, you notice that the noise 
of the cars approaching and then overtaking you does not maintain the same 
parameters in the different positions of the car (source) with respect to you 
(listener) but, first of all, it gets louder in an inversely proportional way 
to the distance between you and the source, and, if you look carefully, the 
intensity is not the only one to change over time: even the frequency of the 
noise emitted by the engine is lower when the engine is distant.

I do not think it is appropriate to report the equation that describes the 
phenomenon as a function of the speed of the two bodies and of the distance, 
as the problem does not touch closely the topic "modulation on Amiga"; that 
equation, however, can easily be found in any physics or general acoustics 
book, even from high school.

Passing, in fact, to the modulation on the Amiga, I am forced to disappoint 
you immediately: although the Paula has particular operating modes to modulate 
the sounds coming from a channel both in amplitude and in frequency, you never 
use this hardware solution because it has a terrible restriction: to modulate 
intensity and height the DMA must read from the RAM the values to be entered 
respectively in the AUDxVOL and / or AUDxPER registers while another DMA reads 
the actual values of the sample to be played and then distorted; this process 
has the limitation that the DMA that reads from the modulation value table 
must be one of the audio channels, so to modulate, for example, the sound read 
from channel 0 both in frequency and in amplitude we are forced to use 
channels 1 and 2 to read the respective tables, with the result of wasting 3 
channels to generate a single modulated sound.

All the modulation effects used by the trackers are managed by the CPU, which 
sets the volume and period registers of the desired voice "nastily" while the 
DMA reads its sample unaware. By doing this, no channels are wasted, even if 
the CPU remains busy calculating the sound effects in real time.

The Amiga does NOT even have an FM (Frequency Modulation) synthesizer capable 
of creating different tones starting from the same waveform.

These apply modulations both in amplitude and in frequency according to 4 
parameters called ADSR, from the initials of the 4 main phases of a 
synthesized sound: Attack, Decay, Sustain, Release.

The graph of this modulation is as follows:

			     b
			     /\
			    /  \ D     
			   /    \      S
		       A  /      \___________d
			 /       c           \
			/		      \  R
		       /		       \
  _ _ _ ______________/				\____________________ _ _ _
		      a				 e

The first phase is Attack, which consists in bringing the volume and/or the 
frequency of the wave from 'a' to 'b' (ie from 0 to a maximum peak value); 
after which, the graph goes down for the Decay segment up to a level 'c', at 
which it stabilizes for the duration of the Sustain; finally it returns to 0 
from 'd' to 'e' with the Release.

** By "playing" acutely with the position of the points 'a', 'b', 'c', 'd' and 
'e' and with the durations of the various phases it is possible to generate an 
infinity of sounds even starting from the sample of a banal harmonic **.

Unfortunately, these notions will not be useful to you for programming the 
Amiga sound chip, so let's move on to the description of those bits that were 
never set in the history of the Amiga and its hardware...:)

The registry in question is the infamous ADKCON ($dff09e), which also has a 
read copy (ADKCONR) at $dff010:

	bit  -  7:      USE3PN  Use channel 3 to not modulate anything
		6:      USE2P3  Use channel 2 to modulate the period of 3
		5:      USE1P2  Use channel 1 to modulate the period of 2
		4:      USE0P1  Use channel 0 to modulate the period of 1
		3:      USE3VN  Use channel 3 to not modulate anything
		2:      USE2V3  Use channel 2 to modulate the VOLUME of 3
		1:      USE1V2  Use channel 1 to modulate the VOLUME of 2
		0:      USE0V1  Use channel 0 to modulate the VOLUME of 1

You will certainly have understood how the matter works: if, for example, you 
have to modulate channel 2 in amplitude, you can do it only using 1 as a 
reader of the values to be entered in the AUD2VOL register, therefore, you 
will have to point the channels to the relative data and give them a reading 
frequency.

** Modulation, however, is a simple but important effect, which must be 
simulated via the CPU - as already mentioned - in order not to occupy some of 
the already few audio channels of the Amiga... **

			   O    .... o      
			     o :¦ll¦:       
			   ___( 'øo` )___   
			 /¨¨¨(_  `____)¨¨¨\ 
			(__,  `----U-'  .__)
			( ¬\\_>FATAL< _,/¯ )
			(__)\ ¯¯":"¯¯¯ /(__)
			(,,) \__ : ___/ (,,)
			     (_\¯¯¯ /_)     
			:...(    Y    ¬) ··:
			    _\___|____/_
			   `-----`------'

I would conclude by allowing myself to state that the knowledge of digital 
acoustics and the functioning of sound chips in general is not as fundamental 
as that of the graphics hardware or the asm of a CPU, and it is certain that 
the mastery of these is necessary for anyone, audiophiles included; it is 
equally true, however, that the true culture on the subject also provides for 
an in-depth knowledge of digital sound theory, which is so much praised in 
recent times, as it is the object of ignorance by most of the people, who 
think just like those "coderS" who snub - not to say "jump" -
completely the sources of information on this topic because «anyway, the music 
routines are just called from the interrupt...».

****************************************************************************
* PART 2: THE SOPHISTICATED REPLAY ROUTINES (author: Fabio Ciucci)	   *
****************************************************************************

Speaking of these music rutines, for now we have only seen the standard one 
that comes with the Protracker, but there are also other more sophisticated 
ones.

We will now see one of the best, player6.1a, which also requires a conversion 
program (the p61con, on this disc), with which we have to transform a normal 
module into one optimized for the replay routine.

NOTE: This player is copyright of the author:

		Jarno Paananen / Guru of Sahara Surfers.
		­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­

			       J.Paananen
			      Puskalantie 6
			    FIN-37120 Nokia
				Finland

Internet:	    Jarno_Paananen@sonata.fipnet.fi
			 jpaana@freenet.hut.fi


So, if you are going to use his replay routine in a commercial product, for 
example in a game, you need to get his written permission and give him 
something (in Finnish Marks!) as a percentage.

He will already be mad at me for not having included the whole archive!!!...

This player has a lot of options, in the meantime let's try to do the simplest 
thing: play a module as we did with the standard routine supplied with the 
Protracker program.

The things to do are these:

1) Convert the module to the P61 format, using the "P61CON" utility. This 
   utility requires the reqtools.library and the powerpacker.library in the 
   libs: directory to work. In the program preferences, do not touch anything, 
   leaving only the "time" option set.
   Make a note of the USECODE when saving, which will be specified in the 
   equate listing "use = ....". This is to reduce code.

2) In this way, we got the converted form NOT COMPRESSED.
   Despite this, the module often gets shorter due to the optimization that is 
   done automatically.

3) Now just do as with the previous routines: call P61_Init before playing, 
   then P61_Music at each frame, and P61_End at the end.
   The only extra request is to enable the level 6 interrupt.

Let's see a practical example in Lesson 14-10a.s

You will notice that it is faster than the standard one, but also that it uses 
CIAB timer A and interrupt level 6 ($78).
Then there are equates, the meaning of which must be known:

fade  = 0	;0 = Normal, NO master volume control possible
		;1 = Use master volume (P61_Master)

This must be set to 1 if you want to control the volume to make a fade, acting 
on the P61_Master label. We will see an example later. If we do not need this 
option, we put 0, in order to save code, in fact these equates are nothing 
more than conditional assemblies that use the assembler directives "ifeq", 
"ifne", "endc"...

jump = 0	;0 = do NOT include position jump code (P61_SetPosition)
		;1 = Include

Also this option must be left at zero, if you do not use the jump routine to a 
specific position of the module. We will see an example later.

system = 0	;0 = killer
		;1 = friendly

This option is best left at 0, if you are doing "evil" code and using 
startup2.s. Just be careful when loading with DOS!!! (you also have to leave 
interrupt $78 (level6) in place, without restoring the system one, in case you 
load with this replay routine active!).

CIA = 0		;0 = CIA disabled
		;1 = CIA enabled

This option must be kept at 0 to use the routine in "standard" mode. If it is 
set to 1, it will no longer be necessary to call P61_Music at each frame, 
because the timing will take place entirely with CIAB. We will see an example.

exec = 1	;0 = ExecBase destroyed
		;1 = ExecBase valid

This we must keep at 1, since in $4.w we leave the valid execbase... we are 
not maniacs!!! And what about the startup we do?

opt020 = 0	;0 = MC680x0 code
		;1 = MC68020+ or better

This is clear: if your game/demo is AGA only, you can set this to 1, otherwise 
leave it to zero. Be careful not to set it to 1 when not needed!!!!!! ONLY IF 
THE GAME/DEMO RUNS **ONLY** ON AGA (therefore 68020+).

use = $2009559	; Usecode (put the value given by p61con when saving, 
		; different for each module!)

Here the comment explains everything ... always write down the usecode on a 
piece of paper (without losing the piece of paper, of course), and put it here.
It is used to assemble only the effect routines used in the module, saving 
space. Putting -1 means assembling everything (ugh!).
			      ____  
			     /    \ 
			  _ |______| _
			 /(_|/\/\/\|_)\
			(______________)
			    |  ..  |
			    | \__/ |
			    |______|
			  .--'    `--.
			  | |      | |
			  | |______| |
			  |_||||||||_|
			  (^) ____ (^)
			    |  ||  |
			   _| _||_ |_
			  /____\/____\

The conversion program also allows you to compress the module, but this loses 
some quality. So I advise you not to compact them...

Unless you need to do a 40k intro and have your back to the wall in terms of 
space, it's always good to use the "normally" converted module.
However, the program allows you to choose which samples to compact and which 
not... and to listen with your ears if you lose too much quality!!!

Here's what needs to be done to compress and play back a compressed module:

1) Convert the module to compressed P61 format, with "P61CON".
   In the program preferences, the "pack samples" option must be activated.
   Note that you can choose which samples to compress and which not.
   Here's what you'll see for each sample:

   Original	   -Play the original sample (Stop with right mouse button)
   Packed	   -Play the sample as it would be compressed. If you notice 
		    that too much is lost in quality, reconsider...!
   Pack		   -Mark this sample as "to be compressed"
   Pack rest	   -Compact all other samples from here on out
   Don't pack	   -Do not compact this sample
   Don't pack rest -Do not compact all other samples (from here on)
   Make a note of the USECODE when saving, as always.
   PLUS, make a note of the "sample buffer length" too!!!!!!

2) In this way, we got the converted and COMPRESSED form.

3) There are now 2 more things to do: First, the module has compressed 
   samples, which need to be unpacked into a buffer. To do this, you need to 
   do 2 things: the buffer, as long as indicated by the program as "sample 
   buffer length", and put its address in a2 before calling P61_Init, which 
   will decompress it. For the rest (play and end routines) it is the same.
   Let's see everything in practice:

	movem.l	d0-d7/a0-a6,-(SP)
	lea	P61_data,a0	; Address of module in a0
	lea	$dff000,a6	; Let's remember the $dff000 in a6!
	sub.l	a1,a1		; The samples are not separated, let's put zero
*******************
>>>>>	lea	samples,a2	; Compacted module! Target buffer for the 
*******************		; samples (in chip-RAM).
	bsr.w	P61_Init	; Note: takes a few seconds to decompress!
	movem.l	(SP)+,d0-d7/a0-a6

For the module and buffer, here are the changes:

1) The module no longer needs to be loaded in chip-RAM:

	Section	module,data	; It does not need to be in chip ram, because 
				; it is compressed and will be unpacked 
				; elsewhere!
P61_data:
	incbin	"P61.stardust"	; Compressed, (option PACK SAMPLES)

2) The buffer must be loaded in CHIP RAM, and as big as specified:

	section	smp,bss_c

samples:
	ds.b	132112	; length reported by the P61CON


As you will notice, in addition to losing quality in the samples, it also uses 
more memory, as we have more buffer, even if the module is shorter.

Let's see an example in Lesson 14-10b.s

Now that we have seen the 2 main implementations, we can see all the 
variations. First of all the CIA option, which is enabled with the equate.
You can see 2 examples in Lesson14-10c.s and Lesson14-10d.s

				  o
				 o. ______
				 °O|.____.|
				°o.|| .. ||
				  O|`----'|
				   |______|
				 .--'    `--.
				 | |      | |
				 | |      | |
				 |_|______|_|
				 (^) ____ (^)
				   |  ||  |
				  _| _||_ |
				 /____\/___\

Finally, let's see the use of 2 options:

The audio fade: just activate the "fade" equate, and act on the appropriate 
label "P61_Master", which goes from 0 to 64. Example in Lesson14-10e.s

The ability to jump to arbitrary module positions: just activate the "jump" 
equate, and call the "P61_SetPosition" routine, with the position in register 
d0. Example in Lesson 14-10f.s

There would also be other options, which we can summarize in the preferences:

Two files:		This option saves the samples and song separately in 2 
			files. It can be useful if we use multiple modules 
			with the same samples...

P61A sign:		puts the sign P61A at the beginning of the module... 
			it can only serve to make it easier for the bad guys 
			to rip it!!! Never set it!

No samples:		It is used when saving many modules that have the same 
			samples: the first time you put "two files", and you 
			save the modules and the first song. Then you set this 
			option and save all the other songs.

Tempo:			To make the player use the "Tempo" option.

Icon:			If you want to save an icon together with the module

Delta:			8-bit instead of 4-bit compression (I noticed that 
			almost nothing changes ... bah!)

Sample packing:		To be set for compression of samples with the 4-bit 
			delta algorithm (QUALITY LOSS!!!).

			 ____     ________     ____
			 \__ \__ /   __   \ __/ __/
			   \____|o o \/ o o|____/
			     \__|__________|__/
			        |     ___/__\
			       _|__   \__/  \\_
			      (_______/U     \/
			____/\_\___U_/ \_____/_/\____
			\ ___/  (_(_______)_)  \___ /
			 \_\/  /      |      \  \/_/
			   /  /       |       \  \
			  /  /________|_______/\  \
			 /  /      _____        \  \
			 \           /             /
			  \_______________________/

Happy listening everyone!

