"""Re-spot the paper bag and carriage in the final stereo mix. Requires FFmpeg, NumPy and Pillow."""
import hashlib
import json
import subprocess
import tempfile
from pathlib import Path

import numpy as np
from PIL import Image, ImageDraw, ImageFont

ROOT = Path(__file__).resolve().parent
FPS, RATE = 24, 48000
SAMPLES = RATE // FPS
START = 566  # First kettle frame in the locked edit.
SOURCES = {
    'mix': ('../scene-one-v9/mix.flac', '38378419c41748a19d29edf7690c3c8df06e9f79694eeba4d9de08d4b15cbeb4'),
    'kettle': ('../scene-one/tea-sound.mp3', 'dd16957cd83b66a9499465a6061f9bc60630b4de87d4d1ca72d22f740952d6f4'),
    'picture': ('../scene-one-v8/pour.mp4', '8838846602d18a321ce37d710241cad88470bbe0a7ce0aad89f8acec127febd2'),
    'room': ('../yesterday/room.mp3', '5e60130853775fcd53306c95d686a15d17ddae36357dd10061c63ff98698bf57'),
}


def digest(path):
    return hashlib.sha256(path.read_bytes()).hexdigest()


def ffmpeg(*args, data=None):
    return subprocess.run(['ffmpeg', '-nostdin', '-v', 'error', '-y', *map(str, args)],
                          input=data, stdout=subprocess.PIPE, check=True).stdout


def decode(path, filters=None):
    args = ['-af', filters] if filters else []
    raw = ffmpeg('-i', path, '-vn', *args, '-ac', 2, '-ar', RATE, '-f', 'f32le', '-')
    return np.frombuffer(raw, '<f4').reshape(-1, 2)


def db(amplitude):
    return round(float(20*np.log10(max(amplitude, 1e-12))), 2)


def peak_window(clip):
    """Centre of the strongest 12 ms of sound, measured every millisecond."""
    square = np.square(clip.astype(np.float64)).mean(axis=1)
    prefix = np.r_[0, np.cumsum(square)]
    window, hop = 576, 48
    starts = np.arange(0, len(clip)-window+1, hop)
    energy = (prefix[starts+window]-prefix[starts])/window
    i = np.argmax(energy)
    return int(starts[i]+window//2), db(np.sqrt(energy[i]))


def render(sources):
    before = decode(sources['mix'])
    after = before.copy()
    tap = decode(sources['kettle'])*(10**(10/20))  # V7 effects +9 dB, master +1 dB.
    room = decode(sources['room'])*(10**(-6/20))
    # Remove only the old kettle stem between relative frames 3 and 52; ease in and out
    # over room-like parts of the take. The independent apartment room runs throughout.
    lo, hi = 3*SAMPLES, 52*SAMPLES
    out = (START*SAMPLES)+np.arange(lo, hi)
    old = tap[lo:hi]
    room_error = np.max(abs(before[out]-old-room[out % len(room)]))
    if room_error > 1e-6:
        raise ValueError('The kettle and room no longer account for the marked sound.')
    fade = np.ones(len(old))
    fade[:960] = np.linspace(0, 1, 960)
    fade[-1440:] = np.linspace(1, 0, 1440)
    after[out] -= old*fade[:, None]

    # The first two cues use separate pieces of fibrous treble from the original dispenser.
    # Keep the initial pressure knock out of the quieter carriage movement.
    cues = [
        ('Paper brushes the rim', .393, .510, 370, 5400, 578.12, -37.0),
        ('Bag lands inside the mug', .600, .795, 270, 4300, 582.35, -30.0),
        ('Carriage starts to travel', 1.49, 1.92, 175, 1600, 608.5, -43.0),
    ]
    placed = []
    for label, first, last, hp, lp, target, peak_db in cues:
        x = decode(sources['kettle'], f'highpass=f={hp},lowpass=f={lp},atrim=start={first}:end={last}').copy()
        duration = len(x)
        head = min(360, duration//4) if target < 600 else 2208
        tail = min(1440, duration//4)
        x[:head] *= np.linspace(0, 1, head)[:, None]
        x[-tail:] *= np.linspace(1, 0, tail)[:, None]
        x *= 10**(peak_db/20)/np.max(abs(x))
        peak, level = peak_window(x)
        put = round(target*SAMPLES)-peak
        after[put:put+len(x)] += x
        placed.append(dict(action=label, sourceSeconds=[first,last], passbandHz=[hp,lp],
                           timelineSample=put, endSampleExclusive=put+len(x), peakFrame=target,
                           peakDbfs=db(np.max(abs(x))), strongest12msRmsDbfs=level))
    target = ROOT/'mix.flac'
    pcm = np.rint(after * 2**23).astype('<i4').view(np.uint8).reshape(-1,4)[:, :3]
    ffmpeg('-f','s24le','-ar',RATE,'-ac',2,'-i','pipe:0','-map_metadata','-1',
           '-compression_level',8,target,data=pcm.tobytes())
    printed = decode(target)
    touched = np.flatnonzero(np.any(printed!=before,axis=1))
    if not len(touched) or touched[0]<out[0] or touched[-1]>out[-1]:
        raise ValueError('An audio sample outside the kettle edit changed.')
    local = printed[out]-room[out % len(room)]
    old_hit = old[(28-3)*SAMPLES:(35-3)*SAMPLES]
    place, level = peak_window(old_hit)
    late = local[(28-3)*SAMPLES:(35-3)*SAMPLES]
    if db(np.max(abs(late)))>-100:
        raise ValueError('The late low thud is still present.')
    return {
        'shotStartFrame':START,'frameNote':601,'fps':FPS,'sampleRate':RATE,
        'source':{k:dict(file=v[0],sha256=v[1]) for k,v in SOURCES.items()},
        'provider':{'tool':'Runway sound-effects','id':'51c101f9-ed97-4764-9a8f-b903f1bc3773',
                    'original':'Single six-second effect for the paper bag, carriage and running water.'},
        'pictureMarks':{'bagAtRim':578,'bagSettles':[582,583],
                        'carriageFirstTravel':[606,607],'carriageMoving':609},
        'originalLoudThud':{'peakFrame':round(START+28+place/SAMPLES,3),'peakDbfs':db(np.max(abs(old_hit))),
                            'strongest12msRmsDbfs':level,'tailAudibleAtMarkedFrame':601},
        'revisedCues':placed,'editWindowFrames':[START+3,START+52],
        'editWindowEndExclusive':True,'changedSamplesPerChannel':int(len(touched)),
        'unchangedSamplesPerChannel':int(len(before)-len(touched)),
        'previousKettleRoomReconstructionMaximumError':float(room_error),
        'lateThudResidualOverRoomPeakDbfs':db(np.max(abs(late))),
        'method':'The original loud low impact followed the visible landing. Its source was the combined generated mechanism and water take. Subtract that stem in a bounded window. Spot two short, filtered textures from its paper movement against the rim and settle. Keep a low mechanical tail for the first visible carriage travel. Preserve the original room, later water, feet and dialogue.',
        'mix':{'file':target.name,'sha256':digest(target),'samplesPerChannel':len(printed),'channels':2},
    }


def evidence(sources, receipt):
    picture = sources['picture']
    marks = [(577,'Just above rim'),(578,'Rim contact'),(582,'Settling'),(596,'Former thud'),(607,'Carriage moves')]
    selected = '+'.join(f'eq(n\\,{n-START})' for n, _ in marks)
    data = ffmpeg('-i',picture,'-vf',f'select={selected},crop=460:385:390:154,scale=230:192',
                  '-fps_mode','passthrough','-f','rawvideo','-pix_fmt','rgb24','-')
    font = ImageFont.load_default(size=15)
    sheet = Image.new('RGB',(len(marks)*234+4,220),'#191a18')
    draw = ImageDraw.Draw(sheet)
    stride = 230*192*3
    for i,(n,caption) in enumerate(marks):
        x = 4+i*234
        sheet.paste(Image.frombytes('RGB',(230,192),data[i*stride:(i+1)*stride]),(x,3))
        draw.text((x,198),f'{n}   {caption}',font=font,fill='#eeeadd')
    sheet.save(ROOT/'sound-spots.jpg',quality=92,subsampling=0)
    with tempfile.TemporaryDirectory() as temp:
        folder = Path(temp)
        # Two passes over the identical 72 camera frames at their actual mix level.
        for i,(label,sound) in enumerate([('V9',sources['mix']),('V10',ROOT/'mix.flac')]):
            bar = Image.new('RGB',(768,40),'#191a18')
            ImageDraw.Draw(bar).text((14,10),f'{label}   |   Paper, cup and carriage',
                                     font=ImageFont.load_default(size=18),fill='#eeeadd')
            bar.save(folder/f'{i}.png')
            ffmpeg('-i',picture,'-i',sound,'-loop',1,'-framerate',FPS,'-i',folder/f'{i}.png',
                   '-filter_complex_threads',2,'-filter_complex',
                   f'[0:v]trim=end_frame=72,scale=768:432,setsar=1[p];[p][2:v]vstack=shortest=1[v];'
                   f'[1:a]atrim=start_sample={START*SAMPLES}:end_sample={(START+72)*SAMPLES},asetpts=PTS-STARTPTS[a]',
                   '-map','[v]','-map','[a]','-c:v','libx264','-threads',2,'-crf',17,
                   '-pix_fmt','yuv420p','-c:a','alac',folder/f'{i}.mp4')
        out = ROOT/'sound-comparison.mp4'
        ffmpeg('-i',folder/'0.mp4','-i',folder/'1.mp4','-filter_complex_threads',2,'-filter_complex',
               '[0:v][0:a][1:v][1:a]concat=n=2:v=1:a=1[v][a]','-map','[v]','-map','[a]','-c:v','libx264',
               '-crf',17,'-threads',2,'-pix_fmt','yuv420p','-c:a','aac','-b:a','192k','-movflags','+faststart',out)
    receipt['comparison'] = dict(file=out.name,sha256=digest(out),order=['V9','V10'],
                                 durationSeconds=6,sourceFrames=[START,START+72],pictureSpots='sound-spots.jpg')


if __name__=='__main__':
    inputs = {k:ROOT/v[0] for k,v in SOURCES.items()}
    for role, item in inputs.items():
        if digest(item)!=SOURCES[role][1]:
            raise ValueError(f'Unexpected source file for {role}')
    result = render(inputs)
    evidence(inputs,result)
    (ROOT/'sound-receipt.json').write_text(json.dumps(result,indent=2,ensure_ascii=False)+'\n')
