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

index.js 7.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. var d3 = require("d3"),
  2. $ = require("jquery"),
  3. preview = require("./preview.js"),
  4. video = require("./video.js"),
  5. audio = require("./audio.js"),
  6. editorEditor = require("./theme-editor.js"),
  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. if (location.pathname === '/theme') {
  33. editorEditor.initialize();
  34. }
  35. });
  36. function submitted() {
  37. d3.event.preventDefault();
  38. var theme = preview.theme(),
  39. caption = preview.caption(),
  40. selection = preview.selection(),
  41. file = preview.file(),
  42. subtitle = preview.subtitle();
  43. if (!file) {
  44. d3.select("#row-audio").classed("error", true);
  45. return setClass("error", "No audio file selected.");
  46. }
  47. if (theme.maxDuration && selection.duration > theme.maxDuration) {
  48. return setClass("error", "Your Audiogram must be under " + theme.maxDuration + " seconds.");
  49. }
  50. if (!theme || !theme.width || !theme.height) {
  51. return setClass("error", "No valid theme detected.");
  52. }
  53. video.kill();
  54. audio.pause();
  55. var formData = new FormData();
  56. formData.append("audio", file);
  57. if (selection.start || selection.end) {
  58. formData.append("start", selection.start);
  59. formData.append("end", selection.end);
  60. }
  61. formData.append("theme", JSON.stringify($.extend({}, theme, { backgroundImageFile: null })));
  62. formData.append("caption", caption);
  63. if (subtitle) {
  64. formData.append("subtitle", subtitle);
  65. }
  66. setClass("loading");
  67. d3.select("#loading-message").text("Uploading audio...");
  68. $.ajax({
  69. url: "/submit/",
  70. type: "POST",
  71. data: formData,
  72. contentType: false,
  73. dataType: "json",
  74. cache: false,
  75. processData: false,
  76. success: function (res) {
  77. poll(res.id, 0);
  78. },
  79. error: function (err) {
  80. error(err)
  81. }
  82. });
  83. }
  84. function poll(id) {
  85. setTimeout(function(){
  86. $.ajax({
  87. url: "/status/" + id + "/",
  88. error: error,
  89. dataType: "json",
  90. success: function(result){
  91. if (result && result.status && result.status === "ready" && result.url) {
  92. video.update(result.url, preview.theme().name);
  93. setClass("rendered");
  94. } else if (result.status === "error") {
  95. error(result.error);
  96. } else {
  97. if (result !== 'unknown') {
  98. d3.select("#loading-message").text(statusMessage(result));
  99. }
  100. poll(id);
  101. }
  102. }
  103. });
  104. }, 2500);
  105. }
  106. function error(msg) {
  107. if (msg.responseText) {
  108. msg = msg.responseText;
  109. }
  110. if (typeof msg !== "string") {
  111. msg = JSON.stringify(msg);
  112. }
  113. if (!msg) {
  114. msg = "Unknown error";
  115. }
  116. d3.select("#loading-message").text("Loading...");
  117. setClass("error", msg);
  118. }
  119. // Once images are downloaded, set up listeners
  120. function initialize(err, themesWithImages) {
  121. // Populate dropdown menu
  122. d3.select("#input-theme")
  123. .on("change", updateTheme)
  124. .selectAll("option")
  125. .data(themesWithImages)
  126. .enter()
  127. .append("option")
  128. .text(function(d){
  129. return d.name;
  130. });
  131. // Get initial theme
  132. d3.select("#input-theme").each(updateTheme);
  133. // Get initial caption (e.g. back button)
  134. d3.select("#input-caption").on("change keyup", updateCaption).each(updateCaption);
  135. // Space bar listener for audio play/pause
  136. d3.select(document).on("keypress", function(){
  137. if (!d3.select("body").classed("rendered") && d3.event.key === " " && !d3.matcher("input, textarea, button, select").call(d3.event.target)) {
  138. audio.toggle();
  139. }
  140. });
  141. // Button listeners
  142. d3.selectAll("#play, #pause").on("click", function(){
  143. d3.event.preventDefault();
  144. audio.toggle();
  145. });
  146. d3.select("#restart").on("click", function(){
  147. d3.event.preventDefault();
  148. audio.restart();
  149. });
  150. // If there's an initial piece of audio (e.g. back button) load it
  151. d3.select("#input-audio").on("change", updateAudioFile).each(updateAudioFile);
  152. d3.select("#return").on("click", function(){
  153. d3.event.preventDefault();
  154. video.kill();
  155. setClass(null);
  156. });
  157. d3.select("#input-subtitle").on("change", updateSubtitleFile).each(updateSubtitleFile);
  158. d3.select("#submit").on("click", submitted);
  159. }
  160. function updateAudioFile() {
  161. d3.select("#row-audio").classed("error", false);
  162. audio.pause();
  163. video.kill();
  164. // Skip if empty
  165. if (!this.files || !this.files[0]) {
  166. d3.select("#minimap").classed("hidden", true);
  167. preview.file(null);
  168. setClass(null);
  169. return true;
  170. }
  171. d3.select("#loading-message").text("Analyzing...");
  172. setClass("loading");
  173. const audioFile = this.files[0];
  174. preview.loadAudio(audioFile, function(err){
  175. if (err) {
  176. d3.select("#row-audio").classed("error", true);
  177. setClass("error", "Error decoding audio file");
  178. } else {
  179. setClass(null);
  180. }
  181. d3.selectAll("#minimap, #submit").classed("hidden", !!err);
  182. });
  183. }
  184. function updateSubtitleFile() {
  185. if (!this.files || !this.files[0]) {
  186. preview.subtitle(null);
  187. setClass(null);
  188. return true;
  189. }
  190. subtitle = this.files[0];
  191. preview.loadSubtitle(subtitle, function (err) {
  192. if (err) {
  193. setClass("error", "Error during loading subtitle file");
  194. } else {
  195. setClass(null);
  196. }
  197. });
  198. }
  199. function updateCaption() {
  200. preview.caption(this.value);
  201. }
  202. function updateTheme() {
  203. preview.theme(d3.select(this.options[this.selectedIndex]).datum());
  204. }
  205. function preloadImages(themes) {
  206. // preload images
  207. var imageQueue = d3.queue();
  208. d3.entries(themes).forEach(function(theme){
  209. if (!theme.value.name) {
  210. theme.value.name = theme.key;
  211. }
  212. if (theme.key !== "default") {
  213. imageQueue.defer(getImage, theme.value);
  214. }
  215. });
  216. imageQueue.awaitAll(initialize);
  217. function getImage(theme, cb) {
  218. if (!theme.backgroundImage) {
  219. return cb(null, theme);
  220. }
  221. theme.backgroundImageFile = new Image();
  222. theme.backgroundImageFile.onload = function(){
  223. return cb(null, theme);
  224. };
  225. theme.backgroundImageFile.onerror = function(e){
  226. console.warn(e);
  227. return cb(null, theme);
  228. };
  229. theme.backgroundImageFile.src = "/settings/backgrounds/" + theme.backgroundImage;
  230. }
  231. }
  232. function setClass(cl, msg) {
  233. d3.select("body").attr("class", cl || null);
  234. d3.select("#error").text(msg || "");
  235. }
  236. function statusMessage(result) {
  237. switch (result.status) {
  238. case "queued":
  239. return "Waiting for other jobs to finish, #" + (result.position + 1) + " in queue";
  240. case "audio-download":
  241. return "Downloading audio for processing";
  242. case "trim":
  243. return "Trimming audio";
  244. case "probing":
  245. return "Probing audio file";
  246. case "waveform":
  247. return "Analyzing waveform";
  248. case "renderer":
  249. return "Initializing renderer";
  250. case "frames":
  251. var msg = "Generating frames";
  252. if (result.numFrames) {
  253. msg += ", " + Math.round(100 * (result.framesComplete || 0) / result.numFrames) + "% complete";
  254. }
  255. return msg;
  256. case "combine":
  257. return "Combining frames with audio (it can take a while)";
  258. case "ready":
  259. return "Cleaning up";
  260. default:
  261. return JSON.stringify(result);
  262. }
  263. }