osc-parser.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. // OSC parsing based on node-osc
  2. module.exports = (function() {
  3. var jspack = require("jspack").jspack,
  4. decode = function(data) {
  5. var message = [],
  6. address = decodeString(data);
  7. data = address.data;
  8. if (address.value === "#bundle") {
  9. data = decodeBundle(data, message);
  10. } else if (data.length > 0) {
  11. data = decodeMessage(address, data, message);
  12. }
  13. return message;
  14. },
  15. decodeBundle = function(data, message) {
  16. var time = decodeTime(data),
  17. bundleSize,
  18. content;
  19. data = time.data;
  20. message.push("#bundle");
  21. message.push(time.value);
  22. while (data.length > 0) {
  23. bundleSize = decodeInt(data);
  24. data = bundleSize.data;
  25. content = data.slice(0, bundleSize.value);
  26. message.push(decode(content));
  27. data = data.slice(bundleSize.value, data.length);
  28. }
  29. return data;
  30. },
  31. decodeMessage = function(address, data, message) {
  32. message.push(address.value);
  33. var typeTags = decodeString(data);
  34. data = typeTags.data;
  35. typeTags = typeTags.value;
  36. if (typeTags[0] === ",") {
  37. for (var i = 1; i < typeTags.length; i++) {
  38. var arg = decodeByTypeTag(typeTags[i], data);
  39. data = arg.data;
  40. message.push(arg.value);
  41. }
  42. }
  43. return data;
  44. },
  45. decodeByTypeTag = function(typeTag, data) {
  46. switch (typeTag) {
  47. case "i":
  48. return decodeInt(data);
  49. case "f":
  50. return decodeFloat(data);
  51. case "s":
  52. return decodeString(data);
  53. }
  54. },
  55. decodeInt = function(data) {
  56. return {
  57. value: jspack.Unpack(">i", data.slice(0, 4))[0],
  58. data: data.slice(4)
  59. };
  60. },
  61. decodeString = function(data) {
  62. var end = 0;
  63. while (data[end] && end < data.length) {
  64. end++;
  65. }
  66. return {
  67. value: data.toString("ascii", 0, end),
  68. data: data.slice(Math.ceil((end + 1) / 4) * 4)
  69. };
  70. },
  71. decodeFloat = function(data) {
  72. return {
  73. value: jspack.Unpack(">f", data.slice(0, 4))[0],
  74. data: data.slice(4)
  75. };
  76. },
  77. decodeTime = function(data) {
  78. var time = jspack.Unpack(">LL", data.slice(0, 8)),
  79. seconds = time[0],
  80. fraction = time[1];
  81. return {
  82. value: seconds + fraction / 4294967296,
  83. data: data.slice(8)
  84. };
  85. };
  86. return {
  87. decode: decode
  88. };
  89. }());