# HG changeset patch # User ymh # Date 1421679317 -3600 # Node ID f58715468f1efff51eafa413ef722bb7bc39d747 # Parent 806739a2685816cf96f839306f0a12ddbd9cf6a4# Parent a323578ea954b64dab616ce82381f1aa6e140ff4 Merged revison 95 diff -r a323578ea954 -r f58715468f1e annot-server/websockets.py --- a/annot-server/websockets.py Mon Jan 19 09:52:52 2015 +0100 +++ b/annot-server/websockets.py Mon Jan 19 15:55:17 2015 +0100 @@ -1,4 +1,3 @@ - # # See LICENCE for detail # Copyright (c) 2014 IRI @@ -50,8 +49,8 @@ def register(self, client): if not client in self.clients: - print("registered client {}".format(client.peer)) - self.clients.append(client) + print("registered client {}".format(client.peer)) + self.clients.append(client) def unregister(self, client): if client in self.clients: @@ -60,11 +59,11 @@ if client in self.filters: self.filters.pop(client, None) - def broadcast(self, msg, filter): + def broadcast(self, msg, filter_list): print("broadcasting prepared message '{}' ..".format(msg)) preparedMsg = self.prepareMessage(msg) for c in self.clients: - if all([ (k in filter and filter[k] in v) for k,v in self.filters.get(c, {}).items()]): + if all([ (k in filter_list and filter_list[k] in v) for k,v in self.filters.get(c, {}).items()]): c.sendPreparedMessage(preparedMsg) print("prepared message sent to {}".format(c.peer)) diff -r a323578ea954 -r f58715468f1e client/annotviz/app/index.html --- a/client/annotviz/app/index.html Mon Jan 19 09:52:52 2015 +0100 +++ b/client/annotviz/app/index.html Mon Jan 19 15:55:17 2015 +0100 @@ -7,29 +7,19 @@ - Piano Roll + Piano Roll Tests -

Piano Roll

- -
+

Piano Roll Tests

- stop intervals - - temps écoulé : +

-

-    
-    
-    
-    
 
 
diff -r a323578ea954 -r f58715468f1e client/annotviz/app/js/doubleroll.js
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/client/annotviz/app/js/doubleroll.js	Mon Jan 19 15:55:17 2015 +0100
@@ -0,0 +1,290 @@
+/**
+* scripts/doubleroll.js
+*
+* This is the starting point for your application.
+* Take a look at http://browserify.org/ for more info
+*/
+
+/* global window: false */
+/* global document: false */
+/* global WebSocket: false */
+/* global MozWebSocket: false */
+
+'use strict';
+
+
+var PIXI = require('pixi');
+var _ = require('lodash');
+var PianoRoll = require('./pianoroll.js');
+
+var NTP_EPOCH_DELTA = 2208988800; //c.f. RFC 868
+
+var defaultConfig = {
+    orientation: 'horizontal',
+    logger: false,
+    sceneWidth: 1920,
+    pianorolls : [
+      {
+        height: 435,
+        timeWidth: 10,
+        lineInterval: 5000,
+        noteHeight: undefined
+      },
+      {
+        height: 645,
+        timeWidth: 60,
+        lineInterval: 5000,
+        noteHeight: undefined
+      },
+    ],
+    framerate: 25,
+    offsetMusic: false,
+    sceneBgColor: 0xFFFFFF,
+    lineColor: 0x444444,
+    lineFillColor: 0xFFFF00,
+    noteColors: [0xB90000, 0x4BDD71, 0xAF931E, 0x1C28BA, 0x536991],
+    canvasContainer: 'canvasContainer',
+    logContainer: 'log',
+    timeContainer: 'timeStarted',
+    noteHeight: undefined,
+    zeroShift: 0.9,
+    timeWidth: 60,
+    lineInterval: 5000,
+    annotationChannel: 'PIANOROLL'
+//    wsUri: undefined,
+//    eventCode: undefined
+
+};
+
+function DoubleRoll(options) {
+
+    var _this = this;
+    var opts = _(options).defaults(defaultConfig).value();
+
+    var orientation = opts.orientation;
+    var isHorizontal = (orientation !== 'vertical');
+
+    this.logger = opts.logger;
+    this.lineColor = opts.lineColor;
+    this.lineFillColor = opts.lineFillColor;
+    this.framerate = opts.framerate;
+    this.offsetMusic = opts.offsetMusic;
+    this.noteColors = opts.noteColors;
+
+    var noteHeight = opts.noteHeight;
+    var sceneBgColor = opts.sceneBgColor;
+    var sceneHeight = opts.sceneHeight || _(opts.pianorolls).reduce(function(s,p) { return s + p.height; }, 0);
+    var timeWidth = opts.timeWidth;
+    var lineInterval = opts.lineInterval;
+    var offsetMusic = opts.offsetMusic;
+
+    var sceneWidth = opts.sceneWidth;
+    var canvasContainer = opts.canvasContainer;
+    var logContainer = opts.logContainer;
+    var timeContainer = opts.timeContainer;
+
+    var zeroShift = opts.zeroShift;
+
+    var eventCode = opts.eventCode;
+    var annotationChannel = opts.annotationChannel;
+    var wsUri = opts.wsUri;
+    if(!wsUri) {
+        if (window.location.protocol === 'file:') {
+            wsUri = 'ws://127.0.0.1:8090/broadcast';
+        }
+        else {
+            wsUri = 'ws://' + window.location.hostname + ':8090/broadcast';
+        }
+        wsUri += '?channel='+annotationChannel+'&event_code='+eventCode;
+    }
+
+
+    var colorsReg = {};
+
+    //create an new instance of a pixi stage
+    var stage = new PIXI.Stage(sceneBgColor);
+    //create a renderer instance.
+    var renderer = PIXI.autoDetectRenderer(sceneWidth, sceneHeight);
+
+    var uberContainer = new PIXI.DisplayObjectContainer();
+    uberContainer.x = Math.floor(sceneWidth*zeroShift);
+    uberContainer.y = 0;
+    stage.addChild(uberContainer);
+
+    var pianorollList = [];
+
+    var pianorollOptions = {
+        parentContainer: uberContainer,
+        orientation: orientation,
+        xInit: 0,
+        width: sceneWidth,
+        noteColors: this.noteColors,
+        colorsReg: colorsReg,
+        lineColor: this.lineColor,
+        lineInterval: lineInterval,
+        offsetMusic: offsetMusic,
+    };
+
+    var yInit = 0;
+    var linesDown = true;
+    _(opts.pianorolls).forEach(function(prDef, i) {
+        var prNoteHeight = noteHeight || prDef.noteHeight || prDef.height / 128;
+        var prTimeWidth = prDef.timeWidth || timeWidth;
+        pianorollList.push(new PianoRoll(_({
+            yInit: yInit,
+            height: prDef.height,
+            linesDown: linesDown,
+            pixelsPerSecond: Math.floor(sceneWidth / prTimeWidth),
+            noteHeight: prNoteHeight,
+            lineInterval: prDef.lineInterval
+        }).defaults(pianorollOptions).value()));
+        yInit += prDef.height;
+        linesDown = !linesDown;
+
+        if(i<(opts.pianorolls.length-1)) {
+            var lineGraphics = new PIXI.Graphics()
+                .beginFill(_this.lineFillColor)
+                .lineStyle(1, _this.lineColor)
+                .moveTo(Math.floor(sceneWidth*zeroShift), yInit)
+                .lineTo(-sceneWidth - Math.floor(sceneWidth*zeroShift), yInit)
+                .endFill();
+            uberContainer.addChild(lineGraphics);
+        }
+    });
+
+    if(!isHorizontal) {
+        uberContainer.rotation = Math.PI/2;
+        uberContainer.y = sceneHeight;
+        uberContainer.x = sceneWidth;
+    }
+
+
+    this.init = function() {
+
+        if(typeof(canvasContainer) === 'string') {
+            canvasContainer = document.getElementById(canvasContainer);
+        }
+        if(typeof(logContainer) === 'string') {
+            logContainer = document.getElementById(logContainer);
+        }
+        if(typeof(timeContainer) === 'string') {
+            timeContainer = document.getElementById(timeContainer);
+        }
+
+
+        if(!this.logger){
+            document.body.removeChild(logContainer);
+            logContainer = undefined;
+        }
+        var sock;
+
+        canvasContainer.appendChild(renderer.view);
+
+        if ('WebSocket' in window) {
+            sock = new WebSocket(wsUri);
+        } else if ('MozWebSocket' in window) {
+            sock = new MozWebSocket(wsUri);
+        } else {
+            this.log('Browser does not support WebSocket!');
+            window.location = 'http://autobahn.ws/unsupportedbrowser';
+        }
+
+        if (!sock) {
+            return;
+        }
+        sock.onopen = function(){
+            if(_this.logger){
+                _this.log('Connected to ' + _this.wsUri);
+            }
+        };
+
+        sock.onclose = function(e) {
+            if(_this.logger){
+                _this.log('Connection closed (wasClean = ' + e.wasClean + ', code = ' + e.code + ', reason = \'' + e.reason + '\')');
+            }
+            sock = null;
+        };
+
+        sock.onmessage = function(e) {
+            var dataJson = JSON.parse(e.data);
+            if(_this.logger){
+                var dataDate = new Date((dataJson.content[0]-NTP_EPOCH_DELTA)*1000);
+                _this.log('Got message: ' + e.data + ' - ' + dataDate.toISOString());
+            }
+            _this.addNotes(dataJson);
+        };
+
+    };
+
+
+    this.addNotes = function(data) {
+        var note = data.content[3];
+        var velocity = data.content[4];
+        var ts = (data.content[0] - NTP_EPOCH_DELTA)*1000;
+        var channel = data.content[2];
+        var sessionTs = data.content[1];
+
+        pianorollList.forEach(function(c) {
+            c.addNote(note, ts, sessionTs, velocity, channel, 0);
+        });
+    };
+
+    this.refreshStage = function() {
+        pianorollList.forEach(function(c) {
+            c.move();
+        });
+        renderer.render(stage);
+    };
+
+    // Init page and intervals
+    var refreshInterval;
+    var refreshTimeInterval;
+    var startTs;
+
+    this.updateTime = function(){
+        var nbSec = (Date.now() - startTs) / 1000;
+        var hours = Math.floor( nbSec / 3600 ) % 24;
+        var minutes = Math.floor( nbSec / 60 ) % 60;
+        var seconds = Math.floor(nbSec % 60);
+        var timeStr = (hours < 10 ? '0' + hours : hours) + ':' + (minutes < 10 ? '0' + minutes : minutes) + ':' + (seconds  < 10 ? '0' + seconds : seconds);
+        timeContainer.innerHTML = timeStr;
+    };
+
+    this.start = function() {
+
+        startTs = Date.now();
+        refreshInterval = window.setInterval(function() {_this.refreshStage();}, 1000/this.framerate);
+        refreshTimeInterval = window.setInterval(function() {_this.updateTime();}, 1000);
+        pianorollList.forEach(function(c) {
+            c.start();
+        });
+    };
+
+    this.stop = function() {
+        window.clearInterval(refreshInterval);
+        window.clearInterval(refreshTimeInterval);
+        pianorollList.forEach(function(c) {
+            c.stop();
+        });
+    };
+
+
+    this.log = function(m) {
+        if(this.logger){
+            this.logContainer.innerHTML += m + '\n';
+            this.logContainer.scrollTop = logContainer.scrollHeight;
+        }
+    };
+
+
+    window.onload = function() {
+        _this.init();
+        _this.start();
+    };
+
+    return this;
+}
+
+module.exports = {
+    DoubleRoll: DoubleRoll
+};
diff -r a323578ea954 -r f58715468f1e client/annotviz/app/js/main.js
--- a/client/annotviz/app/js/main.js	Mon Jan 19 09:52:52 2015 +0100
+++ b/client/annotviz/app/js/main.js	Mon Jan 19 15:55:17 2015 +0100
@@ -7,284 +7,8 @@
 
 'use strict';
 
-
-var PIXI = require('pixi');
-
-// Config vars
-var horizontalView = false;
-var logger = false;
-var sceneWidth = 1920;
-var sceneHeight = 1080;
-var prSize1 = 435;
-var prSize2 = 435;
-var prSize3 = 300;
-var sceneBgColor = 0xFFFFFF;
-var lineColor = 0x444444;
-if (horizontalView){
-	var pixelsPerSecond1 = Math.floor(sceneWidth / 10); // nb of pixels per second
-} else{
-	var pixelsPerSecond1 = Math.floor(sceneHeight / 10); // nb of pixels per second
-}
-var manualFramerate = pixelsPerSecond1 / 4;
-if (horizontalView){
-	var pixelsPerSecond2 = Math.floor(sceneWidth / 60); // nb of pixels per second
-} else {
-	var pixelsPerSecond2 = Math.floor(sceneHeight / 60); // nb of pixels per second
-}
-var pixelsPerSecond3 = Math.floor(sceneHeight / 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();
-if (horizontalView){
-	uberContainer.position.x = Math.floor(sceneWidth*9/10);
-	uberContainer.position.y = 0;
-} else {
-	uberContainer.position.x = 0;
-	uberContainer.position.y = Math.floor(sceneHeight*9/10);
-}
-stage.addChild(uberContainer);
-
-/* ---------------------------------------------------------------- */
-/* ------------------- Init Pianoroll containers ------------------ */
-/* ---------------------------------------------------------------- */
-
-var PianoRoll = require('./pianoroll.js')
-
-var containerList = [];
-
-if (horizontalView){
-	containerList.push(new PianoRoll(uberContainer, 0, 0, prSize1, true, pixelsPerSecond1, sceneWidth, noteColors, colorsReg, lineColor, lineInterval, offsetMusic, prSize1 / 128, horizontalView));
-	containerList.push(new PianoRoll(uberContainer, 0, prSize1, prSize2, false, pixelsPerSecond2, sceneWidth, noteColors, colorsReg, lineColor, lineInterval, offsetMusic, prSize2 / 128, horizontalView));
-} else {
-//	containerList.push(new PianoRoll(uberContainer, sceneWidth - prSize1, 0, sceneHeight, true, pixelsPerSecond1, prSize1, noteColors, colorsReg, lineColor, lineInterval, offsetMusic, prSize1 / 128, horizontalView));
-//	containerList.push(new PianoRoll(uberContainer, sceneWidth - (prSize1 + prSize2), 0, sceneHeight, false, pixelsPerSecond2, prSize2, noteColors, colorsReg, lineColor, lineInterval, offsetMusic, prSize2 / 128, horizontalView));
-	containerList.push(new PianoRoll(uberContainer, sceneWidth - prSize1, 0, sceneHeight, false, pixelsPerSecond2, prSize2, noteColors, colorsReg, lineColor, lineInterval, offsetMusic, prSize2 / 128, horizontalView));
-}
-
-// Line between two containers
-var graphics = new PIXI.Graphics();
-graphics.beginFill(0xFFFF00);
-graphics.lineStyle(1, lineColor);
-if (horizontalView){
-	graphics.moveTo(0, prSize1);
-	graphics.lineTo(sceneWidth, prSize1);
-} else {
-	graphics.moveTo(sceneWidth - prSize1, 0);
-	graphics.lineTo(sceneWidth - prSize1, sceneHeight);
-	graphics.moveTo(sceneWidth - (prSize1 + prSize3), 0);
-	graphics.lineTo(sceneWidth - (prSize1 + prSize3), sceneHeight);
-}
-graphics.endFill();
-stage.addChild(graphics);
-
-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];
-    }
-    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
-            var duration = data.content[1] - noteDict[data.content[2]][note].ts;
-            for(var i=0;i
+
+
+    
+    
+    
+    
+    
+
+    Piano Roll
+
+    
+    
+
+
+
+    

Piano Roll

+ +
+

+ stop intervals - + start intervals - + temps écoulé : +

+

+    
+    
+    
+
+
diff -r a323578ea954 -r f58715468f1e client/annotviz/app/pianoroll_v.html
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/client/annotviz/app/pianoroll_v.html	Mon Jan 19 15:55:17 2015 +0100
@@ -0,0 +1,37 @@
+
+
+
+    
+    
+    
+    
+    
+
+    Piano Roll Vertical
+
+    
+    
+
+
+
+    

Piano Roll vertical

+ +
+

+ stop intervals - + start intervals - + temps écoulé : +

+

+    
+    
+    
+
+
diff -r a323578ea954 -r f58715468f1e client/annotviz/bower.json
--- a/client/annotviz/bower.json	Mon Jan 19 09:52:52 2015 +0100
+++ b/client/annotviz/bower.json	Mon Jan 19 15:55:17 2015 +0100
@@ -3,6 +3,7 @@
   "version": "0.0.0",
   "dependencies": {
     "randomColor": "davidmerfield/randomColor#~0.1.1",
-    "pixi": "~2.2.3"
+    "pixi": "~2.2.3",
+    "lodash": "~2.4.1"
   }
 }
diff -r a323578ea954 -r f58715468f1e client/annotviz/gulp/tasks/browserify.js
--- a/client/annotviz/gulp/tasks/browserify.js	Mon Jan 19 09:52:52 2015 +0100
+++ b/client/annotviz/gulp/tasks/browserify.js	Mon Jan 19 15:55:17 2015 +0100
@@ -15,6 +15,7 @@
   return browserify({debug: true})
     .require('./app/lib/pixi/bin/pixi.js', { expose: 'pixi' })
     .require('./app/lib/randomColor/randomColor.js', {expose: 'randomColor'})
+    .require('./app/lib/lodash/dist/lodash.js', {expose: 'lodash'})
     .bundle()
     .pipe(source('libs-'+p.name+'.js'))
     .pipe(gulp.dest(config.dist + '/js/'));
@@ -26,6 +27,7 @@
     .add('./app/js/main.js')
     .external('pixi')
     .external('randomColor')
+    .external('lodash')
     .transform(partialify) // Transform to allow requireing of templates
     .bundle()
     .pipe(source(p.name+'.js'))
diff -r a323578ea954 -r f58715468f1e client/pianoroll/app/js/main.js
--- a/client/pianoroll/app/js/main.js	Mon Jan 19 09:52:52 2015 +0100
+++ b/client/pianoroll/app/js/main.js	Mon Jan 19 15:55:17 2015 +0100
@@ -84,7 +84,7 @@
     }
     var note = data.content[3];
     var velocity = data.content[4];
-    if(velocity===0){
+    if(velocity===0) {
         if(typeof noteDict[data.content[2]][note]!=='undefined'){
             // We close the note in container one
             //console.log("coucou 2", data);
diff -r a323578ea954 -r f58715468f1e utils/pianoroll-client.py
--- a/utils/pianoroll-client.py	Mon Jan 19 09:52:52 2015 +0100
+++ b/utils/pianoroll-client.py	Mon Jan 19 15:55:17 2015 +0100
@@ -7,6 +7,7 @@
 
 import argparse
 import csv
+import signal
 import time
 
 import ntplib
@@ -19,7 +20,7 @@
     """
     Example that sends UDP messages.
     """
-    def __init__(self, port, host, address, rows, shift):
+    def __init__(self, port, host, address, rows, shift, token):
         self.port = port
         self.host = host
         self.client = async.DatagramClientProtocol()
@@ -27,6 +28,7 @@
         self.rows = rows
         self.address = address
         self.shift = shift
+        self.token = token
         reactor.callLater(0, self.send_messages)
 
     def _send(self, element):
@@ -36,19 +38,31 @@
 
     def send_messages(self):
         t0 = time.time()
+        #tc = 0
         for row in self.rows:
+            if not self.token.running:
+                break
             if self.shift:
-                row[0] = ntplib.system_to_ntp_time(t0 + float(row[1])/10**3)
+                row[0] = ntplib.system_to_ntp_time(t0 + float(row[1])/1000.0)
             row_conv = [ osc.TimeTagArgument(float(row[0]))] + [osc.IntArgument(int(a)) for a in row[1:]]
-            #time.sleep((row_conv[1].value-tc)/10**3)
-            time.sleep(0.1)
-            #tc = row_conv[1].value
+            #time.sleep((row_conv[1].value-tc)/1000.0)
+            sleep_time = t0+float(row[1])/1000.0-time.time()
+            if sleep_time > 0:
+                time.sleep(sleep_time)
+            #time.sleep(0.1)
+            tc = row_conv[1].value
             self._send(osc.Message(self.address,*row_conv))
         print("Goodbye.")
         reactor.callLater(0.1, reactor.stop)
 
+class Token(object):
+    def __init__(self):
+        self.running = True
+
 if __name__ == "__main__":
 
+    token = Token()
+
     parser = argparse.ArgumentParser(description='Simulate an (osc) pianoroll client.')
     parser.add_argument('datafile', metavar='DATAFILE', help='The file containing the pianoroll data (CSV).')
     parser.add_argument('-e', '--event', dest='event', metavar='EVENT', required=True, help='the event code.')
@@ -56,8 +70,16 @@
 
     args = parser.parse_args()
 
+    def customHandler(signum, _):
+        print("Got signal: %s" % signum)
+        token.running = False
+        if reactor.running:
+            reactor.callFromThread(reactor.stop) # to stop twisted code when in the reactor loop
+    signal.signal(signal.SIGINT, customHandler)
+
+
     with open(args.datafile, 'rU') as datafile:
         reader = csv.reader(datafile, delimiter=' ')
-        app = UDPSenderApplication(9090, "127.0.0.1", "/pianoroll/%s/" % args.event, list(reader), args.shift)
+        app = UDPSenderApplication(9090, "127.0.0.1", "/pianoroll/%s/" % args.event, list(reader), args.shift, token)
 
     reactor.run()