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

index.js 10KB

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