#!/usr/bin/env python

import subprocess
import audioprocessing
import gdbm
import cPickle as pickle
import wave
import processing
import time
import sys
import os


description = """This program calculates the Butterscotch signature of all files in the supplied playlist, then stores them into a GDBM database, as pickled strings.

Refer to the butterscotch command for the default parameters of Butterscotch signatures."""

shortcmdline = "[options] cache.gdbm playlist.m3u"

parser = audioprocessing.parser(shortcmdline,description)

options,args = parser.parse_args()

if len(args) != 2:
	parser.print_help()
	sys.exit(os.EX_USAGE)

dictionaryname,playlist = args

def do_one(filename):
	try:
		signature = audioprocessing.mp3_butterscotch(filename,
			options.blocks,options.spb,options.bands)
		if not options.use_full_spectrum: signature = signature.halve_highest_freq()
		if options.use_dB: signature = signature.as_dB()
		if not options.use_linear_bands: signature = signature.as_log_bands()
		print "%s:\n%s"%(filename,signature)
		return (filename,signature)
	except Exception,e:
		print "%s:\nSignature failed: %s"%(filename,str(e))
		return (filename,None)

dictionary = gdbm.open(dictionaryname,"c")
pool = processing.Pool(2) #FIXME numcpus

already = dictionary.keys()

files = [ s.strip() for s in file(playlist).readlines() if s.strip() ]
files = [ f for f in files if f.endswith(".mp3") and not f.startswith("#") and not f in already ]

times = [time.time()]
def avg(lst): return sum(lst) / len(lst)
for filename, result in pool.imap_unordered(do_one,files):
	times.append(time.time())
	if not result: continue
	since_last = times[-1] - times[-2]
	average = avg(tuple(audioprocessing.util.deltas(times)))
	num_processed = len(times) - 1
	num_left = len(files) - num_processed
	eta = average * num_left
	print "%.02f since last song, %02f average, ETA %.01f"%(since_last,average,eta)
	if result: dictionary[filename] = pickle.dumps(result)

dictionary.close()
