// Detect It Easy: detection rule file
// Author: Kaens TG@kaens

meta("audio", "NeXT/Sun Au waveform audio (.AU,.SND)");

/* beautify ignore:start */
function detect() {
	//ref https://en.wikipedia.org/wiki/Au_file_format
	// & https://sox.sourceforge.net/AudioFormats-11.html#ss11.2
	// & http://soundfile.sapp.org/doc/NextFormat/soundstruct.h
	if (X.c("'.snd'")) { tp = 'BE'; en = _BE }
	// all these options, but only .snd is truly still found out there so I didn't test the rest
	else if (X.c("'dns.'")) { tp = 'LE'; en = _LE }
	else if (X.c("00'ds.'")) { tp = 'LE-ds.DEC'; en = _LE }
	else if (X.c("'.sd'00")) { tp = 'BE-ds.'; en = _BE }
	else return false;
	if (!isWithin(dataofs = X.U32(4, en), 0x18, X.Sz())) return false;
	bad = '';
	if (dataofs < 0x1C) bad = bad.addIfNone('!badofs'+Hex(dataofs));
	datasz = X.I32(8, en);
	ch = X.U32(0x14, en); if(!ch || ch > 0x100)  return false;
	sr = X.U32(0x10, en); if(!sr) return false;
	bDetected = true;
	sVersion = tp; fmt = X.U32(0xC, en);
	if (fmt > 0x1D) sVersion = sVersion.appendS('unknown format ('+Hex(fmt)+')', '/');
	else sVersion = sVersion.appendS(
		["unspecified format", "8-bit G.711 μ-law", "8-bit linear PCM", "16-bit linear PCM", "24-bit linear PCM",
		"32-bit linear PCM", "32-bit IEEE floating point", "64-bit IEEE floating point", "Fragmented sample data",
		"nested format", "DSP program", "DSP 8-bit fixed-point data", "DSP 16-bit fixed-point data",
		"DSP 24-bit fixed-point data", "DSP 32-bit fixed-point data", "unknown format (0Fh)",
		/*10*/"Sound Kit's visual data", "μ-law squelch", "16-bit linear w/emphasis", "16-bit linear compressed",
		"16-bit linear w/emphasis compressed", "Music Kit DSP commands", "Music Kit DSP commands: samples",
		"ITU-T G.721 4-bit ADPCM", "ITU-T G.722 4-bit SB-ADPCM", "ITU-T G.723 3-bit SB-ADPCM",
		"ITU-T G.723 5-bit SB-ADPCM", "8-bit G.711 A-law","AES",/*1D*/"8-bit Delta μ-law"][fmt], '/');
	if (bad.length) sVersion = sVersion.appendS('malformed'+bad,'/');
	if (X.isVerbose()) {
		info = []; t = 0x18;
		while(t < dataofs && t < X.Sz()) {
			if ((z = X.fSig(t, Math.min(X.Sz(),0x100,dataofs-t), "00")) < 0) z = dataofs;
			i = X.SC(t,z-t,'CP437').trim(); if(i.length) info.push(i); t = z+1
		}
		sOption(addEllipsis(info.join('; '), 0xC0), 'info:"', '"');
		sOption('ch:' + ch + ' s/r:' + (sr / 1000).toFixed(1) + 'kHz'+(datasz > 0? ' sz:'+outSz(dataofs+datasz): ''));
	}

	return result();
}
/* beautify ignore:end */