annot-server/static/js/pianoroll.js
author ymh <ymh.work@gmail.com>
Mon, 12 Jan 2015 14:08:09 +0100
changeset 82 ae37d35a419c
parent 79 bd2f2c3f205c
permissions -rw-r--r--
Added tag V01.00 for changeset a6bbf198bd24

// Config vars
var logger = false;
var sceneWidth = 1920;
var prHeight1 = 435;
var prHeight2 = 645;
var sceneHeight = prHeight1 + prHeight2;
var sceneBgColor = 0xFFFFFF;
var lineColor = 0x444444;
var pixelsPerSecond1 = Math.floor(sceneWidth / 10); // nb of pixels per second
var manualFramerate = pixelsPerSecond1 / 4;
var pixelsPerSecond2 = Math.floor(sceneWidth / 60); // nb of pixels per second
var lineInterval = 5000; // means line every 5 seconds
var nbLines = -1;
var noteHeight = 110;
var noteColors = [0xB90000, 0x4BDD71, 0xAF931E, 0x1C28BA, 0x536991];
var colorsReg = {}
// Vars
var noteDict = [];
// Timecode method
var timePageLoaded = Date.now();
var offsetMusic = false;


//create an new instance of a pixi stage
var stage = new PIXI.Stage(sceneBgColor);

//create a renderer instance.
var renderer = PIXI.autoDetectRenderer(sceneWidth, sceneHeight);

//add the renderer view element to the DOM
document.getElementById("canvasContainer").appendChild(renderer.view);

var uberContainer = new PIXI.DisplayObjectContainer();
uberContainer.position.x = Math.floor(sceneWidth*9/10);
uberContainer.position.y = 0;
stage.addChild(uberContainer);


function PianoRoll(parentContainer, xInit, yInit, height, linesDown, pixelsPerSecond, width, noteColors, colorsReg){
    var _this = this;
    this.container = new PIXI.DisplayObjectContainer();
    this.container.position.x = xInit;
    this.container.position.y = yInit;
    parentContainer.addChild(this.container);

    this.linesDown = linesDown;
    this.height = height;
    this.pixelsPerSecond = pixelsPerSecond;
    this.width = width;
    this.noteColors = noteColors;
    this.colorsReg = colorsReg || {}

    this.addNote = function(note, startTime, duration, velocity, canal){
        //console.log("coucou 1", note, timeFromZero, ts, velocity, pixelsPerSecond, container, prHeight);
        var beginX = (offsetMusic + startTime) * this.pixelsPerSecond / 1000;
        var width = duration * this.pixelsPerSecond / 1000;
        // We draw the rectangle
        var graphics = new PIXI.Graphics();
        //console.log("beginX = ", beginX, "canal = ", canal, "color = ", noteColor[canal], "width = ", width, "note = ", note, "velocity = ", velocity);
        var color = this.colorsReg[canal];
        if(typeof(color) === 'undefined') {
            var colorsRegSize = Object.keys(this.colorsReg).length
            if(colorsRegSize < this.noteColors.length) {
                color = this.colorsReg[canal] = this.noteColors[colorsRegSize];
            }
            else {
                color = this.colorsReg[canal] = parseInt(randomColor({ luminosity: 'light', hue: 'random', format:'hex'}).replace(/^#/, ''), 16);
            }
        }
        graphics.beginFill(color, (velocity / 128));
        var y = (128-note) * this.height / 128; // (128-note) because y = 0 is for note = 128 and y = 128 for note = 0
        graphics.drawRect(0, Math.floor(y - (noteHeight/2) + ((this.height / 128)/2)), width, noteHeight);
        graphics.endFill();
        graphics.x = beginX;
        this.container.addChild(graphics);
    };

    this.addLine = function(lineNb){
        var graphics = new PIXI.Graphics();
        var x = -this.container.x;
        graphics.beginFill(0xFFFF00);
        graphics.lineStyle(1, lineColor);
        var y = this.linesDown ? this.height - 20 : 0;
        graphics.moveTo(x, y);
        graphics.lineTo(x, y + 20);
        graphics.endFill();
        this.container.addChild(graphics);
        // Add text
        var totalSec = lineNb * lineInterval / 1000;
        var hours = parseInt( totalSec / 3600 ) % 24;
        var minutes = parseInt( totalSec / 60 ) % 60;
        var seconds = totalSec % 60;
        var timeStr = (hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds  < 10 ? "0" + seconds : seconds);
        var fontObj = { font: "10pt Arial", fill: "#444444" };
        var t = new PIXI.Text(timeStr, fontObj);
        t.x = x + 2;
        t.y = this.linesDown ? this.height - 15 : 2;
        this.container.addChild(t);
    };

    this.moveTo = function(diffTime){
        this.container.x = Math.floor(diffTime*this.pixelsPerSecond);
    };

    this.removePassedObjets = function(){
        var nbChilds = _this.container.children.length;
        var i = 0, childIsNowDisplayed = false;
        while(i<nbChilds && !childIsNowDisplayed){
            var child = _this.container.children[0];
            //console.log("remove ? ", child.x, child.width, ((child.x + child.width) < (Math.abs(_this.container.x) - _this.width)));
            if((child.x + child.width) < (Math.abs(_this.container.x) - _this.width)){
                _this.container.removeChild(child);
                //console.log("    remove !!!");
            }
            else{
                childIsNowDisplayed = true;
                //console.log("    childIsNowDisplayed");
            }
            i++;
        }
        //console.log("before : ", nbChilds, ", after : ", _this.container.children.length);
    };

    // remove notes each scene width
    var removeInterval = window.setInterval(this.removePassedObjets, 1000 * sceneWidth / this.pixelsPerSecond );

}

// Init containers
var containerList = [];
containerList.push(new PianoRoll(uberContainer, 0, 0, prHeight1, true, pixelsPerSecond1, sceneWidth, noteColors, colorsReg));
containerList.push(new PianoRoll(uberContainer, 0, prHeight1, prHeight2, false, pixelsPerSecond2, sceneWidth, noteColors, colorsReg));

// Line between two containers
var graphics = new PIXI.Graphics();
graphics.beginFill(0xFFFF00);
graphics.lineStyle(1, lineColor);
graphics.moveTo(0, prHeight1);
graphics.lineTo(sceneWidth, prHeight1);
graphics.endFill();
stage.addChild(graphics);


function replaceContainers(){
    var diff = (Date.now() - timePageLoaded)/1000;// nb of seconds since page loaded
    //console.log("replace ! diff1 = ", container1.x - Math.floor(-diff*pixelsPerSecond1), ", diff 2 = ", container2.x - Math.floor(-diff*pixelsPerSecond2));
    for(var i=0;i<containerList.length;i++){
        containerList[i].moveTo(-diff);
    }
    renderer.render(stage);
}

function addNotes(data){
    if(!offsetMusic){
        // get difference between the current note timecode and my zero to set the difference between the canvas's zero and the music's zero
        // in order to place in real time
        var now = Date.now();
        var timeBetweenNowAndStart = now - timePageLoaded;
        offsetMusic = timeBetweenNowAndStart - data.content[1];
        //console.log("start: ", timePageLoaded, ", now: ", now, ", timeBetweenNowAndStart = ", timeBetweenNowAndStart, ", offsetMusic = ", offsetMusic);
    }
    var note = data.content[3];
    var velocity = data.content[4];
    if(velocity===0){
        if(typeof noteDict[data.content[2]][note]!=='undefined'){
            // We close the note in container one
            //console.log("coucou 2", data);
            var duration = data.content[1] - noteDict[data.content[2]][note].ts;
            for(var i=0;i<containerList.length;i++){
                //               addNote(note, startTime,                          duration, velocity,                                 canal)
                containerList[i].addNote(note, noteDict[data.content[2]][note].ts, duration, noteDict[data.content[2]][note].velocity, data.content[2]);
            }
            // delete entry
            delete noteDict[data.content[2]][note];
        }
    }
    else{
        if(typeof noteDict[data.content[2]]==='undefined'){
            noteDict[data.content[2]] = {};
        }
        noteDict[data.content[2]][note] = {ts: data.content[1], velocity:velocity};
    }
}

function addLine(){
    nbLines++;
    for(var i=0;i<containerList.length;i++){
        containerList[i].addLine(nbLines);
    }
}



// Socket management
var sock = null;
var ellog = null;
function log(m) {
    if(logger){
        ellog.innerHTML += m + '\n';
        ellog.scrollTop = ellog.scrollHeight;
    }
}
window.onload = function(){

    if(logger){
        ellog = document.getElementById('log');
    }
    else{
        document.body.removeChild(document.getElementById('log'));
    }

    var wsuri;
    if (window.location.protocol === "file:") {
       wsuri = "ws://127.0.0.1:8090/broadcast";
    } else {
       wsuri = "ws://" + window.location.hostname + ":8090/broadcast";
    }
    wsuri = wsuri + "?channel=PIANOROLL&event_code="+event_code;

    if ("WebSocket" in window) {
       sock = new WebSocket(wsuri);
    } else if ("MozWebSocket" in window) {
       sock = new MozWebSocket(wsuri);
    } else {
       log("Browser does not support WebSocket!");
       window.location = "http://autobahn.ws/unsupportedbrowser";
    }

    if (sock) {
        sock.onopen = function(){
            if(logger){
                log("Connected to " + wsuri);
            }
        }

        sock.onclose = function(e) {
            if(logger){
                log("Connection closed (wasClean = " + e.wasClean + ", code = " + e.code + ", reason = '" + e.reason + "')");
            }
            sock = null;
        }

        sock.onmessage = function(e) {
            if(logger){
                log("Got message: " + e.data);
            }
            addNotes(JSON.parse(e.data));
        }
    }
};


// Init page and intervals
addLine();
var moveInterval = window.setInterval(replaceContainers, 1000/manualFramerate);
var verticalLinesInterval = window.setInterval(addLine, lineInterval);

// Little inteval to show time
var nbSec = 0;
var mySpan = document.getElementById("myspan");
function updateTime(){
    nbSec++;
    var hours = parseInt( nbSec / 3600 ) % 24;
    var minutes = parseInt( nbSec / 60 ) % 60;
    var seconds = nbSec % 60;
    var timeStr = (hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds  < 10 ? "0" + seconds : seconds);
    mySpan.innerHTML = timeStr;
}
var secondInterval = window.setInterval(updateTime, 1000);