/*!
 * Modified Recorder.js to create small-sized recorded audio
 * Copyright (c) 2013 Matt Diamond
 * Licensed under MIT (https://github.com/mattdiamond/Recorderjs/blob/master/README.md)
 */
'use strict';
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var lodash_1 = __importDefault(require("lodash"));
var RecorderLib = /** @class */ (function () {
    function RecorderLib(cfg, sampleRate) {
        this.config = {
            bufferLen: 2048,
            numChannels: 1,
            mimeType: 'audio/wav'
        };
        this.recording = false;
        this.config = lodash_1.default.assign(this.config, cfg);
        this.onaudioprocess = this.onaudioprocess.bind(this);
        this.worker = (function () {
            var recLength = 0;
            var recBuffers = [];
            var sampleRate;
            var numChannels;
            return {
                init: function (config) {
                    sampleRate = config.sampleRate;
                    numChannels = config.numChannels;
                    initBuffers();
                },
                record: function (inputBuffer) {
                    for (var channel = 0; channel < numChannels; channel++) {
                        recBuffers[channel].push(inputBuffer[channel]);
                    }
                    recLength += inputBuffer[0].length;
                },
                exportWAV: function (type, cb) {
                    var buffers = [];
                    for (var channel = 0; channel < numChannels; channel++) {
                        buffers.push(mergeBuffers(recBuffers[channel], recLength));
                    }
                    var interleaved;
                    if (numChannels === 2) {
                        interleaved = interleave(buffers[0], buffers[1]);
                    }
                    else {
                        interleaved = buffers[0];
                    }
                    var dataview = encodeWAV(interleaved);
                    var audioBlob = new Blob([dataview], { type: type });
                    if (lodash_1.default.isFunction(cb)) {
                        cb(audioBlob);
                    }
                },
                getBuffer: function (cb) {
                    var buffers = [];
                    for (var channel = 0; channel < numChannels; channel++) {
                        buffers.push(mergeBuffers(recBuffers[channel], recLength));
                    }
                    if (lodash_1.default.isFunction(cb)) {
                        cb(buffers);
                    }
                },
                clear: function () {
                    recLength = 0;
                    recBuffers = [];
                    initBuffers();
                }
            };
            function initBuffers() {
                for (var channel = 0; channel < numChannels; channel++) {
                    recBuffers[channel] = [];
                }
            }
            function mergeBuffers(recBuffers, recLength) {
                var result = new Float32Array(recLength);
                var offset = 0;
                for (var i = 0; i < recBuffers.length; i++) {
                    result.set(recBuffers[i], offset);
                    offset += recBuffers[i].length;
                }
                return result;
            }
            function interleave(inputL, inputR) {
                var length = inputL.length + inputR.length;
                var result = new Float32Array(length);
                var index = 0;
                var inputIndex = 0;
                while (index < length) {
                    result[index++] = inputL[inputIndex];
                    result[index++] = inputR[inputIndex];
                    inputIndex++;
                }
                return result;
            }
            function floatTo16BitPCM(output, offset, input) {
                for (var i = 0; i < input.length; i++, offset += 2) {
                    var s = Math.max(-1, Math.min(1, input[i]));
                    output.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7fff, true);
                }
            }
            //added for single channel
            function floatTo8BitPCM(output, offset, input) {
                for (var i = 0; i < input.length; i++, offset++) {
                    var s = Math.max(-1, Math.min(1, input[i]));
                    var val = s < 0 ? s * 0x8000 : s * 0x7fff;
                    val = parseInt((255 / (65535 / (val + 32768))));
                    output.setInt8(offset, val, true);
                }
            }
            function writeString(view, offset, string) {
                for (var i = 0; i < string.length; i++) {
                    view.setUint8(offset + i, string.charCodeAt(i));
                }
            }
            function encodeWAV(samples) {
                var is2Channel = numChannels === 2;
                var sampleBits = is2Channel ? 16 : 8;
                var sampleBytes = sampleBits / 8;
                var dataLength = samples.length * sampleBytes;
                var buffer = new ArrayBuffer(44 + samples.length * sampleBytes);
                var view = new DataView(buffer);
                /* RIFF identifier */
                writeString(view, 0, 'RIFF');
                /* RIFF chunk length */
                view.setUint32(4, 36 + dataLength, true);
                /* RIFF type */
                writeString(view, 8, 'WAVE');
                /* format chunk identifier */
                writeString(view, 12, 'fmt ');
                /* format chunk length */
                view.setUint32(16, 16, true);
                /* sample format (raw) */
                view.setUint16(20, 1, true);
                /* channel count */
                view.setUint16(22, numChannels, true);
                /* sample rate */
                view.setUint32(24, sampleRate, true);
                /* byte rate (sample rate * block align) */
                view.setUint32(28, sampleRate * numChannels * sampleBytes, true);
                /* block align (channel count * bytes per sample) */
                view.setUint16(32, numChannels * sampleBytes, true);
                /* bits per sample */
                view.setUint16(34, sampleBits, true);
                /* data chunk identifier */
                writeString(view, 36, 'data');
                /* data chunk length */
                view.setUint32(40, dataLength, true);
                if (is2Channel) {
                    floatTo16BitPCM(view, 44, samples);
                }
                else {
                    floatTo8BitPCM(view, 44, samples);
                }
                return view;
            }
        })();
        this.worker.init({
            sampleRate: sampleRate,
            numChannels: this.config.numChannels
        });
    }
    RecorderLib.prototype.onaudioprocess = function (e) {
        if (!this.recording) {
            return;
        }
        var buffer = [];
        for (var channel = 0; channel < this.config.numChannels; channel++) {
            //should clone the samples instead of directly pushing them!!!
            buffer.push(new Float32Array(e.inputBuffer.getChannelData(channel)));
        }
        this.worker.record(buffer);
    };
    RecorderLib.prototype.record = function () {
        this.recording = true;
    };
    RecorderLib.prototype.stop = function () {
        this.recording = false;
    };
    RecorderLib.prototype.clear = function () {
        this.worker.clear();
    };
    RecorderLib.prototype.getBuffer = function (cb) {
        cb = cb || this.config.callback;
        if (!cb) {
            throw new Error('Callback not set');
        }
        this.worker.getBuffer(cb);
    };
    RecorderLib.prototype.exportWAV = function (cb, mimeType) {
        mimeType = mimeType || this.config.mimeType;
        cb = cb || this.config.callback;
        if (!cb) {
            throw new Error('Callback not set');
        }
        this.worker.exportWAV(mimeType, cb);
    };
    RecorderLib.forceDownload = function (blob, filename) {
        var url = (window.URL || window['webkitURL']).createObjectURL(blob);
        var link = window.document.createElement('a');
        link.href = url;
        link.download = filename || 'output.wav';
        var click = document.createEvent('Event');
        click.initEvent('click', true, true);
        link.dispatchEvent(click);
    };
    return RecorderLib;
}());
exports.RecorderLib = RecorderLib;
function getRecorderInputVolume(analyser, volume, reset, tweenIn, tweenOut) {
    if (tweenIn === void 0) { tweenIn = 1.618; }
    if (tweenOut === void 0) { tweenOut = 0; }
    tweenOut = tweenOut || tweenIn * 3;
    var buffer = new Uint8Array(analyser.fftSize);
    analyser.getByteTimeDomainData(buffer);
    var range = getDynamicRange(buffer) * (Math.E - 1);
    var currentVolume = Math.floor(Math.log1p(range) * 100);
    var tween = currentVolume > volume ? tweenIn : tweenOut;
    currentVolume = reset ? currentVolume : volume + (currentVolume - volume) / tween;
    return currentVolume;
}
exports.getRecorderInputVolume = getRecorderInputVolume;
function getDynamicRange(buffer) {
    var len = buffer.length;
    var min = 128;
    var max = 128;
    for (var i = 0; i < len; i++) {
        var sample = buffer[i];
        if (sample < min) {
            min = sample;
        }
        else if (sample > max) {
            max = sample;
        }
    }
    return (max - min) / 255;
}
//# sourceMappingURL=RecorderLib.js.map