#!/usr/bin/pythonw
#
# stpconvert.py
#
# Michael Pruett <michael@68k.org>
#
# Use Soundtrack Pro to convert an audio file to a different file format,
# sample format, or sample rate.
#
# File type is derived from output extension.
#
# EXAMPLES
# Convert file.aiff to a WAVE file called newfile.wav:
# % stconvert.py file.aiff newfile.wav
#
# Convert file.aiff to a 24-bit 48 kHz NeXT sound file:
# % stconvert.py file.aiff newfile.au integer 24 rate 48000

import appscript
import macfile
import sys, os

def fileTypeFromExtension(ext):
	if ext == ".aif" or ext == ".aiff" or ext == ".aifc":
		return u'AIFF File'
	elif ext == ".wav" or ext == ".wave":
		return u'WAVE File'
	elif ext == ".au" or ext == ".snd":
		return u'NeXT Sound File'

def usage():
	print "usage: stpconvert.py infile outfile [options]"
	print "where the following options specify the format of the output file"
	print "    integer n    n-bit integer audio file"
	print "    float        32-bit floating-point audio file"
	print "    rate r       sample rate r Hz"
	print "    dither       apply dither"
	sys.exit()

if len(sys.argv) < 3:
	usage()

outbitdepth = 0
outsampleformat = 0
outsamplerate = 0
outdither = 0

# Parse command-line arguments.
i = 3
while i < len(sys.argv):
	if sys.argv[i] == "integer":
		if i+1 >= len(sys.argv):
			usage()
		outsampleformat = appscript.k.integer
		outbitdepth = int(sys.argv[i+1])
		if (not outbitdepth in (8, 16, 24, 32)):
			outbitdepth = 0
		i = i+1
	elif sys.argv[i] == "float":
		outsampleformat = appscript.k.floating_point
		outbitdepth = 32
	elif sys.argv[i] == "rate":
		if i+1 >= len(sys.argv):
			usage()
		outsamplerate = int(sys.argv[i+1])
		i = i+1
	elif sys.argv[i] == "dither":
		outdither = 1
	i = i+1

infile = os.path.abspath(sys.argv[1])
outfile = os.path.abspath(sys.argv[2])
infilebasename = os.path.basename(infile)

outextension = os.path.splitext(outfile)[1]
outfiletype = fileTypeFromExtension(outextension)

stp = appscript.app('Soundtrack Pro')
stp.open(macfile.Alias(infile))
doc = stp.audio_file_documents[1]

saveargs = {'as':outfiletype,
	'in_':macfile.File(outfile)}

if outbitdepth != 0:
	saveargs['bit_depth'] = outbitdepth
if outsampleformat != 0:
	saveargs['bit_depth_type'] = outsampleformat
if outsamplerate != 0:
	saveargs['sample_rate'] = outsamplerate
if outdither != 0:
	saveargs['dither'] = outdither

doc.save(**saveargs)
doc.close()
