/*******************************************************************************
 *
 * (c) Copyright 1993 Commodore-Amiga, Inc.  All rights reserved.
 *
 * This software is provided as-is and is subject to change; no warranties
 * are made.  All use is at your own risk.  No liability or responsibility
 * is assumed.
 *
 * Audio - Reads an 8SVX audio file, strips the IFF headers, and writes to the
 * raw animation file.
 *
 ******************************************************************************/

#include <exec/types.h>
#include <exec/memory.h>
#include <proto/exec.h>
#include <libraries/iffparse.h>
#include <proto/iffparse.h>
#include <dos/dos.h>
#include <proto/dos.h>

#include "/playanim.h"

#define ID_8SVX MAKE_ID('8','S','V','X')
#define ID_VHDR MAKE_ID('V','H','D','R')
#define ID_BODY MAKE_ID('B','O','D','Y')

/* convert an 8SVX file to raw audio data. */
void GetAudio(STRPTR FileName, BPTR OutFile)
{
    struct ContextNode *cn;
    struct StoredProperty *sp;
    struct IFFHandle *iff;
    ULONG secsize;
    UBYTE *inbuff;
    struct VHDR vhdr;
    struct RawAudio ra;

    if (iff = AllocIFF())
    {
	if (iff->iff_Stream = Open(FileName, MODE_OLDFILE))
	{
		InitIFFasDOS(iff);
		if (OpenIFF(iff, IFFF_READ) == NULL)
		{
			if ((PropChunk(iff, ID_8SVX, ID_VHDR) == 0) &&
			    (StopChunk(iff, ID_8SVX, ID_BODY) == 0) &&
			    (ParseIFF(iff, IFFPARSE_SCAN) == 0))
			{
				if (sp = FindProp(iff, ID_8SVX, ID_VHDR))
				{
					vhdr = (*(struct VHDR *)sp->sp_Data);
					ra.ra_SizeOfSample = vhdr.OneShotHiSamples;
					ra.ra_SamplesPerSecond = vhdr.SamplesPerSec;
					ra.ra_SamplesPerCycle = vhdr.SamplesPerHiCycle;
					ra.ra_Volume = vhdr.Volume;
				}
				/* we are at the BODY chunk */
				if ((cn = CurrentChunk(iff)) &&
				    (secsize = (WHOLE_SECTORS(cn->cn_Size + sizeof(struct RawAudio)) * SECTORSIZE)) &&
				    (inbuff = AllocVec(secsize, MEMF_CLEAR)))
				{
					ReadChunkBytes(iff, inbuff, cn->cn_Size);
					Write(OutFile, &ra, sizeof(struct RawAudio));
					Write(OutFile, inbuff, (secsize - sizeof(struct RawAudio)));
					FreeVec(inbuff);
				}
			}
			CloseIFF(iff);
		}
		Close(iff->iff_Stream);
	}
	FreeIFF(iff);
    }
}
