# Generate a set of mixed audio samples as if captured by a phased array of
# MICROPHONES, then decode a set of samples for a given focus point.
#
# Copyright (c) 2011, Ben Stewart. All Rights Reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer. Redistributions in binary
# form must reproduce the above copyright notice, this list of conditions and
# the following disclaimer in the documentation and/or other materials provided
# with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Known bugs:
# - Attenuation with distance is not implemented when mixing audio SOURCES down
#   to microphone outputs.
# - Non-isotropic behaviour of SOURCES and MICROPHONES is not implemented.
# - Only 44.1kHz, mono, 16-bit SOURCES are supported.
# - This code is pretty fugly.
#
# All measurements in this script are in metric units: metres, seconds, m/s.

import array
import math
import struct
import sys
import wave

AUDIO_VELOCITY = 340 # m/s
ENCODE = True
DECODE = True

# Calculate the propagation delay for audio over a given distance.
def delay_sec(distance_m):
    return distance_m / AUDIO_VELOCITY

# Get the magnitude of a vector.
def magnitude(vector):
    return math.sqrt(math.fsum(map(lambda i: i*i, vector)))

# Difference of two vectors with the same dimensions
def vector_sub(vec1, vec2):
    assert len(vec1) == len(vec2)
    return map(lambda (a,b): a-b, zip(vec1, vec2))


DIST_SRC = 5 # metres
MIC_SPACING = 0.2

MICROPHONE_GRID = [
    (0,  0 * MIC_SPACING, -3 * MIC_SPACING),
    (0,  0 * MIC_SPACING, -2 * MIC_SPACING),
    (0,  0 * MIC_SPACING, -1 * MIC_SPACING),
    (0,  0 * MIC_SPACING,  0 * MIC_SPACING),
    (0,  0 * MIC_SPACING,  1 * MIC_SPACING),
    (0,  0 * MIC_SPACING,  2 * MIC_SPACING),
    (0,  0 * MIC_SPACING,  3 * MIC_SPACING),

    (0,  1 * MIC_SPACING, -3 * MIC_SPACING),
    (0,  1 * MIC_SPACING, -2 * MIC_SPACING),
    (0,  1 * MIC_SPACING, -1 * MIC_SPACING),
    (0,  1 * MIC_SPACING,  0 * MIC_SPACING),
    (0,  1 * MIC_SPACING,  1 * MIC_SPACING),
    (0,  1 * MIC_SPACING,  2 * MIC_SPACING),
    (0,  1 * MIC_SPACING,  3 * MIC_SPACING),

    (0,  2 * MIC_SPACING, -3 * MIC_SPACING),
    (0,  2 * MIC_SPACING, -2 * MIC_SPACING),
    (0,  2 * MIC_SPACING, -1 * MIC_SPACING),
    (0,  2 * MIC_SPACING,  0 * MIC_SPACING),
    (0,  2 * MIC_SPACING,  1 * MIC_SPACING),
    (0,  2 * MIC_SPACING,  2 * MIC_SPACING),
    (0,  2 * MIC_SPACING,  3 * MIC_SPACING),

    (0,  3 * MIC_SPACING, -3 * MIC_SPACING),
    (0,  3 * MIC_SPACING, -2 * MIC_SPACING),
    (0,  3 * MIC_SPACING, -1 * MIC_SPACING),
    (0,  3 * MIC_SPACING,  0 * MIC_SPACING),
    (0,  3 * MIC_SPACING,  1 * MIC_SPACING),
    (0,  3 * MIC_SPACING,  2 * MIC_SPACING),
    (0,  3 * MIC_SPACING,  3 * MIC_SPACING),
]

FOCUSES = [
    (DIST_SRC, 0, 0),
    (DIST_SRC, 1, 0),
    (DIST_SRC, 1, 1),
]

SOURCES = [
    ("src0.wav", (DIST_SRC, 0, 0)),
    ("conv1.wav", (DIST_SRC, 1, 0)),
    ("conv2.wav", (DIST_SRC, 1, 1)),
]

def fmtVector(vec):
    return "(%s)" % (", ".join(map(lambda i: "%4.1f" % i, vec)))

def displayMicrophoneInfo(sources, microphones):
    print "%20s %20s %11s %11s %11s %11s" % ("From", "To", "Distance", "Delay", "Delta", "SampleDly")

    for _, src in sources:
        # Assume reference microphone is at 0, 0, 0
        baseline = magnitude(src)
        basetime = delay_sec(baseline)

        for mic in microphones:
            distance = magnitude(vector_sub(src, mic))
            delay = delay_sec(distance)
            difference = abs(delay - basetime)
            sampledelay = round(delay * 44100)
            print "%20s %20s  %9.3fm  %8.3fms  %8.3fms  %10d" % (
                fmtVector(src), fmtVector(mic),
                distance, delay * 1000, difference * 1000, sampledelay)

def encodeSources(sources, microphones):
    SOURCEFILES = map(lambda x: x[0], sources)
    SOURCES     = map(lambda x: x[1], sources)
    sourcewav = map(wave.open, SOURCEFILES)
    samplecount = min(map(lambda x: x.getnframes(), sourcewav))

    outno = 0
    outwav = []
    for mic in microphones:
        w = wave.open("microphone%d.wav" % outno, "w")
        w.setframerate(44100)
        w.setsampwidth(2)
        w.setnchannels(1)
        outwav.append(w)
        outno += 1

    for outid in xrange(len(microphones)):
        w = outwav[outid]
        samples = [0] * samplecount

        for inpid in xrange(len(SOURCES)):
            distance = magnitude(vector_sub(SOURCES[inpid], microphones[outid]))
            delay = delay_sec(distance)
            sampledelay = int(round(delay * 44100))

            win = wave.open(SOURCEFILES[inpid])
            inpdata = array.array('h')
            inpdata.fromstring(win.readframes(samplecount))

            for i in xrange(samplecount - sampledelay):
                # FIXME: not all samples are / by num srcs
                if i < len(inpdata):
                    samples[i + sampledelay] += inpdata[i]


        samples = map(lambda a: a / len(SOURCES), samples)
        data = array.array('h', samples)
        w.writeframes(data.tostring())
        w.close()

def decodeMicrophones(microphones, focuses):
    decodedid = 0

    for focus in focuses:
        mixed = []
        for outid in xrange(len(microphones)):
            mixed.append(wave.open('microphone%d.wav' % outid))

        samplecount = min(map(lambda x: x.getnframes(), mixed))

        decoded = wave.open('focus%d.wav' % decodedid, 'w')
        decoded.setframerate(44100)
        decoded.setsampwidth(2)
        decoded.setnchannels(1)

        samples = [0] * samplecount

        for outid in xrange(len(microphones)):
            distance = magnitude(vector_sub(focus, microphones[outid]))
            delay = delay_sec(distance)
            sampledelay = int(round(delay * 44100))

            mixdata = array.array('h')
            mixdata.fromstring(mixed[outid].readframes(samplecount))

            for i in xrange(samplecount - sampledelay):
                samples[i] += mixdata[i + sampledelay]

        samples = map(lambda a: a / len(microphones), samples)
        data = array.array('h', samples)
        decoded.writeframes(data.tostring())

        decodedid += 1

# Generate a ring of microphones, with an optional centre element
def generateRing(centreElem, numMicrophones, radius):
    assert numMicrophones >= 1

    microphones = []
    if centreElem:
        microphones.append((0, 0, 0))
        numMicrophones -= 1

    for i in xrange(numMicrophones):
        theta = 2 * math.pi * i / numMicrophones
        x = 0
        y = radius * math.sin(theta)
        z = radius * math.cos(theta)
        microphones.append((x, y, z))

    return microphones

def score(sources, focuses):
    assert len(sources) == len(focuses)
    for i in xrange(len(sources)):
        src = wave.open(sources[i][0])
        foc = wave.open('focus%d.wav' % i)
        samples = min(map(lambda x: x.getnframes(), [src, foc]))

        score = 1
        error = 0
        total = 0
        srcfr = src.readframes(samples)
        focfr = foc.readframes(samples)
        srcf = array.array('h')
        focf = array.array('h')
        srcf.fromstring(srcfr)
        focf.fromstring(focfr)

        for samp in xrange(samples):
            # FIXME: make a better scoring function.
            delta = abs(srcf[samp] - focf[samp])
            if delta > 0:
                error += math.log(delta, 2)
            total += 16

        score = 1 - (float(error) / total)
        print "%20s to %20s: %d %d %5.2f%%" % (sources[i][1], focuses[i], error, total, score * 100)

def main(argv):
    # microphones = MICROPHONE_GRID
    microphones = (generateRing(True, 10, 0.4))

    displayMicrophoneInfo(SOURCES, microphones)
    encodeSources(SOURCES, microphones)
    decodeMicrophones(microphones, FOCUSES)
    score(SOURCES, FOCUSES)

if __name__ == '__main__':
    main(sys.argv)
