
	.arm
	.align		4
	
	.set	PLAYBACK_FREQ		,22050
	.set	SAMPLE_BUFFER_LENGTH	,512	
	
	
	.set	S_SD_SAMPLE		,0
	.set	S_SD_SAMPLE_LENGTH	,4
	.set	S_SD_SAMPLE_POS		,8
	.set	S_SD_STOP		,12
	.set	S_SD_SAMPLE_TIME	,16
	.set	S_SD_FREQ		,20

	
	
	.global		play_sound_irq
	.type		play_sound_irq,function
	.global		play_sound
	.type		play_sound,function
	
		
	
play_sound_irq

;stop dma

	stmfd	sp!,{r0-r7}

	ldr	r7,=sd_struct

	mov	r0,#$4000000
	add	r1,r0,#$100
	add	r2,r0,#$200
	
	strh	r3,[r0,#$c6]		;REG_DMA1CNT_H=0; //stop DMA	
	
	;**** test against end
	
	ldr	r5,[r7,#S_SD_STOP]
	cmp	r5,#0
	bne	play_sound_irq_end
		
	;**** reload dma
		
	ldr	r3,[r7,#S_SD_SAMPLE]
	ldr	r4,[r7,#S_SD_SAMPLE_POS]
	add	r3,r3,r4
	str	r3,[r0,#$bc]		;dma1=source
	add	r3,r0,#$a0
	str	r3,[r0,#$c0]		;dma1=$040000a0
	mov	r3,#$b600
	strh	r3,[r0,#$c6]		;dma1ctrl

	;**** check	

 	ldr	r5,[r7,#S_SD_SAMPLE_LENGTH]
	sub	r5,r5,#SAMPLE_BUFFER_LENGTH*2
	cmp	r4,r5				;if(s>sm)
	ble	play_not_rest	
	
	sub	r5,r4,r5	;rest
	mvn	r6,#0
	sub	r5,r6,r5
	str	r5,[r7,#S_SD_SAMPLE_TIME]
	
	mov	r6,#1
	str	r6,[r7,#S_SD_STOP]
	
play_not_rest	

	add	r4,r4,#SAMPLE_BUFFER_LENGTH	;s=s+l
	str	r4,[r7,#S_SD_SAMPLE_POS]
	
	;reload timer 1	

	ldr	r3,[r7,#S_SD_SAMPLE_TIME]		
	strh	r3,[r1,#$4]		
	mov	r3,#$c4
	strh	r3,[r1,#$6]		

play_sound_irq_end
	ldmfd	sp!,{r0-r7}
	bx	lr	
	
nothing	.long	0
	
;*****************************************************************
;*
;* play_sound
;*
;* r0 = sample
;* r1 = sample_length
;* r2 = $ffff-16777216/FREQ
;*	
	
play_sound

	;**** init
	
	ldr	r10,=sd_struct
	stmia	r10,{r0,r1}		;set sample+ len

	mov	r0,#0
	str	r0,[r10,#S_SD_SAMPLE_POS]
	str	r0,[r10,#S_SD_STOP]

	ldr	r0,=($ffff-(SAMPLE_BUFFER_LENGTH))
	str	r0,[r10,#S_SD_SAMPLE_TIME]
	
	str	r2,[r10,#S_SD_FREQ]
	
	mov	r0,#SAMPLE_BUFFER_LENGTH
	str	r0,[r10,#S_SD_SAMPLE_POS]

	;uses timer 0 as sampling rate source
	;uses timer 1 to count the samples played in order to stop the sound 

	mov	r6,#$4000000
	add	r7,r6,#$100
	add	r8,r6,#$200
	

	ldr	r0,=$0b0f		
	mov	r1,#$0080		
	mov	r2,#0			
	
	strh	r0,[r6,#$80]		
	strh	r0,[r6,#$82]		
	strh	r1,[r6,#$84]		

	ldr	r0,[r10,#S_SD_SAMPLE]
	add	r1,r6,#$a0
	mov	r2,#$b600
	
	str	r0,[r6,#$bc]		
	str	r1,[r6,#$c0]		
	strh	r2,[r6,#$c6]		

	ldr	r0,[r10,#S_SD_SAMPLE_TIME]	
	mov	r1,#$c4
	
	strh	r0,[r7,#$4]		
	strh	r1,[r7,#$6]		

	mov	r0,#$10
	mov	r1,#$1
	
	strh	r0,[r8,#$0]		
	strh	r1,[r8,#$8]		

	ldr	r3,=sd_freq
	ldr	r0,[r3]
	mov	r1,#$80

	strh	r0,[r7,#$0]		
	strh	r1,[r7,#$2]		
	
	bx	lr	

	.section    	.ewram,"ax"
	.align	4
	
;**** struct
	
sd_struct	
sd_sample	.long	0
sd_samplelen	.long	0
sd_samplepos	.long	0
sd_stop		.long	0
sd_sampletime	.long	0
sd_freq		.long	0
	
	.end
	
	
				