Turn audio into a shareable video. forked from nypublicradio/audiogram

index.js 9.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. var d3 = require("d3"),
  2. $ = require("jquery"),
  3. preview = require("./preview.js"),
  4. video = require("./video.js"),
  5. audio = require("./audio.js"),
  6. newTheme = null;
  7. d3.json("/settings/themes.json", function(err, themes){
  8. var errorMessage;
  9. // Themes are missing or invalid
  10. if (err || !d3.keys(themes).filter(function(d){ return d !== "default"; }).length) {
  11. if (err instanceof SyntaxError) {
  12. errorMessage = "Error in settings/themes.json:<br/><code>" + err.toString() + "</code>";
  13. } else if (err instanceof ProgressEvent) {
  14. errorMessage = "Error: no settings/themes.json.";
  15. } else if (err) {
  16. errorMessage = "Error: couldn't load settings/themes.json.";
  17. } else {
  18. errorMessage = "No themes found in settings/themes.json.";
  19. }
  20. d3.select("#loading-bars").remove();
  21. d3.select("#loading-message").html(errorMessage);
  22. if (err) {
  23. throw err;
  24. }
  25. return;
  26. }
  27. for (var key in themes) {
  28. themes[key] = $.extend({}, themes.default, themes[key]);
  29. }
  30. preloadImages(themes);
  31. });
  32. function submitted() {
  33. d3.event.preventDefault();
  34. var theme = preview.theme(),
  35. caption = preview.caption(),
  36. selection = preview.selection(),
  37. file = preview.file();
  38. if (!file) {
  39. d3.select("#row-audio").classed("error", true);
  40. return setClass("error", "No audio file selected.");
  41. }
  42. if (theme.maxDuration && selection.duration > theme.maxDuration) {
  43. return setClass("error", "Your Audiogram must be under " + theme.maxDuration + " seconds.");
  44. }
  45. if (!theme || !theme.width || !theme.height) {
  46. return setClass("error", "No valid theme detected.");
  47. }
  48. video.kill();
  49. audio.pause();
  50. var formData = new FormData();
  51. formData.append("audio", file);
  52. if (selection.start || selection.end) {
  53. formData.append("start", selection.start);
  54. formData.append("end", selection.end);
  55. }
  56. formData.append("theme", JSON.stringify($.extend({}, theme, { backgroundImageFile: null })));
  57. formData.append("caption", caption);
  58. setClass("loading");
  59. d3.select("#loading-message").text("Uploading audio...");
  60. $.ajax({
  61. url: "/submit/",
  62. type: "POST",
  63. data: formData,
  64. contentType: false,
  65. dataType: "json",
  66. cache: false,
  67. processData: false,
  68. success: function(data){
  69. poll(data.id, 0);
  70. },
  71. error: error
  72. });
  73. }
  74. function uploadTheme() {
  75. var formData = new FormData();
  76. var file = preview.newTheme();
  77. formData.append("newTheme", file);
  78. var newCaption = preview.newCaption();
  79. console.log('new theme', newCaption);
  80. formData.append("newCaption", newCaption);
  81. console.log(formData);
  82. $.ajax({
  83. url: "/theme/upload",
  84. type: "POST",
  85. data: formData,
  86. contentType: false,
  87. cache: false,
  88. processData: false,
  89. success: function () {
  90. d3.json("/settings/themes.json", function(err, themes){
  91. var errorMessage;
  92. // Themes are missing or invalid
  93. if (err || !d3.keys(themes).filter(function(d){ return d !== "default"; }).length) {
  94. if (err instanceof SyntaxError) {
  95. errorMessage = "Error in settings/themes.json:<br/><code>" + err.toString() + "</code>";
  96. } else if (err instanceof ProgressEvent) {
  97. errorMessage = "Error: no settings/themes.json.";
  98. } else if (err) {
  99. errorMessage = "Error: couldn't load settings/themes.json.";
  100. } else {
  101. errorMessage = "No themes found in settings/themes.json.";
  102. }
  103. d3.select("#loading-bars").remove();
  104. d3.select("#loading-message").html(errorMessage);
  105. if (err) {
  106. throw err;
  107. }
  108. return;
  109. }
  110. for (var key in themes) {
  111. themes[key] = $.extend({}, themes.default, themes[key]);
  112. }
  113. preloadImages(themes);
  114. d3.select("#input-theme")
  115. .selectAll("option")
  116. .each(function (d) {
  117. if (d.name === newCaption) {
  118. this["selected"] = "selected";
  119. d3.select("#input-new-theme").property("value", "");
  120. d3.select("#input-new-caption").property("value", "");
  121. return;
  122. }
  123. });
  124. });
  125. },
  126. error: function (error) {
  127. console.log('error', error);
  128. }
  129. });
  130. }
  131. function poll(id) {
  132. setTimeout(function(){
  133. $.ajax({
  134. url: "/status/" + id + "/",
  135. error: error,
  136. dataType: "json",
  137. success: function(result){
  138. if (result && result.status && result.status === "ready" && result.url) {
  139. video.update(result.url, preview.theme().name);
  140. setClass("rendered");
  141. } else if (result.status === "error") {
  142. error(result.error);
  143. } else {
  144. d3.select("#loading-message").text(statusMessage(result));
  145. poll(id);
  146. }
  147. }
  148. });
  149. }, 2500);
  150. }
  151. function error(msg) {
  152. if (msg.responseText) {
  153. msg = msg.responseText;
  154. }
  155. if (typeof msg !== "string") {
  156. msg = JSON.stringify(msg);
  157. }
  158. if (!msg) {
  159. msg = "Unknown error";
  160. }
  161. d3.select("#loading-message").text("Loading...");
  162. setClass("error", msg);
  163. }
  164. // Once images are downloaded, set up listeners
  165. function initialize(err, themesWithImages) {
  166. // Populate dropdown menu
  167. d3.select("#input-theme")
  168. .on("change", updateTheme)
  169. .selectAll("option")
  170. .data(themesWithImages)
  171. .enter()
  172. .append("option")
  173. .text(function(d){
  174. return d.name;
  175. });
  176. // Get initial theme
  177. d3.select("#input-theme").each(updateTheme);
  178. // Get initial caption (e.g. back button)
  179. d3.select("#input-caption").on("change keyup", updateCaption).each(updateCaption);
  180. // Space bar listener for audio play/pause
  181. d3.select(document).on("keypress", function(){
  182. if (!d3.select("body").classed("rendered") && d3.event.key === " " && !d3.matcher("input, textarea, button, select").call(d3.event.target)) {
  183. audio.toggle();
  184. }
  185. });
  186. // Button listeners
  187. d3.selectAll("#play, #pause").on("click", function(){
  188. d3.event.preventDefault();
  189. audio.toggle();
  190. });
  191. d3.select("#restart").on("click", function(){
  192. d3.event.preventDefault();
  193. audio.restart();
  194. });
  195. // If there's an initial piece of audio (e.g. back button) load it
  196. d3.select("#input-audio").on("change", updateAudioFile).each(updateAudioFile);
  197. d3.select("#return").on("click", function(){
  198. d3.event.preventDefault();
  199. video.kill();
  200. setClass(null);
  201. });
  202. d3.select("#btn-new-theme").on("click", uploadTheme);
  203. d3.select("#input-new-theme").on("change", updateNewThemeFile).each(updateNewThemeFile);
  204. d3.select("#input-new-caption").on("change keyup", updateNewCaption).each(updateNewCaption);
  205. d3.select("#submit").on("click", submitted);
  206. }
  207. function updateAudioFile() {
  208. d3.select("#row-audio").classed("error", false);
  209. audio.pause();
  210. video.kill();
  211. // Skip if empty
  212. if (!this.files || !this.files[0]) {
  213. d3.select("#minimap").classed("hidden", true);
  214. preview.file(null);
  215. setClass(null);
  216. return true;
  217. }
  218. d3.select("#loading-message").text("Analyzing...");
  219. setClass("loading");
  220. preview.loadAudio(this.files[0], function(err){
  221. if (err) {
  222. d3.select("#row-audio").classed("error", true);
  223. setClass("error", "Error decoding audio file");
  224. } else {
  225. setClass(null);
  226. }
  227. d3.selectAll("#minimap, #submit").classed("hidden", !!err);
  228. });
  229. }
  230. function updateNewThemeFile() {
  231. if (!this.files || !this.files[0]) {
  232. preview.newTheme(null);
  233. return true;
  234. }
  235. newTheme = this.files[0];
  236. preview.loadNewTheme(newTheme, function (err) {
  237. if (err) {
  238. setClass("error", "Error updating new theme file");
  239. } else {
  240. setClass(null);
  241. }
  242. });
  243. }
  244. function updateCaption() {
  245. preview.caption(this.value);
  246. }
  247. function updateTheme() {
  248. preview.theme(d3.select(this.options[this.selectedIndex]).datum());
  249. }
  250. function updateNewCaption() {
  251. preview.newCaption(this.value);
  252. }
  253. function preloadImages(themes) {
  254. // preload images
  255. var imageQueue = d3.queue();
  256. d3.entries(themes).forEach(function(theme){
  257. if (!theme.value.name) {
  258. theme.value.name = theme.key;
  259. }
  260. if (theme.key !== "default") {
  261. imageQueue.defer(getImage, theme.value);
  262. }
  263. });
  264. imageQueue.awaitAll(initialize);
  265. function getImage(theme, cb) {
  266. if (!theme.backgroundImage) {
  267. return cb(null, theme);
  268. }
  269. theme.backgroundImageFile = new Image();
  270. theme.backgroundImageFile.onload = function(){
  271. return cb(null, theme);
  272. };
  273. theme.backgroundImageFile.onerror = function(e){
  274. console.warn(e);
  275. return cb(null, theme);
  276. };
  277. theme.backgroundImageFile.src = "/settings/backgrounds/" + theme.backgroundImage;
  278. }
  279. }
  280. function setClass(cl, msg) {
  281. d3.select("body").attr("class", cl || null);
  282. d3.select("#error").text(msg || "");
  283. }
  284. function statusMessage(result) {
  285. switch (result.status) {
  286. case "queued":
  287. return "Waiting for other jobs to finish, #" + (result.position + 1) + " in queue";
  288. case "audio-download":
  289. return "Downloading audio for processing";
  290. case "trim":
  291. return "Trimming audio";
  292. case "probing":
  293. return "Probing audio file";
  294. case "waveform":
  295. return "Analyzing waveform";
  296. case "renderer":
  297. return "Initializing renderer";
  298. case "frames":
  299. var msg = "Generating frames";
  300. if (result.numFrames) {
  301. msg += ", " + Math.round(100 * (result.framesComplete || 0) / result.numFrames) + "% complete";
  302. }
  303. return msg;
  304. case "combine":
  305. return "Combining frames with audio";
  306. case "ready":
  307. return "Cleaning up";
  308. default:
  309. return JSON.stringify(result);
  310. }
  311. }